code
stringlengths
2
1.05M
/*(function () { 'use strict'; angular .module('logs') .run(menuConfig); menuConfig.$inject = ['Menus']; function menuConfig(Menus) { Menus.addMenuItem('topbar', { title: 'Log', state: 'logs', type: 'dropdown', roles: ['admin', 'user'] }); // Add the dropdown create item Menus.addSubMenuItem('topbar', 'logs', { title: 'Criar log', state: 'logs.create', roles: ['admin'] }); // Add the dropdown list item Menus.addSubMenuItem('topbar', 'logs', { title: 'Listar logs', state: 'logs.list' }); // Add the dropdown list autenticacao item Menus.addSubMenuItem('topbar', 'logs', { title: 'Listar logs de autenticação', state: 'logs.list-autenticacao' }); // Add the dropdown list evento item Menus.addSubMenuItem('topbar', 'logs', { title: 'Listar logs de eventos', state: 'logs.list-eventos' }); // Add the dropdown list firewall item Menus.addSubMenuItem('topbar', 'logs', { title: 'Listar logs de firewall', state: 'logs.list-firewall' }); // Add the dropdown list mrtg item Menus.addSubMenuItem('topbar', 'logs', { title: 'Listar logs de mrtg', state: 'logs.list-mrtg' }); // Add the dropdown list mrtg item Menus.addSubMenuItem('topbar', 'logs', { title: 'Listar logs de sarg', state: 'logs.list-sarg' }); } })(); */
var assert = require('assert'); var getMyIp = require('../dist/') describe('This project', function (done) { it('can get IP and clean context', function (done) { getMyIp(function (err, data) { assert.ok(typeof data === 'string') assert.ok(typeof returnCitySN === 'undefined') done() }) }) it('can get IP and revert context', function (done) { returnCitySN = 1 getMyIp(function (err, data) { assert.ok(typeof data === 'string') assert.equal(returnCitySN, 1) done() }) }) })
import ButtonGroup from './components/button-group' import Button from './components/button' import Link from './components/link' import Icon from './components/icon' import Field from './components/field' import Input from './components/input' import InputGroup from './components/input-group' import Radio from './components/radio' import RadioGroup from './components/radio-group' import Switch from './components/switch' import Checkbox from './components/checkbox' import CheckboxGroup from './components/checkbox-group' import Addon from './components/addon' import Label from './components/label' import Dropdown from './components/dropdown' import Menu from './components/menu' import Popover from './components/popover' import Card from './components/card' const components = { ButtonGroup, Button, Link, Icon, Field, Input, InputGroup, Radio, RadioGroup, Switch, Checkbox, CheckboxGroup, Addon, Label, Dropdown, Menu, Popover, Card } components.install = (Vue, options = {}) => { for (const componentName in components) { const component = components[componentName]; if (component && componentName !== 'install') { Vue.component(component.name, component); } } } export default components
import builtin from './builtin.js'; const universal = [ builtin // TODO: Add types that are de-facto universal even though not // built-in into ecmasript standard. ]; export default universal;
var assert = require('assert'); var nock = require('nock'); var streamSpec = require('stream-spec'); var rssParser = require('../lib/rss-parser'); describe('RSS parser module', function () { it('should return a readable stream', function () { streamSpec(rssParser([], false)) .readable() .pausable({strict: true}) .validateOnExit(); }); it('should request the feeds provided', function (done) { var feeds = [ nock('http://tapir.com').get('/rss').reply(200), nock('http://badger.com').get('/xml').reply(200), ]; rssParser(['http://tapir.com/rss', 'http://badger.com/xml'], false) .on('data', function () { // Prompts the stream to output data }) .on('end', function () { feeds.forEach(function (feed) { assert(feed.isDone(), 'URL was not visited'); }); done(); }); }); it('should parse and stream items from a feed', function (done) { nock('http://badger.com') .get('/xml') .replyWithFile(200, __dirname + '/fixtures/rss.xml'); var expected = ['Title one', 'Title two', 'Title three']; var items = []; rssParser(['http://badger.com/xml'], false) .on('data', function (data) { items.push(data); }) .on('end', function () { var titles = items.map(function(item) { return item.title; }) assert.deepEqual(titles, expected); done(); }); }); it('should parse and stream items from multiple feeds', function (done) { nock('http://tapir.com') .get('/rss') .delay(100) .replyWithFile(200, __dirname + '/fixtures/rss.xml'); nock('http://badger.com') .get('/xml') .replyWithFile(200, __dirname + '/fixtures/rss2.xml'); var expected = ['Title A','Title B','Title C','Title one','Title two','Title three']; var items = []; rssParser(['http://tapir.com/rss', 'http://badger.com/xml'], false) .on('data', function (data) { items.push(data); }) .on('end', function () { var titles = items.map(function(item) { return item.title; }); assert.deepEqual(titles, expected); done(); }); }); it('should parse and stream items up to the specified limit', function (done) { nock('http://tapir.com') .get('/rss') .delay(100) .replyWithFile(200, __dirname + '/fixtures/rss.xml'); nock('http://badger.com') .get('/xml') .delay(150) .replyWithFile(200, __dirname + '/fixtures/rss2.xml'); var expected = ['Title one', 'Title A']; var items = []; rssParser(['http://tapir.com/rss', 'http://badger.com/xml'], 1) .on('data', function (data) { items.push(data); }) .on('end', function () { var titles = items.map(function(item) { return item.title; }); assert.deepEqual(titles, expected); done(); }); }); });
var searchData= [ ['initializecomponent',['InitializeComponent',['../class_a_c_h_clerk_1_1_about_pane.html#ac6bf4799d9b4c90f779b9fd654bcd8a9',1,'ACHClerk.AboutPane.InitializeComponent()'],['../class_a_c_h_clerk_1_1_clerk_form.html#a912757e423567686856960486ac9edaa',1,'ACHClerk.ClerkForm.InitializeComponent()'],['../class_a_c_h_clerk_1_1_preview_pane_form.html#a30703e54fcdd8320c58533582585ecd1',1,'ACHClerk.PreviewPaneForm.InitializeComponent()'],['../class_a_c_h_clerk_1_1_save_folder_diag.html#a0623e918a21b3723a2e5043a2be9bac7',1,'ACHClerk.SaveFolderDiag.InitializeComponent()']]] ];
require(['jquery', 'fuelux'], function($){ $('a.checkbox').click(function(event){ if($(this).hasClass('active')) { $(this).removeClass('active'); $('input[name="'+this.id+'"]').prop('checked', false); $('input[name="'+this.id+'"]').checkbox('uncheck'); } else { $(this).addClass('active'); $('input[name="'+this.id+'"]').prop('checked', true); $('input[name="'+this.id+'"]').checkbox('check'); } }) });
var express = require('express') , app = express() var pointlessFormTemplate = '<html><body><form method="POST" action="/admin/users"><label>foo</label><input type="text" name="foo" value="bar"><button type="submit">Submit</button></body></html>' function genericRoute(req,res) { var strToSend = '[' + req.method + '] You hit: ' + req.path + '. We just wanted to let you know, in case you didn\'t believe your URL bar' if (req.body) { strToSend += '<p>You also had this request body: ' + require('util').inspect(req.body) } res.send(strToSend) } function formRoute(req,res) { res.send(pointlessFormTemplate) } function ensureAdmin(req,res,next) { console.log('Gee, I sure hope that was an admin!') next() } function ensureUser(req,res,next) { console.log('Well, the user *claims* to have logged in...') next() } var bodyParser = require('body-parser') app.use(bodyParser.urlencoded({extended:false})) app.get('/admin*', ensureAdmin) app.get('/admin/users', formRoute) app.post('/admin/users', genericRoute) app.get('/admin/accounts`', genericRoute) app.get('/admin/transactions', genericRoute) app.get('/auth/sign_in', genericRoute) app.get('/auth/sign_out', genericRoute) app.get('/auth/register', genericRoute) app.get('/app/widgets', genericRoute) app.get('/app/tasks', genericRoute) app.listen(3000) console.log("I'm listening on port 3000!")
const chai = require('chai'); const expect = require('expect.js'); const { RelationExpression } = require('../../../'); describe('RelationExpression', () => { describe('parse', () => { it('empty expression', () => { testParse('', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, }); testParse( {}, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, } ); }); it('non-string', () => { let expectedResult = { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, }; testParse(null, expectedResult); testParse(false, expectedResult); testParse(true, expectedResult); testParse(1, expectedResult); testParse({}, expectedResult); testParse([], expectedResult); }); describe('single relation', () => { it('single relation', () => { testParse('a', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, }); testParse( { a: {}, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, } ); }); it('list with one value', () => { testParse('[a]', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, }); }); it('weird characters', () => { testParse('_-%§$?+1Aa!€^', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, '_-%§$?+1Aa!€^': { $name: '_-%§$?+1Aa!€^', $relation: '_-%§$?+1Aa!€^', $modify: [], $recursive: false, $allRecursive: false, }, }); }); }); describe('nested relations', () => { it('one level', () => { testParse('a.b', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, }, }); }); it('two levels', () => { testParse('a.b.c', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, }, }, }); testParse( { a: { b: { c: {}, }, }, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, }, }, } ); }); }); it('multiple relations', () => { testParse('[a, b, c]', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, }); testParse( { a: true, b: {}, c: true, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, } ); }); it('multiple nested relations', () => { testParse('[a.b, c.d.e, f]', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, }, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, d: { $name: 'd', $relation: 'd', $modify: [], $recursive: false, $allRecursive: false, e: { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, }, }, }, f: { $name: 'f', $relation: 'f', $modify: [], $recursive: false, $allRecursive: false, }, }); testParse( { a: { b: true, }, c: { d: { e: {}, }, }, f: {}, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, }, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, d: { $name: 'd', $relation: 'd', $modify: [], $recursive: false, $allRecursive: false, e: { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, }, }, }, f: { $name: 'f', $relation: 'f', $modify: [], $recursive: false, $allRecursive: false, }, } ); }); it('deep nesting and nested lists', () => { testParse('[a.[b, c.[d, e.f]], g]', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, d: { $name: 'd', $relation: 'd', $modify: [], $recursive: false, $allRecursive: false, }, e: { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, f: { $name: 'f', $relation: 'f', $modify: [], $recursive: false, $allRecursive: false, }, }, }, }, g: { $name: 'g', $relation: 'g', $modify: [], $recursive: false, $allRecursive: false, }, }); }); it('arguments', () => { testParse('[a(arg1,arg2,arg3), b(arg4) . [c(), d(arg5 arg6), e]]', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: ['arg1', 'arg2', 'arg3'], $recursive: false, $allRecursive: false, }, b: { $name: 'b', $relation: 'b', $modify: ['arg4'], $recursive: false, $allRecursive: false, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, d: { $name: 'd', $relation: 'd', $modify: ['arg5', 'arg6'], $recursive: false, $allRecursive: false, }, e: { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, }, }, }); testParse( { a: { $modify: ['arg1', 'arg2', 'arg3'], }, b: { $modify: ['arg4'], c: true, d: { $modify: ['arg5', 'arg6'], }, e: {}, }, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: ['arg1', 'arg2', 'arg3'], $recursive: false, $allRecursive: false, }, b: { $name: 'b', $relation: 'b', $modify: ['arg4'], $recursive: false, $allRecursive: false, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, d: { $name: 'd', $relation: 'd', $modify: ['arg5', 'arg6'], $recursive: false, $allRecursive: false, }, e: { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, }, }, } ); testParse('a(f1).b(^f2, ^f3)', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: ['f1'], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: ['^f2', '^f3'], $recursive: false, $allRecursive: false, }, }, }); }); it('alias', () => { testParse('a as b', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, }); testParse( { b: { $relation: 'a', }, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, } ); testParse('aasb', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, aasb: { $name: 'aasb', $relation: 'aasb', $modify: [], $recursive: false, $allRecursive: false, }, }); testParse('[ as , b]', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, as: { $name: 'as', $relation: 'as', $modify: [], $recursive: false, $allRecursive: false, }, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, }); testParse( `a as aa.[ b as bb, c as cc ]`, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, aa: { $name: 'aa', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, bb: { $name: 'bb', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, cc: { $name: 'cc', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, }, } ); testParse( `a(f1, f2) as aa . [ c(f3, f4) as cc, b as bb .[ e, f as ff ] ]`, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, aa: { $name: 'aa', $relation: 'a', $modify: ['f1', 'f2'], $recursive: false, $allRecursive: false, cc: { $name: 'cc', $relation: 'c', $modify: ['f3', 'f4'], $recursive: false, $allRecursive: false, }, bb: { $name: 'bb', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, e: { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, }, ff: { $name: 'ff', $relation: 'f', $modify: [], $recursive: false, $allRecursive: false, }, }, }, } ); }); it('should ignore whitespace', () => { testParse( '\n\r\t [ a (\narg1\n arg2,arg3), \n \n b\n(arg4) . [c(), \td (arg5 arg6), e] \r] ', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: ['arg1', 'arg2', 'arg3'], $recursive: false, $allRecursive: false, }, b: { $name: 'b', $relation: 'b', $modify: ['arg4'], $recursive: false, $allRecursive: false, c: { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, d: { $name: 'd', $relation: 'd', $modify: ['arg5', 'arg6'], $recursive: false, $allRecursive: false, }, e: { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, }, }, } ); }); it('should throw with invalid input', () => { testParseFail('.'); testParseFail('..'); testParseFail('a.'); testParseFail('.a'); testParseFail('['); testParseFail(']'); testParseFail('[[]]'); testParseFail('[a'); testParseFail('a]'); testParseFail('[a.]'); testParseFail('a.[b]]'); testParseFail('a.[.]'); testParseFail('a.[.b]'); testParseFail('[a,,b]'); // Alias tests testParseFail('a asb'); testParseFail('aas b'); testParseFail('a asd b'); // TODO: enable for v2.0. // testParseFail('[a.b, a.c]'); // testParseFail('a.[b.c, b.d]'); }); it('should accept single function or modifier name in $modifiers', () => { const modifier = () => {}; testParse( { a: { $modify: modifier, }, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: [modifier], $recursive: false, $allRecursive: false, }, } ); testParse( { a: { $modify: 'someModifier', }, }, { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'a', $modify: ['someModifier'], $recursive: false, $allRecursive: false, }, } ); }); }); it('clone', () => { testClone('[aaa as a . bbb as b.^, c(f)]', { $name: null, $relation: null, $modify: [], $recursive: false, $allRecursive: false, a: { $name: 'a', $relation: 'aaa', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'bbb', $modify: [], $recursive: true, $allRecursive: false, }, }, c: { $name: 'c', $relation: 'c', $modify: ['f'], $recursive: false, $allRecursive: false, }, }); }); describe('#expressionsAtPath', () => { it('a from a', () => { testPath('a', 'a', [ { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, ]); }); it('a from a.a', () => { testPath('a.b', 'a', [ { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, b: { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, }, ]); }); it('a.b from a', () => { testPath('a', 'a.b', []); }); it('a.b from a.b', () => { testPath('a.b', 'a.b', [ { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, ]); }); it('a.b from a.[b, c]', () => { testPath('a.[b, c]', 'a.b', [ { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, ]); }); it('a.[b, c] from a.[b, c]', () => { testPath('a.[b, c]', 'a.[b, c]', [ { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, { $name: 'c', $relation: 'c', $modify: [], $recursive: false, $allRecursive: false, }, ]); }); it('a.[b, d] from a.[b, c]', () => { testPath('a.[b, c]', 'a.[b, d]', [ { $name: 'b', $relation: 'b', $modify: [], $recursive: false, $allRecursive: false, }, ]); }); it('[a, b.c.d.[e, f]] from [a, b.[g, c.[d.[e, f], i], h]]', () => { testPath('[a, b.[g, c.[d.[e, f], i], h]]', '[a, b.c.d.[e, f]]', [ { $name: 'a', $relation: 'a', $modify: [], $recursive: false, $allRecursive: false, }, { $name: 'e', $relation: 'e', $modify: [], $recursive: false, $allRecursive: false, }, { $name: 'f', $relation: 'f', $modify: [], $recursive: false, $allRecursive: false, }, ]); }); it('b.c.d.[e, f] from [a, b.[g, c.[d.[e(a1), f(a2)], i], h]]', () => { testPath('[a, b.[g, c.[d.[e(a1), f(a2)], i], h]]', 'b.c.d.[e, f]', [ { $name: 'e', $relation: 'e', $modify: ['a1'], $recursive: false, $allRecursive: false, }, { $name: 'f', $relation: 'f', $modify: ['a2'], $recursive: false, $allRecursive: false, }, ]); }); it('b.c.d from [a, b.[g, c.[d.[e(a1), f(a2)], i], h]]', () => { testPath('[a, b.[g, c.[d.[e(a1), f(a2)], i], h]]', 'b.c.d', [ { $name: 'd', $relation: 'd', $modify: [], $recursive: false, $allRecursive: false, e: { $name: 'e', $relation: 'e', $modify: ['a1'], $recursive: false, $allRecursive: false, }, f: { $name: 'f', $relation: 'f', $modify: ['a2'], $recursive: false, $allRecursive: false, }, }, ]); }); }); describe('#merge', () => { testMerge('a', 'b', '[a, b]'); testMerge('a.b', 'b', '[a.b, b]'); testMerge('a', 'b.c', '[a, b.c]'); testMerge('[a, b]', '[b, c]', '[a, b, c]'); testMerge('a.b', 'a.c', 'a.[b, c]'); testMerge('[a.b, d]', 'a.c', '[a.[b, c], d]'); testMerge('a.[c, d.e, g]', 'a.[c.l, d.[e.m, n], f]', 'a.[c.l, d.[e.m, n], g, f]'); testMerge('a.^4', 'a.^3', 'a.^4'); testMerge('a.^', 'a.^6', 'a.^'); testMerge('a.^6', 'a.^', 'a.^'); testMerge('a.a', 'a.^', 'a.^'); testMerge('a(f)', 'a(g)', 'a(f, g)'); testMerge('a.b(f)', 'a.b(g)', 'a.b(f, g)'); }); describe('#toString', () => { testToString('a'); testToString('a.b'); testToString('a as b.b as c'); testToString('a as b.[b as c, d as e]'); testToString('a.[b, c]'); testToString('a.[b, c.d]'); testToString('[a, b]'); testToString('[a.[b, c], d.e.f.[g, h.i]]'); testToString('a.*'); testToString('a.^'); testToString('a.^3'); testToString('[a.*, b.c.^]'); }); describe('#isSubExpression', () => { testSubExpression('*', 'a'); testSubExpression('*', '[a, b]'); testSubExpression('*', 'a.b'); testSubExpression('*', 'a.b.[c, d]'); testSubExpression('*', '[a, b.c, c.d.[e, f.g.[h, i]]]'); testSubExpression('*', '*'); testSubExpression('*', 'a.*'); testSubExpression('*', 'a.^'); testSubExpression('a.*', 'a'); testSubExpression('a.*', 'a.b'); testSubExpression('a.*', 'a.*'); testSubExpression('a.*', 'a.^'); testSubExpression('a.*', 'a.b.c'); testSubExpression('a.*', 'a.[b, c]'); testSubExpression('a.*', 'a.[b, c.d]'); testSubExpression('a.[b.*, c]', 'a.b.c.d'); testSubExpression('a.[b.*, c]', 'a.[b.c.d, c]'); testSubExpression('a.[b.*, c]', 'a.[b.[c, d], c]'); testNotSubExpression('a.*', 'b'); testNotSubExpression('a.*', 'c'); testNotSubExpression('a.*', '[a, b]'); testNotSubExpression('a.*', '*'); testNotSubExpression('a.[b.*, c]', 'a.[b.c.d, c.d]'); testSubExpression('a.b.*', 'a.b.*'); testNotSubExpression('a.b.*', '*'); testNotSubExpression('a.b.*', 'a.*'); testNotSubExpression('a.b.*', 'a.[b.*, c]'); testSubExpression('a', 'a'); testSubExpression('a.b', 'a.b'); testSubExpression('a.b.[c, d]', 'a.b.[c, d]'); testSubExpression('[a.b.[c, d], e]', '[a.b.[c, d], e]'); testSubExpression('a.b', 'a'); testNotSubExpression('a', 'a.b'); testSubExpression('a.b.c', 'a'); testSubExpression('a.b.c', 'a.b'); testNotSubExpression('a', 'a.b.c'); testNotSubExpression('a.b', 'a.b.c'); testSubExpression('a.[b, c]', 'a'); testSubExpression('a.[b, c]', 'a.b'); testSubExpression('a.[b, c]', 'a.c'); testNotSubExpression('a.[b, c]', 'a.c.d'); testNotSubExpression('a.[b, c]', 'b'); testNotSubExpression('a.[b, c]', 'c'); testSubExpression('[a.b.[c, d.e], b]', 'a'); testSubExpression('[a.b.[c, d.e], b]', 'b'); testSubExpression('[a.b.[c, d.e], b]', 'a.b'); testSubExpression('[a.b.[c, d.e], b]', 'a.b.c'); testSubExpression('[a.b.[c, d.e], b]', 'a.b.d'); testSubExpression('[a.b.[c, d.e], b]', 'a.b.d.e'); testSubExpression('[a.b.[c, d.e], b]', '[a.b.[c, d], b]'); testSubExpression('[a.b.[c, d.e], b]', '[a.b.[c, d.[e]], b]'); testNotSubExpression('[a.b.[c, d.e], b]', 'c'); testNotSubExpression('[a.b.[c, d.e], b]', 'b.c'); testNotSubExpression('[a.b.[c, d.e], b]', '[a, b, c]'); testNotSubExpression('[a.b.[c, d.e], b]', 'a.b.e'); testNotSubExpression('[a.b.[c, d.e], b]', '[a.b.e, b]'); testNotSubExpression('[a.b.[c, d.e], b]', '[a.b.c, c]'); testNotSubExpression('[a.b.[c, d.e], b]', 'a.b.[c, e]'); testNotSubExpression('[a.b.[c, d.e], b]', 'a.b.[c, d, e]'); testNotSubExpression('[a.b.[c, d.e], b]', 'a.b.[c, d.[e, f]]'); testSubExpression('a.^', 'a.^'); testSubExpression('a.^', 'a.^100'); testSubExpression('a.^3', 'a.^3'); testSubExpression('a.^3', 'a.^2'); testSubExpression('a.^3', 'a.^1'); testSubExpression('a.^3', 'a.a.a'); testSubExpression('a.^3', 'a.a'); testSubExpression('a.^3', 'a'); testSubExpression('a.^', 'a.a'); testSubExpression('a.^', 'a.a.^'); testSubExpression('a.^', 'a.a.a'); testSubExpression('a.^', 'a.a.a.^'); testSubExpression('[a.^, b.[c.^, d]]', 'a'); testSubExpression('[a.^, b.[c.^, d]]', 'b.c'); testSubExpression('[a.^, b.[c.^, d]]', 'b.c.^'); testSubExpression('[a.^, b.[c.^, d]]', '[a, b]'); testSubExpression('[a.^, b.[c.^, d]]', '[a.^, b]'); testSubExpression('[a.^, b.[c.^, d]]', '[a.a, b]'); testSubExpression('[a.^, b.[c.^, d]]', '[a.a.^, b.c]'); testSubExpression('[a.^, b.[c.^, d]]', '[a.a.^, b.c.^]'); testSubExpression('[a.^, b.[c.^, d]]', '[a.a.^, b.c.c]'); testSubExpression('[a.^, b.[c.^, d]]', '[a.a.^, b.[c.c.c, d]]'); testNotSubExpression('a.^', 'b'); testNotSubExpression('a.^', 'a.b'); testNotSubExpression('a.^', 'a.a.b'); testNotSubExpression('a.^', 'a.a.b.^'); testNotSubExpression('[a.^, b.[c.^, d]]', 'a.b'); testNotSubExpression('[a.^, b.[c.^, d]]', '[c, b]'); testNotSubExpression('[a.^, b.[c.^, d]]', '[c, b]'); testNotSubExpression('[a.^, b.[c.^, d]]', 'b.c.d'); testNotSubExpression('a.^', 'a.[b, ^, c]'); testNotSubExpression('a.^3', 'a.^'); testNotSubExpression('a.^3', 'a.^4'); testNotSubExpression('a.^3', 'a.a.a.a'); testSubExpression('[a as aa.[c as cc . d as dd], b as bb]', 'a as aa'); testSubExpression('[a as aa.[c as cc . d as dd], b as bb]', '[a as aa, b as bb]'); testSubExpression('[a as aa.[c as cc . d as dd], b as bb]', 'a as aa . c as cc'); testSubExpression('[a as aa.[c as cc . d as dd], b as bb]', 'a as aa . c as cc . d as dd'); }); describe('#forEachChildExrpression', () => { it('should traverse first level children', () => { const expr = RelationExpression.create('[a, b.c, d]'); const items = []; const fakeModel = { getRelationNames() { return ['a', 'b', 'd']; }, getRelationUnsafe(name) { return name + name; }, }; expr.forEachChildExpression(fakeModel, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); }); expect(items).to.eql([ { exprName: 'a', relation: 'aa' }, { exprName: 'b', relation: 'bb' }, { exprName: 'd', relation: 'dd' }, ]); }); it('should work with recursive expressions', () => { const expr = RelationExpression.create('a.^'); const items = []; const fakeModel = { getRelationNames() { return ['a']; }, getRelationUnsafe(name) { return name + name; }, }; expr.forEachChildExpression(fakeModel, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); expr.forEachChildExpression(fakeModel, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); expr.forEachChildExpression(fakeModel, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); }); }); }); expect(items).to.eql([ { exprName: 'a', relation: 'aa' }, { exprName: 'a', relation: 'aa' }, { exprName: 'a', relation: 'aa' }, ]); }); it('should work with limited recursive expressions', () => { const expr = RelationExpression.create('a.^2'); const items = []; const fakeModel = { getRelationNames() { return ['a']; }, getRelationUnsafe(name) { return name + name; }, }; expr.forEachChildExpression(fakeModel, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); expr.forEachChildExpression(fakeModel, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); expr.forEachChildExpression(fakeModel, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); }); }); }); expect(items).to.eql([ { exprName: 'a', relation: 'aa' }, { exprName: 'a', relation: 'aa' }, ]); }); it('should work with all recursive expressions', () => { const expr = RelationExpression.create('a.*'); const items = []; const fakeModel1 = { getRelationNames() { return ['a']; }, getRelationUnsafe(name) { return name + name; }, }; const fakeModel2 = { getRelationNames() { return ['b', 'c', 'd']; }, getRelationUnsafe(name) { return name + name; }, }; expr.forEachChildExpression(fakeModel1, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); expr.forEachChildExpression(fakeModel2, (expr, relation) => { items.push({ exprName: expr.node.$name, relation }); }); }); expect(items).to.eql([ { exprName: 'a', relation: 'aa' }, { exprName: 'b', relation: 'bb' }, { exprName: 'c', relation: 'cc' }, { exprName: 'd', relation: 'dd' }, ]); }); }); function testParse(str, parsed) { chai.expect(RelationExpression.create(str).node).to.containSubset(parsed); } function testClone(expr, cloned) { chai.expect(RelationExpression.create(expr).clone().node).to.containSubset(cloned); } function testMerge(str1, str2, parsed) { it(str1 + ' + ' + str2 + ' --> ' + parsed, () => { expect(RelationExpression.create(str1).merge(str2).toString()).to.equal(parsed); expect( RelationExpression.create(str1).merge(RelationExpression.create(str2)).toString() ).to.equal(parsed); }); } function testPath(str, path, expected) { chai .expect( RelationExpression.create(str) .expressionsAtPath(path) .map((it) => it.node) ) .to.containSubset(expected); } function testToString(str) { it(str, () => { expect(RelationExpression.create(str).toString()).to.equal(str); }); } function testToJSON(str, expectedJson) { it(str, () => { const json = RelationExpression.create(str).toJSON(); expect(json).to.eql(expectedJson); expect(RelationExpression.create(json).toString()).to.eql(str); }); } function testParseFail(str) { expect(() => { RelationExpression.create(str); }).to.throwException(); } function testSubExpression(str, subStr) { it('"' + subStr + '" is a sub expression of "' + str + '"', () => { expect(RelationExpression.create(str).isSubExpression(subStr)).to.equal(true); }); } function testNotSubExpression(str, subStr) { it('"' + subStr + '" is not a sub expression of "' + str + '"', () => { expect(RelationExpression.create(str).isSubExpression(subStr)).to.equal(false); }); } });
describe("When GHM is in use,", function(){ describe("git merge", function(){ beforeEach(function(done){ TEST_SUITE.setup(true, true, true, function(err){ if(err){ done(err); } else{ TEST_SUITE.git.__makeAddAndCommitFile("master", "master", function(err){ if(err){ done(err); } else{ TEST_SUITE.git.__setupBranch("other", function(err){ if(err){ done(err); } else{ TEST_SUITE.git.checkout("master", done); } }); } }); } }); }); describe("should run hooks when", function(){ it("merging in exhisting branch", function(done){ TEST_SUITE.git.merge("other", function(err, stdout, stderr){ if(err){ done(err); } else{ try{ stderr.should.equal("post-merge\n\n"); done(); } catch(err){ done(err); } } }); }); }); }); });
window.addEvent("domready", function() { // http://icebeat.bitacoras.com/mootools/growl/ Growl.Smoke({ title: 'Window.Growl By Daniel Mota', text: 'http://icebeat.bitacoras.com', image: 'growl.jpg', duration: 2 }); })
function number_format( numero, decimal, decimal_separador, milhar_separador ){ numero = (numero + '').replace(/[^0-9+\-Ee.]/g, ''); var n = !isFinite(+numero) ? 0 : +numero, prec = !isFinite(+decimal) ? 0 : Math.abs(decimal), sep = (typeof milhar_separador === 'undefined') ? ',' : milhar_separador, dec = (typeof decimal_separador === 'undefined') ? '.' : decimal_separador, s = '', toFixedFix = function (n, prec) { var k = Math.pow(10, prec); return '' + Math.round(n * k) / k; }; // Fix para IE: parseFloat(0.55).toFixed(0) = 0; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec); }
function render(file) { return function(req, res, next) { res.render(file, {}, function(err, html) { if(err) { res.render('errors/e404'); } else { res.send(html); } }); } }; module.exports = render;
const { task, series, dest, src, watch } = require('gulp'); const path = require('path'); const config = require('./config/settings'); // utils const $ = require('./utils/plugins'); const pumped = require('./utils/pumped'); const getFolders = require('./utils/getFolders'); /** * 本番テーマAssetsディレクトリーから * SVG Spriteを消去 */ task('sprite:clean', done => { $.del(config.svg.clean, { force: true }) .then(() => { done() }); }); /** * Dev & Prod */ task('sprite:dev', () => { src(config.sprite.src).pipe($.plumber()) .pipe($.svgSprite({ mode: { inline: true, symbol: { dest: '.', sprite: config.sprite.name } }, shape: { id: { generator: config.sprite.geneartor } } })) .on('error', $.util.log) .pipe($.svgmin({ multipass: true, plugins: [ { cleanupIDs: false }, { removeAttrs: { attrs: 'fill' } } ] })) .pipe(dest(config.sprite.dest)) .pipe($.notify({ message: pumped('Svg Sprites Generated'), onLast: true })) .on('end', $.browser.reload); }); /** * Production */ task('sprite:prod', done => { src(config.sprite.src).pipe($.plumber()) .pipe($.svgSprite({ mode: { inline: true, symbol: { dest: '.', sprite: config.sprite.name } }, shape: { id: { generator: config.sprite.geneartor } } })) .on('error', $.util.log) .pipe($.svgmin({ multipass: true, plugins: [ { cleanupIDs: false }, { removeAttrs: { attrs: 'fill' } } ] })) .pipe(dest(config.sprite.dest)) .pipe($.notify({ message: pumped('Svg Sprites Generated'), onLast: true })); done(); }); /** * Watch */ task('sprite:watch', () => { watch(config.svg.watch, series('sprite:dev')); });
var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var DjModuleGenerator = module.exports = function DjModuleGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(DjModuleGenerator, yeoman.generators.Base); DjModuleGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [ { name: 'moduleName', message: 'What do you want to call your module?', default: 'djx.module.myModule' } ]; this.prompt(prompts, function (props) { this.moduleName = props.moduleName; cb(); }.bind(this)); }; DjModuleGenerator.prototype.app = function app() { this.mkdir('test'); this.mkdir('lib'); this.copy('_do_not_do_this_test.js', 'test/do_not_do_this_test.js'); this.copy('_do_not_do_this.js', 'lib/do_not_do_this.js'); this.template('_package.json', 'package.json'); this.template('_README.md', 'README.md'); this.template('_Gruntfile.js', 'Gruntfile.js'); }; DjModuleGenerator.prototype.projectfiles = function projectfiles() { this.copy('editorconfig', '.editorconfig'); this.copy('gitignore', '.gitignore'); };
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); //var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var jwt = require('jsonwebtoken'); var config = require('../config.js'); var User = require('../models/user.js'); router.get('/', function(req, res) { res.render('login'); }); module.exports = router;
function gameCreate(main_scene, socket) { //----------------------------------------- // game vars //----------------------------------------- var time = 0; var time_add_mine = 0; var game_over = true; var game_players = 0; var scene = main_scene; var objects = []; var sphere_glow = THREE.ImageUtils.loadTexture('assets/sphere_glow.jpg'); var laser_glow = THREE.ImageUtils.loadTexture('assets/laser_glow.jpg'); objects["sphere"] = new THREE.SphereGeometry( 75,12,12 ); objects["laser"] = new THREE.BoxGeometry( 10000,10,10 ); objects["mine"] = new THREE.SphereGeometry( 75,4,3 ); objects["sphere_glow"] = new THREE.PlaneBufferGeometry( 75,75 ); objects["laser_glow"] = new THREE.PlaneBufferGeometry( 10000,10 ); objects["mine_glow"] = new THREE.PlaneBufferGeometry( 75,75 ); function createMaterial(name) { if (name == "sphere_glow") return new THREE.MeshLambertMaterial( { color: 0xFFFFFF, transparent: true, map: sphere_glow, blending: THREE.AdditiveBlending, } ); if (name == "laser_glow") return new THREE.MeshLambertMaterial( { color: 0xFFFFFF, transparent: true, map: laser_glow, blending: THREE.AdditiveBlending, opacity: 0.5 } ); if (name == "mine_glow") return new THREE.MeshLambertMaterial( { color: 0xFFFFFF, transparent: true, map: sphere_glow, blending: THREE.AdditiveBlending, } ); return new THREE.MeshLambertMaterial( { color: 0xFFFFFF } ); } function createObject(name) { console.log("Spawn object: " + name); var obj = new THREE.Mesh(objects[name], createMaterial(name)); var new_object = { obj: obj }; scene.add(obj); return new_object; } //----------------------------------------- // players //----------------------------------------- console.log("Init Players"); var players = []; for (var i = 0; i < 4; i++) { var player = createObject("sphere"); setVisible(player, false); setScale(player, PLAYER_SCALE); setColor(player, COLORS_PLAYER[i]); players.push(player); // glow player.light = createObject("sphere_glow"); setVisible(player.light, false); setScale(player.light, LIGHT_SCALE); setColor(player.light, COLORS_PLAYER[i]); } //----------------------------------------- // Network hacks //----------------------------------------- var GAME_WAITING = 0; var GAME_INPROGRESS = 1; var GAME_PAUSED = 2; var GAME_RESUME = 3; var GAME_OVER = 4; var game_state = GAME_WAITING; var game_options; // NOTE(jordi): this should only need a function getPlayerId that gets the local player or players from game_options.room_clients var game_playerid = 0; // NOTE(jordi): to be replaced with full inputmanager structure var game_inputs = { left: false, right: false, up: false, down: false, action: false }; //----------------------------------------- // lasers //----------------------------------------- var lasers = []; function createLaser(pos, owner, direction) { console.log("Create laser: " + owner) var laser = createObject("laser"); setColor(laser, COLORS_RAY[owner]); setPosition(laser, vec3(pos.x,pos.y,LIGHT_POS_Z+0.5)); setScale(laser, LASER_SCALE); // glow laser.light = createObject("laser_glow"); setPosition(laser.light, vec3(pos.x,pos.y,LIGHT_POS_Z)); setScale(laser.light, LASER_SCALE * 6); setColor(laser.light, COLORS_PLAYER[owner]); // game vars laser.owner = owner; laser.direction = direction; laser.angle = random(0, PI_2); laser.speed = 1.0 / random(25.0, 40.0); laser.line = { x1: pos.x, y1: pos.y, x2: 0, y2: 0, }; laser.spawn = true; laser.time_spawn = time; laser.alive = false; laser.dead = false; laser.die = false; lasers.push(laser); } //----------------------------------------- // mines //----------------------------------------- var mines = []; function createMine() { if (mines.length > 5) return; for (var j = 0; j < 5; j++) { var ok = true; var pos = vec3(random(-SCR_X * 0.8, SCR_X * 0.8), random(-SCR_Y * 0.8, SCR_Y * 0.8), Z_POS); for (i = 0; i < 4; i++) { var player = players[i]; if (player.alive) { var dist = distsq(getPosition(player), pos); if (dist < MINE_PROXIMITY_DIST_SQ) ok = false; } } // added? if (ok) { var mine = createObject("mine"); setColor(mine, COLOR_MINE); setScale(mine, MINE_SCALE); setPosition(mine, pos); // glow mine.light = createObject("mine_glow"); setScale(mine.light, MINE_SCALE*3.5); setPosition(mine.light, vec3(pos.x,pos.y,LIGHT_POS_Z)); // game vars mine.spawn = true; mine.time_spawn = time; mine.alive = false; mine.die = false; mine.dead = false; mines.push(mine); console.log("New mine (" + mines.length + ") " + logVec3(pos)) return; } } } //----------------------------------------- // game //----------------------------------------- function gameStart(options) { console.log(">>> Start new game"); // Seeding our random number generator Math.seedrandom(options.seed); // delete previous mines/lasers deleteAll(lasers, function(laser) { console.log("Remove laser"); scene.remove(laser.light.obj); scene.remove(laser.obj); }); // delete dead mines deleteAll(mines, function(mine) { console.log("Remove mine"); scene.remove(mine.light.obj); scene.remove(mine.obj); }); // create players game_players = 0; for (var i = 0; i < 4; i++) { var enabled = (i<2); var player = players[i]; setVisible(player, enabled); setScale(player, PLAYER_SCALE); setColor(player, COLORS_PLAYER[i]); setVisible(player.light, enabled); setScale(player.light, LIGHT_SCALE); setColor(player.light, COLORS_PLAYER[i]); player.enabled = enabled; player.alive = player.enabled; player.dead = false; player.die = false; player.time_die = 0; player.mine = true; player.time_mine = 0; player.laser = false; player.time_laser = 0; player.num_lasers = 0; player.transparent = false; player.speed = vec2(0,0); player.action = false; if (player.enabled) game_players++; } var x = SCR_X * 0.5 var y = SCR_Y * 0.5 setPosition(players[0], vec3(-x,-y, Z_POS)); setPosition(players[1], vec3(-x, y, Z_POS)); setPosition(players[2], vec3( x,-y, Z_POS)); setPosition(players[3], vec3( x, y, Z_POS)); // add some initial random mines for (var i = 0; i < game_players; i++) { createMine(); } game_over = false; time_add_mine = time; game_state = GAME_INPROGRESS; console.log("Num players: " + game_players); } function gameOver() { game_over = true; game_state = GAME_OVER; socket.emit('game over', {}); } //----------------------------------------- // gameRunCollisions //----------------------------------------- function gameRunCollisions() { // for each alive player for (var i = 0; i < game_players; i++) { var player = players[i]; if (!player.alive) continue; var pos = getPosition(player); // if player has no mine, check against all alive mines if (!player.mine && !player.transparent) { for (var j = 0; j < mines.length; j++) { if (mines[j].alive) { var dist = distsq(getPosition(player), getPosition(mines[j])); //console.log("Player " + i + " dist to mine " + dist); if (dist < DIST_MINE_SQ) { console.log("Player " + i + " got mine"); player.mine = true; player.time_mine = time; mines[j].alive = false; mines[j].dead = false; mines[j].die = true; mines[j].time_die = time; break; } } } } // if player is not transparent, check against all alive lasers if (!player.transparent) { for (var j = 0; j < lasers.length; j++) { if (lasers[j].alive) { var line = lasers[j].line; var dist = distPointLine(pos.x, pos.y, line.x1, line.y1, line.x2, line.y2); // if close and different owner, die! if (lasers[j].owner != i) { //console.log("Dist " + lasers[j].owner + ", " + i + ", " + dist); if (dist < DIST_LINE) { console.log("Player DEAD!!! " + i); player.alive = false; player.dead = false; player.die = true; player.time_die = time; game_players = game_players - 1; if (game_players == 1) { console.log("Game over!"); gameOver(); } break; } } } } } } } //----------------------------------------- // gamerun //----------------------------------------- function gameRun(delta) { // drop mines if (!game_over) { if (time - time_add_mine > TIME_MINES) { time_add_mine = time; createMine(); } } var test = false; // update players for (var i = 0; i < game_players; i++) { var player = players[i]; // die bicho if (player.die) { // flash var t = time01(time, player.time_die, PLAYER_MINE_LEN); if (t < 1) { setVisible(player, flash(time)); setColor(player, COLOR_DIE); setVisible(player.light, flash(time)); } else { setVisible(player, visible); setVisible(player.light, visible); player.alive = false; } } // do alive stuff if (player.alive) { var pos = getPosition(player); // flash if (player.transparent) setVisible(player, flash(time)); else setVisible(player, true); // mine if (player.mine) { // flash var t = time01(time, player.time_mine, PLAYER_MINE_LEN); var f = to010(t); setScale(player, lerp(PLAYER_SCALE, PLAYER_SCALE_MINE, t)); setColor(player, lerpColor(COLORS_PLAYER_MINE[i], COLOR_FLASH, f)); setScale(player.light, lerp(LIGHT_SCALE, LIGHT_SCALE_MINE, t)); // update pos pos.x = pos.x + player.speed.x * delta * PLAYER_SPEED_MINE pos.y = pos.y + player.speed.y * delta * PLAYER_SPEED_MINE } else { // flash var t = time01(time, player.time_laser, PLAYER_LASER_LEN); var f = to010(t); setScale(player, lerp(PLAYER_SCALE_MINE, PLAYER_SCALE, t)); setColor(player, lerpColor(COLORS_PLAYER[i], COLOR_FLASH, f)); setScale(player.light, lerp(LIGHT_SCALE_MINE, LIGHT_SCALE, t)); // update pos pos.x = pos.x + player.speed.x * delta * PLAYER_SPEED pos.y = pos.y + player.speed.y * delta * PLAYER_SPEED } // warp ? if (pos.x < -SCR_X) pos.x = SCR_X; if (pos.y < -SCR_Y) pos.y = SCR_Y; if (pos.x > SCR_X) pos.x = -SCR_X; if (pos.y > SCR_Y) pos.y = -SCR_Y; //console.log("Player speed: " + logVec2(player.speed) + " delta " + delta + " Speed = " + PLAYER_SPEED_MINE) setPosition(player, pos); setPosition(player.light, vec3(pos.x,pos.y,LIGHT_POS_Z)); // actions if (player.transparent) { // transparent ignore actions var t = time - player.time_transparent; if (t > TRANS_TIME) { setColor(player, COLORS_PLAYER[i]); player.transparent = false; console.log("Player " + i + " end TRANSPARENT"); } } else { // alive if (!game_over) { var laser_dir = 0 if (player.action) { player.action = false; if (player.mine) { // drop laser if (random(0.0,1.0) > 0.5) laser_dir = 1; else laser_dir =-1; createLaser(pos, i, laser_dir); player.mine = false; player.laser = true; player.time_laser = time; player.num_lasers = player.num_lasers + 1; console.log("Player " + i + " DROP laser (lasers = " + player.num_lasers + ")"); } else { // if we have lasers, deactivate one and we become transparent / invincible for a while if (player.num_lasers > 0) { player.num_lasers = player.num_lasers - 1; player.transparent = true; player.time_transparent = time; setColor(player, COLORS_PLAYER_TRANS[i]); console.log("Player " + i + " set TRANSPARENT (lasers = " + player.num_lasers + ")"); // update lasers for (var j = 0; j < lasers.length; j++) { if (lasers[j].alive && lasers[j].owner == i) { console.log(" Removed laser from owner = " + lasers[j].owner); lasers[j].alive = false; lasers[j].die = true; lasers[j].time_die = time; test = true; break; } } } } } } } } } // update lasers for (var j = 0; j < lasers.length; j++) { // spawn if (lasers[j].spawn) { var t = time01(time, lasers[j].time_spawn, LASER_SPAWN_LEN); if (t < 1) { setVisible(lasers[j], flash(time)); setScale(lasers[j], LASER_SCALE * t); setRotation(lasers[j], vec3(0,0,lasers[j].angle)); setRotation(lasers[j].light, vec3(0,0,lasers[j].angle)); setVisible(lasers[j].light, flash(time)); } else { setVisible(lasers[j], true); setScale(lasers[j], LASER_SCALE); setVisible(lasers[j].light, true); lasers[j].spawn = false; lasers[j].alive = true; } } // alive if (lasers[j].alive) { // Rotate lasers[j].angle = lasers[j].angle + lasers[j].direction * delta * PI_2 * lasers[j].speed; setRotation(lasers[j], vec3(0,0,lasers[j].angle)); setRotation(lasers[j].light, vec3(0,0,lasers[j].angle)); var p = rotate(1, 0, lasers[j].angle); lasers[j].line.x2 = lasers[j].line.x1 + p.x; lasers[j].line.y2 = lasers[j].line.y1 + p.y; } // die if (lasers[j].die) { // Rotate console.log("Die laser") var t = time01(time, lasers[j].time_die, LASER_DIE_LEN); if (t < 1) { setVisible(lasers[j], flash(time)); setScale(lasers[j], LASER_SCALE * (1 - t)); setVisible(lasers[j].light, flash(time)); setScale(lasers[j].light, LASER_SCALE * 6 * (1 - t)); } else lasers[j].dead = true; } } // delete dead lasers deleteDead(lasers, function(laser) { scene.remove(laser.obj); scene.remove(laser.light.obj); }) // update mines for (var j = 0; j < mines.length; j++) { setRotation(mines[j], vec3(0,0,mines[j].time_spawn + time*0.9)); mines[j].light.obj.material.opacity = nsin(mines[j].time_spawn + time*0.9) * 0.5 + 0.5; // spawn if (mines[j].spawn) { var t = time01(time, mines[j].time_spawn, MINE_SPAWN_LEN); if (t < 1) { setVisible(mines[j], flash(time)); setVisible(mines[j].light, flash(time)); setScale(mines[j], MINE_SCALE * t); } else { setVisible(mines[j], true); setVisible(mines[j].light, true); mines[j].spawn = false; mines[j].alive = true; } } // die if (mines[j].die) { console.log("Delete mine (" + mines.length + ")") var t = time01(time, mines[j].time_die, MINE_DIE_LEN); if (t < 1) { setColor(mines[j], lerpColor(COLOR_MINE, COLOR_FLASH, t)); setScale(mines[j], MINE_SCALE * (1 - t)); setScale(mines[j].light, MINE_SCALE * 3.5 * (1 - t)); } else mines[j].dead = true; } } // delete dead mines deleteDead(mines, function(mine) { scene.remove(mine.obj); scene.remove(mine.light.obj); }) } function gameUpdate(delta,inputs) { time += delta; if (game_state == GAME_INPROGRESS) { // save input if (inputs[0]) { players[0].speed.x = ((inputs[0].buttons & Buttons.Left)?-1:0) + ((inputs[0].buttons & Buttons.Right)?1:0); players[0].speed.y = ((inputs[0].buttons & Buttons.Up)?0:-1) + ((inputs[0].buttons & Buttons.Down)?0:1); players[0].action = inputs[0].buttons_pressed & Buttons.A; } if (inputs[1]) { players[1].speed.x = ((inputs[1].buttons & Buttons.Left)?-1:0) + ((inputs[1].buttons & Buttons.Right)?1:0); players[1].speed.y = ((inputs[1].buttons & Buttons.Up)?0:-1) + ((inputs[1].buttons & Buttons.Down)?0:1); players[1].action = inputs[1].buttons_pressed & Buttons.A; } // run! gameRun(delta); gameRunCollisions(); } } //----------------------------------------- // gameState //----------------------------------------- this.onRoomMessage = function(action, data) { switch (action) { case "game_start": console.log("game start ( " + data.seed + " )"); gameStart(data); break; case "game_update": // NOTE(jordi): hardcoded game_playerid for 2 players gameUpdate(data.delta, data.inputs); break; } } }
var fs = require('fs'); var should = require('should'); var utils = require('../../lib/utils'); var q = require('q'); /** * Function: expectFilesToMatch * ---------------------------- * Expects the contents of the two given files to match. * * @param expectedFileName - the file with the expected contents * @param actualFileName - the file with the actual contents * * @return promise that yields success if the contents match or an error * otherwise */ exports.expectFilesToMatch = function(expectedFileName, actualFileName) { var expected = utils.readFile(expectedFileName); var actual = utils.readFile(actualFileName); return exports.expectResultsToMatch(expected, actual); }; /** * Function: expectResultsToMatch * ------------------------------ * Expects the results of the two given promises to match. * * @param expected - an expected string or promise for a string * @param actual - an actual string or promise for a string * * @return promise that yields success if the results match or an error * otherwise */ exports.expectResultsToMatch = function(expected, actual) { return q.all([expected, actual]) .spread(function(expected, actual) { // make line-endings consistent actual = actual.replace(/\r\n/g, '\n'); expected = expected.replace(/\r\n/g, '\n'); actual.should.equal(expected); }); }; /** * Function: mockUtilsModification * ------------------------------- * Mocks the watchFileForModification function in the utils module. Adds a * mockFileModication function to utils that immediately triggers a given * file's modification callback. * * @return the mocked utils module */ exports.mockUtilsModifications = function() { var utils = require('../../lib/utils'); var events = require('events'); var emitter = new events.EventEmitter(); utils.watchFileForModification = function(fileName, interval, callback) { emitter.on('mockModification', function(fileModified) { if (fileModified === fileName) { // make sure the modification time of the current stat is greater than // the modification time of the old stat when triggering the callback callback({ mtime: 10 }, { mtime: 9 }); } }); }; /** * Function: mockFileModification * ------------------------------ * Immediately triggers the modification callback for the given file. * * @param fileName - the file to trigger a modification callback for */ utils.mockFileModification = function(fileName) { emitter.emit('mockModification', fileName); }; /** * Function: removeMockModificationListeners * ----------------------------------------- * Removes any EventEmitter listeners associated with mocked modifications * thus far. Doesn't stop future mocked modifications. */ utils.removeMockModificationListeners = function() { emitter.removeAllListeners(); }; return utils; };
/* Copyright (c) 2012-2013 Coding Smackdown TV, http://codingsmackdown.tv 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. */ 'use strict'; // Declare module which depends on filters, and services angular.module('notificationWidget', []) // Declare an http interceptor that will signal the start and end of each request .config(['$httpProvider', function ($httpProvider) { var $http, interceptor = ['$q', '$injector', '$location', '$rootScope', function ($q, $injector, $location, $rootScope) { var notificationChannel; function removeErrors() { var $inputs = $(':input'); $inputs.each(function() { $(this).removeClass("validationerror"); }); } function success(response) { // clear previous errors for a success request. delete $rootScope.errorStatus; delete $rootScope.errorDetails; removeErrors(); // get $http via $injector because of circular dependency problem $http = $http || $injector.get('$http'); // don't send notification until all requests are complete if ($http.pendingRequests.length < 1) { // get requestNotificationChannel via $injector because of circular dependency problem notificationChannel = notificationChannel || $injector.get('requestNotificationChannel'); // send a notification requests are complete notificationChannel.requestEnded(); } if(response.config && response.config.method=="GET"){ return response; }else { if (response.data && response.data.commandId) { //Maker checker is enabled or performing actions of maker checker if (response.config.url.indexOf('makercheckers/') > 0) { //return response for maker checker actions(approve or delete) return response; } else{ //redirect if maker checker is enabled $location.path('/viewMakerCheckerTask/'+response.data.commandId); } } else{ //when no maker checker enabled return response; }; } } function error(response) { // get $http via $injector because of circular dependency problem $http = $http || $injector.get('$http'); removeErrors(); // don't send notification until all requests are complete if ($http.pendingRequests.length < 1) { // get requestNotificationChannel via $injector because of circular dependency problem notificationChannel = notificationChannel || $injector.get('requestNotificationChannel'); // send a notification requests are complete notificationChannel.requestEnded(); } if (response.status === 0) { $rootScope.errorStatus='No connection. Verify application is running.'; } else if (response.status == 401) { $rootScope.errorStatus='Unauthorized'; } else if (response.status == 404) { $rootScope.errorStatus='Requested page not found. [404]'; } else if (response.status == 405) { $rootScope.errorStatus='HTTP verb not supported [405]'; } else if (response.status == 500) { $rootScope.errorStatus='Internal Server Error [500].'; } else { var jsonErrors = JSON.parse(JSON.stringify(response.data)); var valErrors = jsonErrors.errors; var errorArray = new Array(); var arrayIndex = 0; for(var i in valErrors) { var temp = valErrors[i]; // add error class to input in dialog var fieldId = '#' + temp.parameterName; $(fieldId).addClass("validationerror"); var errorObj = new Object(); errorObj.field = temp.parameterName; errorObj.code = temp.userMessageGlobalisationCode; errorObj.args = {params:[]}; for(var j in temp.args) { errorObj.args.params.push({value : temp.args[j].value}); } errorArray[arrayIndex] = errorObj; arrayIndex++; }; $rootScope.errorDetails = errorArray; } return $q.reject(response); } return function (promise) { // get requestNotificationChannel via $injector because of circular dependency problem notificationChannel = notificationChannel || $injector.get('requestNotificationChannel'); // send a notification requests are complete notificationChannel.requestStarted(); return promise.then(success, error); } }]; $httpProvider.responseInterceptors.push(interceptor); }]) // declare the notification pub/sub channel .factory('requestNotificationChannel', ['$rootScope', function($rootScope){ // private notification messages var _START_REQUEST_ = '_START_REQUEST_'; var _END_REQUEST_ = '_END_REQUEST_'; // publish start request notification var requestStarted = function() { $rootScope.$broadcast(_START_REQUEST_); $rootScope.blockUI = true; }; // publish end request notification var requestEnded = function() { $rootScope.$broadcast(_END_REQUEST_); $rootScope.blockUI = false; }; // subscribe to start request notification var onRequestStarted = function($scope, handler){ $scope.$on(_START_REQUEST_, function(event){ handler(); }); }; // subscribe to end request notification var onRequestEnded = function($scope, handler){ $scope.$on(_END_REQUEST_, function(event){ handler(); }); }; return { requestStarted: requestStarted, requestEnded: requestEnded, onRequestStarted: onRequestStarted, onRequestEnded: onRequestEnded }; }])
'use strict' describe('Poker.Hand', function () { var hand beforeEach(function () { hand = new DISBRANDED.Poker.Hand }) it('should add a card to the hand', function () { hand.add('AS') expect(hand.has('AS')).toBe(true) expect(hand.has('2S')).toBe(false) expect(hand.get(0)).toBe('AS') expect(hand.get(1)).toBe(null) }) it('should not add a card that the hand already has', function () { hand.add('AS') hand.add('AS') expect(hand.cards.length).toBe(1) }) it('should set a card at an index', function () { hand.set(5, 'AS') expect(hand.get(5)).toBe(null) expect(hand.get(0)).toBe('AS') expect(hand.cards).toEqual(['AS']) hand.set(-1, '2D') expect(hand.get(0)).toBe('2D') expect(hand.cards).toEqual(['2D']) hand.set(0, '2S') hand.set(1, '3S') hand.set(4, '6S') hand.set(3, '5S') hand.set(2, '4S') hand.set(3, '7S') hand.set(4, '8S') expect(hand.get(0)).toBe('2S') expect(hand.get(2)).toBe('4S') expect(hand.get(4)).toBe('8S') }) it('should set multiple cards at once', function () { hand.add('2S', '3S', '4S', '5S', '6S') expect(hand.get(0)).toBe('2S') expect(hand.get(1)).toBe('3S') expect(hand.get(2)).toBe('4S') expect(hand.get(3)).toBe('5S') expect(hand.get(4)).toBe('6S') }) it('should reset the hand', function () { hand.add('2S', '3S', '4S', '5S', '6S') hand.reset() expect(hand.cards.length).toBe(0) expect(hand.get(0)).toBe(null) }) })
'use strict'; var config = { awsProfile: "default", awsRegion : "us-east-1", environmentStage: "development", resourcePrefix: "pe-justin", slsProject: "pantryexpress-api" }; // Check if it is in environment variable. function getVar(name) { if (process.env[name]){ console.log('Getting value', name, 'from environmental variable with value', process.env[name], ' overriding ', config[name]); return process.env[name]; } return config[name]; } module.exports = { awsProfile: getVar('awsProfile'), awsRegion : getVar('awsRegion'), environmentStage: getVar('environmentStage'), resourcePrefix: getVar('resourcePrefix'), slsProject: getVar('slsProject') };
import compose from '../utils/compose'; import clone from 'lodash/objects/clone'; export default compose(function(name) { this._db = new PouchDB(name); this._revs = {}; }, { setItem: function(key, value) { var revs = this._revs; return this._db.put(value, key, revs[key]).then(function(resp) { revs[key] = resp.rev; }); }, removeItem: function(key) { var rev = this._revs[key]; return this._db.remove(key, rev); }, get: function() { var revs = this._revs; return this._db.allDocs({ include_docs: true }).then(function(resp) { var values = {}; resp.rows.forEach(function(row) { var value = row.doc; delete value._id; delete value._rev; values[row.id] = value; revs[row.id] = row.value.rev; }); return values; }); }, addItems: function(itemsAsDict) { var revs = this._revs; var itemsAsArray = []; Object.keys(itemsAsDict).forEach(function(key) { var doc = clone(itemsAsDict[key]); doc._id = key; itemsAsArray.push(doc); }); return this._db.bulkDocs(itemsAsArray).then(function(resp) { resp.forEach(function(row) { revs[row.id] = row.rev; }); }); } });
export const host = 'http://localhost:3000/';
require.config({ baseUrl: '.', paths: { 'weather-client': 'lib/weather-client' } }); var views = {}; function weatherDay(city, require) { var weather = require('weather-client'); var typetemperature = "metric"; console.log(city); weather.getToday(city, typetemperature).then(function (data) { views.todayView(data); }, function (data) { views.todayView(data); }); } function weatherweek(city, require) { var weather = require('weather-client'); var typetemperature = "metric"; weather.getWeek(city, typetemperature).then(function (data) { views.weekView(data); }, function (data) { views.weekView(data); }); } function setCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return null; } function loadmain() { require(['require', 'weather-client'], function (require) { city = document.getElementById("city").value; console.log(city); citycookie = getCookie("city"); if (city === '') { if (citycookie === null) { city = "toronto"; } else { city = getCookie("city"); } } else { setCookie('city', city, 10); } weatherDay(city, require); weatherweek(city, require); }); } function typetemp(temp, type) { if (type === "metric") { return temp.toFixed(1) + " ºC"; } else { return temp.toFixed(1) + " ºF"; } } function convertDate(date_, w) { var time_zone = 1000 * (new Date().getTimezoneOffset()) * (-60); date_ = new Date(date_ * 1000 + time_zone); if (w === 1) { var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; date_ = weekday[date_.getDay()]; } return date_; } views.emptyView = function (data) { var html = '<div class="row"><div class="col-md-12">' + '<div class="row"><div class="col-md-10"><input class="form-control" type="text" id="city" value="' + data.name + '" onkeydown="if (event.keyCode === 13) loadmain();" placeholder="Enter you city" autofocus></div>'; html += '<div class="col-md-2"> <button type="button" id="enviar" class="btn btn-primary" onclick="loadmain()">Search</button></div></div>'; if (data.status === 404) { html += '<h1>' + data.message.replace('Error:', ' ') + '</h1>'; } html += '</div></div>'; return html; }; views.itemView = function (data) { return '<div class="row"><div class="col-md-12">' + views.emptyView(data) + ' </div></div>' + '<div class="row"><div class="col-md-12">' + '<h1>' + data.name + '</h1><h2>' + data.desc + '</h2>' + '<table align=center><tr><td><h2><img src="img_clima/' + data.icon + '.png" align="left middle" > ' + typetemp(data.temp, data.type) + '</h2></td><td><h1>&nbsp;/&nbsp;<h1></td><td align=left>max: ' + typetemp(data.temp_max, data.type) + '<br>min: ' + typetemp(data.temp_min, data.type) + '</td></tr></table>' + '</div></div>'; }; views.todayView = function (data) { var html; console.log(data.status); if (data.status !== 200) { data.name = ""; html = views.emptyView(data); titulo = '<img src="img_clima/01d.png" align="left middle" > WeatherNow'; } else { titulo = '<img src="img_clima/' + data.icon + '.png" align="left middle" > WeatherNow'; html = views.itemView(data); } document.getElementById("main").innerHTML = html; document.getElementById("titlemain").innerHTML = titulo; }; views.itemweekView = function (data) { return '<div class="col-lg-6">' + '<h3>' + convertDate(data.dt, 1) + '</h3>' + '<p>' + data.weather[0].description + '</p>' + '<table align=center><tr><td><h2><img src="img_clima/' + data.weather[0].icon + '.png" align="left middle" > ' + typetemp(data.temp.day, data.type) + '</h2></td><td><h1>&nbsp;/&nbsp;<h1></td><td align=left>max: ' + typetemp(data.temp.max, data.type) + '<br>min: ' + typetemp(data.temp.morn, data.type) + '</td></tr></table>' + '<p>' + 'Morn: ' + typetemp(data.temp.morn, data.type) + '<br>' + 'Ever: ' + typetemp(data.temp.eve, data.type) + '<br>' + 'Nigh: ' + typetemp(data.temp.night, data.type) + '<br>' + '</p>' + '</div>'; }; views.weekView = function (data) { if (data.status === "200") { var len = data.list.length; var ct = 0; var html = ""; for (var i = 0; i < len; i++) { if (ct === 0) { html += '<div class="row marketing sombrarredondada" >'; abre = 1; } html += views.itemweekView(data.list[i]); ct += 1; if (ct === 2) { ct = 0; abre = 0; html += '</div>'; } } if (abre === 1) { html += '</div>'; } document.getElementById("week").innerHTML = html; } else { document.getElementById("week").innerHTML = ""; } }; loadmain();
(function() { 'Use strict'; var Role = require('./../models/role.models'); /** * [function to create a role] * @param {[http request object]} req [used to get the request query] * @param {[http response object]} res [used to respond back to client ] * @return {[json]} [success message that role has been created] */ exports.createRole = function(req, res) { //check if role already exists Role.findOne({ title: req.body.title }, function(err, role) { if (err) { res.send(err); } else { //if role exists if (role) { res.status(409).json({ message: 'Role already exists!' }); } else { var newRole = new Role({ title: req.body.title }); //create a new role newRole.save(function(err) { if (err) { res.send(err); } else { res.status(200).json({ message: 'Role successfully created!' }); } }); } } }); }; /** * [function to get all available roles] * @param {[http request object]} req [used to get the request query] * @param {[http response object]} res [used to respond back to client ] * @return {[json]} [all available roles in the database] */ exports.getAllRoles = function(req, res) { //find all available roles Role.find({}, function(err, roles) { if (err) { res.send(err); } else { res.status(200).json(roles); } }); }; /** * [function to get a specific role by it Id] * @param {[http request object]} req [used to get the request query] * @param {[http response object]} res [used to respond back to client ] * @return {[json]} [a role with a specific Id] */ exports.getRoleById = function(req, res) { Role.findById(req.params.id, function(err, role) { if (err) { res.send(err); } else if (!role) { res.status(404).json({ message: 'Role not found!' }); } else { res.status(200).json({ message: role }); } }); }; /** * [function to edit a role's detail] * @param {[http request object]} req [used to get the request query] * @param {[http response object]} res [used to respond back to client ] * @return {[json]} [success message that role has been updated] */ exports.editRole = function(req, res) { //find a role with its Id and update its content Role.findByIdAndUpdate(req.params.id, req.body, function(err, role) { if (err) { res.json({ message: 'Update role failed!' }); //if no role is found } else if (!role) { res.status(404).json({ message: 'Role not found' }); } else { res.status(200).json({ message: 'Role successfully updated' }); } }); }; /** * [function to delete a role] * @param {[http request object]} req [used to get the request query] * @param {[http response object]} res [used to respond back to client ] * @return {[json]} [success message that role has been deleted] */ exports.deleteRole = function(req, res) { //find a role with its Id and delete Role.findById(req.params.id).remove(function(err, role) { if (err) { res.json({ message: 'Delete role failed' }); //if no role is found } else if (!role) { res.status(404).json({ message: 'Role does not exist!' }); } else { res.status(200).json({ message: 'Role successfully deleted' }); } }); }; })();
// Marionette Controller // --------------------- // // A multi-purpose object to use as a controller for // modules and routers, and as a mediator for workflow // and coordination of other objects, views, and more. Marionette.Controller = function(options){ this.triggerMethod = Marionette.triggerMethod; this.options = options || {}; if (_.isFunction(this.initialize)){ this.initialize(this.options); } }; Marionette.Controller.extend = Marionette.extend; // Controller Methods // -------------- // Ensure it can trigger events with Backbone.Events _.extend(Marionette.Controller.prototype, Backbone.Events, { close: function(){ this.stopListening(); var args = Array.prototype.slice.call(arguments); this.triggerMethod.apply(this, ["close"].concat(args)); this.unbind(); } });
(function() { ActiveAdmin.DependentSelects = (function() { function DependentSelects(options, element) { this.element = element; this.$element = $(this.element); this.$selectInputs = this.$element.find('.dependent_select_input'); this.options = options; defaults = { url: this.$element.attr('url'), valueAttr: this.$element.attr('value_attr'), labelAttr: this.$element.attr('label_attr'), inputPrompt: this.$element.attr('prompt'), inputName: this.$selectInputs.last().attr('name') }; this.options = $.extend(defaults, options); var _this = this; this.$selectInputs.each(function() { _this._bind($(this)); }); }; DependentSelects.prototype.option = function(key, value) { if ($.isPlainObject(key)) { return this.options = $.extend(true, this.options, key); } else if (key != null) { return this.options[key]; } else { return this.options[key] = value; } }; DependentSelects.prototype._buildChildInput = function(collection) { if (collection.length === 0) return; var $newSelectInput = $('<select class="dependent_select_input"></select>'); var tempCategory; $newSelectInput.append('<option value="">'+ this.options.inputPrompt +'</option>'); for (var i = 0; i < collection.length; i++) { tempCategory = collection[i]; $newSelectInput.append( '<option value=' + tempCategory[this.options.valueAttr] + '>' + tempCategory[this.options.labelAttr] + '</option>'); } this.$element.append($newSelectInput); return $newSelectInput; }; DependentSelects.prototype._bind = function($selectInput) { var _this = this; $selectInput.change(function() { $selectInput.nextAll().remove(); if ($selectInput.val() === "") { $selectInput.removeAttr("name"); $selectInput.prev().attr("name", _this.options.inputName); return false; } $selectInput.prevAll().removeAttr("name"); $selectInput.attr("name", _this.options.inputName); $.ajax({ url: _this.options.url, data: function() { var result = {}; result[_this.options.valueAttr] = $selectInput.val(); return result; }() }).done(function(collection) { var $newSelectInput = _this._buildChildInput(collection); if ($newSelectInput) _this._bind($newSelectInput); }); return false; }); }; return DependentSelects; })(); $.widget.bridge('aaDependentSelects', ActiveAdmin.DependentSelects); $(function() { $('.dependent_select').aaDependentSelects(); $(document).on('click', 'a.button.has_many_add', function() { $('.dependent_select').aaDependentSelects(); }); }); }).call(this);
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { Button } from '../Button'; import styles from './styles.scss'; import i18n from './i18n'; class CopyToClipboard extends Component { executeCopy() { this.copyTextArea.focus(); this.copyTextArea.select(); try { const result = document.execCommand('copy'); if (result) { this.copyTextArea.blur(); if (typeof this.props.handleSuccess === 'function') this.props.handleSuccess(); } else if (typeof this.props.handleFailure === 'function') { this.props.handleFailure(); } } catch (e) { console.error(e); if (typeof this.props.handleFailure === 'function') { this.props.handleFailure(); } } } render() { const { currentLocale, buttonClassName, disabled, copiedText, buttonText, button: CustomButton, } = this.props; return ( <div className={styles.container}> <textarea className={styles.copyTextArea} ref={(ref) => { this.copyTextArea = ref; }} defaultValue={copiedText} /> {CustomButton ? ( <CustomButton {...this.props} executeCopy={() => this.executeCopy()} /> ) : ( <Button disabled={disabled} dataSign="copyToClipboard" className={classnames(styles.primaryButton, buttonClassName)} onClick={() => this.executeCopy()} > {buttonText || i18n.getString('copyToClipboard', currentLocale)} </Button> )} </div> ); } } CopyToClipboard.propTypes = { currentLocale: PropTypes.string.isRequired, handleSuccess: PropTypes.func, handleFailure: PropTypes.func, buttonClassName: PropTypes.string, disabled: PropTypes.bool, copiedText: PropTypes.string, buttonText: PropTypes.string, button: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), }; CopyToClipboard.defaultProps = { handleSuccess: undefined, handleFailure: undefined, buttonClassName: undefined, disabled: undefined, copiedText: undefined, buttonText: undefined, button: undefined, }; export default CopyToClipboard;
function StatsJournal(options) { var Cucumber = require('../../cucumber'); var _ = require('lodash'); function getCountsObject () { var statuses = [ Cucumber.Status.FAILED, Cucumber.Status.PASSED, Cucumber.Status.PENDING, Cucumber.Status.SKIPPED, Cucumber.Status.UNDEFINED ]; var counts = {}; statuses.forEach(function (status) { counts[status] = 0; }); return counts; } var scenarioResult; var scenarioCounts = getCountsObject(); var stepCounts = getCountsObject(); var duration = 0; if (!options) options = {}; var self = Cucumber.Listener(); self.handleBeforeScenarioEvent = function handleBeforeScenarioEvent(event, callback) { scenarioResult = Cucumber.Runtime.ScenarioResult(); callback(); }; self.handleAfterScenarioEvent = function handleAfterScenarioEvent(event, callback) { scenarioCounts[scenarioResult.getStatus()] += 1; callback(); }; self.handleStepResultEvent = function handleStepResult(event, callback) { var stepResult = event.getPayloadItem('stepResult'); var stepDuration = stepResult.getDuration(); if (stepDuration) { duration += stepDuration; } var status = stepResult.getStatus(); var step = stepResult.getStep(); if (!step.isHidden()) { stepCounts[status] += 1; } scenarioResult.witnessStepResult(stepResult); callback(); }; self.isCurrentScenarioFailing = function isCurrentScenarioFailing() { return scenarioResult.getStatus() === Cucumber.Status.FAILED; }; self.getScenarioCounts = function getScenarioCounts() { return _.clone(scenarioCounts); }; self.getStepCounts = function getStepCounts() { return _.clone(stepCounts); }; self.getDuration = function getDuration() { return duration; }; return self; } module.exports = StatsJournal;
// Generated by CoffeeScript 1.8.0 /*! * jQuery POP'n SocialButton v0.1.9 * * http://github.com/ktty1220/jquery.popn-socialbutton * * 参考サイト * * - http://q.hatena.ne.jp/1320898356 * - http://stackoverflow.com/questions/5699270/how-to-get-share-counts-using-graph-api * - http://stackoverflow.com/questions/8853342/how-to-get-google-1-count-for-current-page-in-php * - http://hail2u.net/blog/coding/jquery-query-yql-plugin.html * - http://hail2u.net/blog/coding/jquery-query-yql-plugin-supports-open-data-tables.html * - http://www.absolute-keitarou.net/blog/?p=1068 * * Copyright (c) 2013 ktty1220 ktty1220@gmail.com * Licensed under the MIT license */ (function() { (function(jQuery) { 'use strict'; var $; $ = jQuery; return $.fn.popnSocialButton = function(services, options) { var exOptions, iconSize, idx, mkYQL, popnUp, sName, scheme, servicesProp, _addLink, _i, _len; if (options == null) { options = {}; } exOptions = $.extend({}, { url: document.location.href, text: $('title').html(), imgDir: './img', buttonSpace: 24, countPosition: { top: 32, right: -12 }, countColor: { text: '#ffffff', bg: '#cc0000', textHover: '#ffffff', bgHover: '#ff6666', border: '#ffffff' }, countSize: 11, popupWindow: { width: 640, height: 480 } }, options); exOptions.urlOrg = exOptions.url; exOptions.url = encodeURIComponent(exOptions.urlOrg); exOptions.text = encodeURIComponent(exOptions.text); iconSize = 44; popnUp = 4; scheme = /https/.test(document.location.protocol) ? 'https' : 'http'; mkYQL = function(url, wantJson) { var yUrl; if (wantJson == null) { wantJson = false; } yUrl = "" + scheme + "://query.yahooapis.com/v1/public/yql?env=http://datatables.org/alltables.env&q=" + (encodeURIComponent("SELECT content FROM data.headers WHERE url='" + url + "' and ua='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 5.1)'")); if (wantJson) { yUrl += '&format=json'; } return yUrl; }; servicesProp = { twitter: { img: 'twitter_2x.png', alt: 'Twitter Share Button', shareUrl: "https://twitter.com/share?url=" + exOptions.url + "&text=" + exOptions.text, commentUrl: "https://twitter.com/search/?q=" + exOptions.url, countUrl: "http://urls.api.twitter.com/1/urls/count.json?url=" + exOptions.url, jsonpFunc: function(json, cb) { var _ref; return cb((_ref = json.count) != null ? _ref : 0); } }, facebook: { img: 'facebook_2x.png', alt: 'Facebook Share Button', shareUrl: "https://www.facebook.com/sharer.php?u=" + exOptions.url + "&t=" + exOptions.text, countUrl: "https://graph.facebook.com/" + exOptions.url, jsonpFunc: function(json, cb) { /* * - Graph APIでsharesが取得できない場合はFQLでtotal_countを取得する * - Graph APIのlikes + FQLのtotal_countでいいねボタンと同じ件数になる模様(いくつかのケースを調べた結果) * - ほとんどのサイトではFQLのtotal_countだけでいいねボタンと同じ件数になる */ var graphLikes, _ref; if (json.shares != null) { return cb(json.shares); } graphLikes = (_ref = json.likes) != null ? _ref : 0; return $.ajax({ url: "https://graph.facebook.com/fql?q=" + (encodeURIComponent("SELECT total_count FROM link_stat WHERE url='" + exOptions.urlOrg + "'")), dataType: 'jsonp' }).done(function(json) { var fqlTotal, _ref1, _ref2; fqlTotal = (_ref1 = (_ref2 = json.data[0]) != null ? _ref2.total_count : void 0) != null ? _ref1 : 0; return cb(graphLikes + fqlTotal); }); } }, hatebu: { img: 'hatena_bookmark_2x.png', alt: 'Hatena Bookmark Share Button', shareUrl: "http://b.hatena.ne.jp/add?mode=confirm&url=" + exOptions.url + "&title=" + exOptions.text + "&mode=confirm", commentUrl: "http://b.hatena.ne.jp/entry/" + exOptions.urlOrg, countUrl: "http://api.b.st-hatena.com/entry.count?url=" + exOptions.url, jsonpFunc: function(json, cb) { return cb(json != null ? json : 0); } }, gplus: { img: 'google+1_2x.png', alt: 'Google Plus Share Button', shareUrl: "https://plusone.google.com/share?url=" + exOptions.url, /* * - Google+1ボタンはシェア数に関するjsonpを提供していない(jsonすら提供していない)ので+1ボタンのhtmlを取得してその中から件数を取得する * - クロスドメインによる取得になるのでYQLを使用する * - ただしgoogleのサーバーに設置してあるrobots.txtはYQL(というかYahooのロボット全般?)のUAを拒否するのでOpen Data Tableのdata.headerプラグインを使用する */ countUrl: mkYQL("https://plusone.google.com/_/+1/fastbutton?hl=ja&url=" + exOptions.urlOrg), jsonpFunc: function(json, cb) { var count, m, _ref; count = 0; if (((_ref = json.query) != null ? _ref.count : void 0) > 0) { m = json.results[0].match(/window\.__SSR = {c: ([\d]+)/); if (m != null) { count = m[1]; } } return cb(count); } }, pocket: { img: 'pocket_2x.png', alt: 'Pocket Stock Button', shareUrl: "https://getpocket.com/save?url=" + exOptions.url + "&title=" + exOptions.text, /* * Google+1ボタンと同様にYQLでカウントを取得する */ countUrl: mkYQL("https://widgets.getpocket.com/v1/button?label=pocket&count=vertical&align=left&v=1&url=" + exOptions.urlOrg + "&src=" + exOptions.urlOrg + "&r=" + (Math.random() * 100000000)), jsonpFunc: function(json, cb) { var count, m, _ref; count = 0; if (((_ref = json.query) != null ? _ref.count : void 0) > 0) { m = json.results[0].match(/em id="cnt"&gt;(\d+)&lt;/); if (m != null) { count = m[1]; } } return cb(count); } }, feedly: { img: 'feedly_2x.png', alt: 'Feedly Follow Button', shareUrl: "https://feedly.com/index.html#subscription%2Ffeed%2F" + exOptions.feedUrl, /* * Google+1ボタンと同様にYQLでカウントを取得する */ countUrl: mkYQL("https://cloud.feedly.com/v3/feeds/feed%2F" + (encodeURIComponent(exOptions.feedUrl)), true), jsonpFunc: function(json, cb) { var _ref, _ref1, _ref2, _ref3, _ref4, _ref5; return cb((_ref = json != null ? (_ref1 = json.query) != null ? (_ref2 = _ref1.results) != null ? (_ref3 = _ref2.resources) != null ? (_ref4 = _ref3.content) != null ? (_ref5 = _ref4.json) != null ? _ref5.subscribers : void 0 : void 0 : void 0 : void 0 : void 0 : void 0) != null ? _ref : 0); } }, github: { img: 'github_alt_2x.png', alt: 'GitHub Repository', shareUrl: "https://github.com/" + exOptions.githubRepo, commentUrl: "https://github.com/" + exOptions.githubRepo + "/stargazers", countUrl: "https://api.github.com/repos/" + exOptions.githubRepo, jsonpFunc: function(json, cb) { var _ref, _ref1; return cb((_ref = json != null ? (_ref1 = json.data) != null ? _ref1.watchers : void 0 : void 0) != null ? _ref : 0); } } }; _addLink = (function(_this) { return function(name, prop, idx) { var countTag, countTagType, imgTag, shareTag, wrapTag; wrapTag = $('<div/>').attr({ "class": "popn-socialbutton-wrap " + name }).css({ 'float': 'left', position: 'relative', width: iconSize, height: iconSize, marginTop: popnUp }); if (idx > 0) { wrapTag.css({ marginLeft: exOptions.buttonSpace }); } shareTag = $('<a/>').attr({ href: prop.shareUrl, "class": 'popn-socialbutton-share', target: '_blank' }).css({ outline: 'none', display: 'block', width: '100%', height: '100%' }); imgTag = $('<img/>').attr({ src: "" + exOptions.imgDir + "/" + prop.img, alt: prop.alt }).css({ border: 'none' }); countTagType = prop.commentUrl ? 'a' : 'span'; countTag = $("<" + countTagType + "/>").attr({ "class": 'popn-socialbutton-count' }); if (countTagType === 'a') { countTag.attr({ href: prop.commentUrl, target: '_blank' }); } else { countTag.css({ cursor: 'default' }); } countTag.css($.extend({}, { display: 'none', position: 'absolute', color: exOptions.countColor.text, backgroundColor: exOptions.countColor.bg, border: "solid 2px " + exOptions.countColor.border, fontSize: exOptions.countSize, textDecoration: 'none', outline: 'none', fontWeight: 'bold', padding: '0 4px', borderRadius: 6, boxShadow: '0 1px 2px rgba(0, 0, 0, 0.8)', zIndex: 1 }, exOptions.countPosition)); wrapTag.append(shareTag.append(imgTag)).append(countTag); $(_this).append(wrapTag); return $.ajax({ url: prop.countUrl, dataType: 'jsonp' }).done(function(json) { return prop.jsonpFunc(json, function(count) { return countTag.show().text(count); }); }); }; })(this); for (idx = _i = 0, _len = services.length; _i < _len; idx = ++_i) { sName = services[idx]; if (servicesProp[sName] != null) { _addLink(sName, servicesProp[sName], idx); } } $(this).height(iconSize + popnUp); $(this).find('.popn-socialbutton-share').click(function() { var left, top; if (/(github|feedly)/.test($(this).parent().attr('class'))) { return true; } top = (screen.height / 2) - (exOptions.popupWindow.height / 2); left = (screen.width / 2) - (exOptions.popupWindow.width / 2); window.open(this.href, '', "width=" + exOptions.popupWindow.width + ", height=" + exOptions.popupWindow.height + ", top=" + top + ", left=" + left); return false; }); $(this).find('a.popn-socialbutton-count').mouseenter(function() { return $(this).css({ color: exOptions.countColor.textHover, backgroundColor: exOptions.countColor.bgHover }); }).mouseleave(function() { return $(this).css({ color: exOptions.countColor.text, backgroundColor: exOptions.countColor.bg }); }); return $(this).find('.popn-socialbutton-wrap').mouseenter(function() { return $(this).stop().animate({ marginTop: 0 }, 100, 'swing'); }).mouseleave(function() { return $(this).stop().animate({ marginTop: 4 }, 100, 'swing'); }); }; })(jQuery); }).call(this);
define(["angular", "underscore"], function(angular, _) { "use strict"; function experiencesController($scope, mountainsService, treeSvc, seasonSvc) { $scope.resume = {}; $scope.transitionSpring = function() { seasonSvc.progressThroughAllSeasons(); } mountainsService.drawMountains(); } return experiencesController; });
import BaseDataLayer from './base'; import {merge} from '../../helpers/layouts'; /** * @memberof module:LocusZoom_DataLayers~annotation_track */ const default_layout = { color: '#000000', filters: null, tooltip_positioning: 'vertical', hitarea_width: 8, }; /** * Create a single continuous 2D track that provides information about each datapoint * * For example, this can be used to mark items by membership in a group, alongside information in other panels * @alias module:LocusZoom_DataLayers~annotation_track * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options */ class AnnotationTrack extends BaseDataLayer { /** * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color] Specify how to choose the fill color for each tick mark * @param {number} [layout.hitarea_width=8] The width (in pixels) of hitareas. Annotation marks are typically 1 px wide, * so a hit area of 4px on each side can make it much easier to select an item for a tooltip. Hitareas will not interfere * with selecting adjacent points. * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='vertical'] Where to draw the tooltip relative to the datum. */ constructor(layout) { if (!Array.isArray(layout.filters)) { throw new Error('Annotation track must specify array of filters for selecting points to annotate'); } merge(layout, default_layout); super(...arguments); } initialize() { super.initialize(); this._hitareas_group = this.svg.group.append('g') .attr('class', `lz-data_layer-${this.layout.type}-hit_areas`); this._visible_lines_group = this.svg.group.append('g') .attr('class', `lz-data_layer-${this.layout.type}-visible_lines`); } render() { // Apply filters to only render a specified set of points const track_data = this._applyFilters(); const hit_areas_selection = this._hitareas_group.selectAll(`rect.lz-data_layer-${this.layout.type}`) .data(track_data, (d) => d[this.layout.id_field]); const _getX = (d, i) => { // Helper for hitarea position calcs: ensures that a hitarea never overlaps the space allocated // for a real data element. Helps to avoid mouse jitter when selecting tooltips in crowded areas. const x_center = this.parent['x_scale'](d[this.layout.x_axis.field]); let x_left = x_center - this.layout.hitarea_width / 2; if (i >= 1) { // This assumes that the data are in sorted order. const left_node = track_data[i - 1]; const left_node_x_center = this.parent['x_scale'](left_node[this.layout.x_axis.field]); x_left = Math.max(x_left, (x_center + left_node_x_center) / 2); } return [x_left, x_center]; }; // Draw hitareas under real data elements, so that real data elements always take precedence hit_areas_selection.enter() .append('rect') .attr('class', `lz-data_layer-${this.layout.type}`) // Update the set of elements to reflect new data .merge(hit_areas_selection) .attr('id', (d) => this.getElementId(d)) .attr('height', this.parent.layout.height) .attr('opacity', 0) .attr('x', (d, i) => { const crds = _getX(d, i); return crds[0]; }) .attr('width', (d, i) => { const crds = _getX(d, i); return (crds[1] - crds[0]) + this.layout.hitarea_width / 2; }); const width = 1; const selection = this._visible_lines_group.selectAll(`rect.lz-data_layer-${this.layout.type}`) .data(track_data, (d) => d[this.layout.id_field]); // Draw rectangles (visual and tooltip positioning) selection.enter() .append('rect') .attr('class', `lz-data_layer-${this.layout.type}`) .merge(selection) .attr('id', (d) => this.getElementId(d)) .attr('x', (d) => this.parent['x_scale'](d[this.layout.x_axis.field]) - width / 2) .attr('width', width) .attr('height', this.parent.layout.height) .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i)); // Remove unused elements selection.exit() .remove(); // Set up tooltips and mouse interaction this.svg.group .call(this.applyBehaviors.bind(this)); // Remove unused elements hit_areas_selection.exit() .remove(); } /** * Render tooltip at the center of each tick mark * @param tooltip * @return {{y_min: number, x_max: *, y_max: *, x_min: number}} * @private */ _getTooltipPosition(tooltip) { const panel = this.parent; const data_layer_height = panel.layout.height - (panel.layout.margin.top + panel.layout.margin.bottom); const stroke_width = 1; // as defined in the default stylesheet const x_center = panel.x_scale(tooltip.data[this.layout.x_axis.field]); const y_center = data_layer_height / 2; return { x_min: x_center - stroke_width, x_max: x_center + stroke_width, y_min: y_center - panel.layout.margin.top, y_max: y_center + panel.layout.margin.bottom, }; } } export {AnnotationTrack as default};
import PropTypes from 'prop-types'; import { Platform } from 'react-native'; // Todo: port over values from // https://github.com/NewSpring/junction-framework/blob/master/lib/_defaults.scss export const DEFAULT_THEME = { primaryColor: '#6bac43', secondaryColor: '#1c683e', tertiaryColor: '#2a4930', darkPrimaryColor: '#303030', darkSecondaryColor: '#505050', darkTertiaryColor: '#858585', lightPrimaryColor: '#ffffff', lightSecondaryColor: '#f7f7f7', lightTertiaryColor: '#dddddd', darkOverlayColor: 'rgba(48,48,48,0.8)', alertColor: '#c64f55', baseUnit: 20, baseFontColor: '#505050', baseFontSize: 18, baseLineHeight: 20, fontFamilySans: null, // force default system font fontFamilySerif: Platform.OS !== 'android' ? 'Georgia' : 'serif', screenLightColor: '#ffffff', screenDarkColor: '#000000', cardBorderRadius: 6, breakpoints: { xs: 320, sm: 496, md: 800, lg: 1200, }, }; export const THEME_PROPS = { primaryColor: PropTypes.string, secondaryColor: PropTypes.string, primaryFont: PropTypes.string, breakpoints: PropTypes.shape({ xs: PropTypes.number, sm: PropTypes.number, md: PropTypes.number, lg: PropTypes.number, }), };
/* * Vanilla Unorphanize * Based on https://github.com/simeydotme/jQuery-Unorphanize * @author Kyle Foster (@hkfoster) * @license MIT */ !function(a,b){"use strict";function d(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function e(a,c){this.selector=b.querySelectorAll(a),this.options=d(this.defaults,c),this.init()}e.prototype={defaults:{companions:1},init:function(a){var b=this,a=b.selector,c=b.options;Array.prototype.forEach.call(a,function(a){var d,e,f,g,h,i,b=[];for(d=a.innerHTML,e=d.match(/<([A-Z][A-Z0-9]*)\b[^>]*>/gi),h=null!==e?e.length:0,f=0;h>f;f++)b.push(e[f]),d=d.replace(e[f],"__"+f+"__");for(f=0;f<c.companions;f++)g=d.lastIndexOf(" "),g>0&&(d=d.substring(0,g)+"&nbsp;"+d.substring(g+1));for(f=0;h>f;f++)i=new RegExp("__"+f+"__"),d=d.replace(i,b[f]);a.innerHTML=d},!1)}},a.unorphanize=e}(window,document);
/** * Created by ssehacker on 16/9/2. */ import _ from 'underscore'; import Status from '../src/Status'; // 以下请求需要登录才能访问 const requestsNeedAuth = [ { path: '/api/article/:id', method: 'DELETE', }, { path: '/api/article/:id', method: 'PUT', }, { path: '/api/user', method: 'PUT', }, { path: '/api/user', method: 'PATCH', }, { path: '/api/user', method: 'GET', }, { path: '/api/logout', method: 'POST', }, ]; function match(path, method) { return _.find(requestsNeedAuth, item => (item.path === path && item.method === method)); } export default async function (ctx, next) { if (match(ctx.path, ctx.method) && !ctx.session.username) { ctx.error(Status.USER_AUTH_FAILED); return; } await next(); }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug); var _path = require('path'); var _path2 = _interopRequireDefault(_path); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var debug = (0, _debug2.default)('feathers:configuration'); var config = require('config'); var separator = _path2.default.sep; exports.default = module.exports = function () { return function () { var app = this; var convert = function convert(current) { var result = Array.isArray(current) ? [] : {}; Object.keys(current).forEach(function (name) { var value = current[name]; if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) { value = convert(value); } if (typeof value === 'string') { if (value.indexOf('\\') === 0) { value = value.replace('\\', ''); } else { if (process.env[value]) { value = process.env[value]; } else if (value.indexOf('.') === 0 || value.indexOf('..') === 0) { // Make relative paths absolute value = _path2.default.resolve(_path2.default.join(config.util.getEnv('NODE_CONFIG_DIR')), value.replace(/\//g, separator)); } } } result[name] = value; }); return result; }; var env = config.util.getEnv('NODE_ENV'); debug('Initializing configuration for ' + env + ' environment'); var conf = convert(config); if (!app) { return conf; } Object.keys(conf).forEach(function (name) { var value = conf[name]; debug('Setting ' + name + ' configuration value to', value); app.set(name, value); }); }; };
import React, { Component, PropTypes } from 'react'; import assign from 'deep-assign'; const WaveSurfer = require('wavesurfer.js'); const EVENTS = [ 'audioprocess', 'error', 'finish', 'loading', 'mouseup', 'pause', 'play', 'ready', 'scroll', 'seek', 'zoom' ]; /** * @description Capitalise the first letter of a string */ function capitaliseFirstLetter(string) { return string.split('-').map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(''); } /** * @description Throws an error if the prop is defined and not an integer or not positive */ function positiveIntegerProptype(props, propName, componentName) { const n = props[propName]; if (n !== undefined && (typeof n !== 'number' || n !== parseInt(n, 10) || n < 0)) { return new Error(`Invalid ${propName} supplied to ${componentName}, expected a positive integer`); } return null; } const resizeThrottler = (fn) => () => { let resizeTimeout; if (!resizeTimeout) { resizeTimeout = setTimeout(() => { resizeTimeout = null; fn(); }, 66); } }; class Wavesurfer extends Component { constructor(props) { super(props); this.state = { isReady: false }; if (typeof WaveSurfer === undefined) { throw new Error('WaveSurfer is undefined!'); } this._wavesurfer = Object.create(WaveSurfer); this._loadMediaElt = this._loadMediaElt.bind(this); this._loadAudio = this._loadAudio.bind(this); this._seekTo = this._seekTo.bind(this); if (this.props.responsive) { this._handleResize = resizeThrottler(() => { // pause playback for resize operation if (this.props.playing) { this._wavesurfer.pause(); } // resize the waveform this._wavesurfer.empty(); this._wavesurfer.drawBuffer(); // restore previous position this._seekTo(this.props.pos); // restore playback if (this.props.playing) { this._wavesurfer.play(); } }); } } componentDidMount() { const options = assign({}, this.props.options, { container: this.wavesurferEl }); // media element loading is only supported by MediaElement backend if (this.props.mediaElt) { options.backend = 'MediaElement'; } this._wavesurfer.init(options); // file was loaded, wave was drawn this._wavesurfer.on('ready', () => { this.setState({ isReady: true, pos: this.props.pos }); // set initial position if (this.props.pos) { this._seekTo(this.props.pos); } // set initial volume if (this.props.volume) { this._wavesurfer.setVolume(this.props.volume); } // set initial zoom if (this.props.zoom) { this._wavesurfer.zoom(this.props.zoom); } if (this.props.responsive) { window.addEventListener('resize', this._handleResize, false); } }); this._wavesurfer.on('audioprocess', (pos) => { this.setState({ pos }); this.props.onPosChange({ wavesurfer: this._wavesurfer, originalArgs: [pos] }); }); // `audioprocess` is not fired when seeking, so we have to plug into the // `seek` event and calculate the equivalent in seconds (seek event // receives a position float 0-1) – See the README.md for explanation why we // need this this._wavesurfer.on('seek', (pos) => { const formattedPos = this._posToSec(pos); this.setState({ formattedPos }); this.props.onPosChange({ wavesurfer: this._wavesurfer, originalArgs: [formattedPos] }); }); // hook up events to callback handlers passed in as props EVENTS.forEach((e) => { const propCallback = this.props[`on${capitaliseFirstLetter(e)}`]; const wavesurfer = this._wavesurfer; if (propCallback) { this._wavesurfer.on(e, (...originalArgs) => { propCallback({ wavesurfer, originalArgs }); }); } }); // if audioFile prop, load file if (this.props.audioFile) { this._loadAudio(this.props.audioFile, this.props.audioPeaks); } // if mediaElt prop, load media Element if (this.props.mediaElt) { this._loadMediaElt(this.props.mediaElt, this.props.audioPeaks); } } // update wavesurfer rendering manually componentWillReceiveProps(nextProps) { // update audioFile if (this.props.audioFile !== nextProps.audioFile) { this._loadAudio(nextProps.audioFile, nextProps.audioPeaks); } // update mediaElt if (this.props.mediaElt !== nextProps.mediaElt) { this._loadMediaElt(nextProps.mediaElt, nextProps.audioPeaks); } // update peaks if (this.props.audioPeaks !== nextProps.audioPeaks) { if (nextProps.mediaElt) { this._loadMediaElt(nextProps.mediaElt, nextProps.audioPeaks); } else { this._loadAudio(nextProps.audioFile, nextProps.audioPeaks); } } // update position if (nextProps.pos && this.state.isReady && nextProps.pos !== this.props.pos && nextProps.pos !== this.state.pos) { this._seekTo(nextProps.pos); } // update playing state if (this.props.playing !== nextProps.playing || this._wavesurfer.isPlaying() !== nextProps.playing) { if (nextProps.playing) { this._wavesurfer.play(); } else { this._wavesurfer.pause(); } } // update volume if (this.props.volume !== nextProps.volume) { this._wavesurfer.setVolume(nextProps.volume); } // update volume if (this.props.zoom !== nextProps.zoom) { this._wavesurfer.zoom(nextProps.zoom); } // update audioRate if (this.props.options.audioRate !== nextProps.options.audioRate) { this._wavesurfer.setPlaybackRate(nextProps.options.audioRate); } // turn responsive on if (nextProps.responsive && this.props.responsive !== nextProps.responsive) { window.addEventListener('resize', this._handleResize, false); } // turn responsive off if (!nextProps.responsive && this.props.responsive !== nextProps.responsive) { window.removeEventListener('resize', this._handleResize); } } shouldComponentUpdate() { return false; } componentWillUnmount() { // remove listeners EVENTS.forEach((e) => { this._wavesurfer.un(e); }); // destroy wavesurfer instance this._wavesurfer.destroy(); if (this.props.responsive) { window.removeEventListener('resize', this._handleResize); } } // receives seconds and transforms this to the position as a float 0-1 _secToPos(sec) { return (1 / this._wavesurfer.getDuration()) * sec; } // receives position as a float 0-1 and transforms this to seconds _posToSec(pos) { return pos * this._wavesurfer.getDuration(); } // pos is in seconds, the 0-1 proportional position we calculate here … _seekTo(sec) { const pos = this._secToPos(sec); if (this.props.options.autoCenter) { this._wavesurfer.seekAndCenter(pos); } else { this._wavesurfer.seekTo(pos); } } // load a media element selector or HTML element // if selector, get the HTML element for it // and pass to _loadAudio _loadMediaElt(selectorOrElt, audioPeaks) { if (selectorOrElt instanceof window.HTMLElement) { this._loadAudio(selectorOrElt, audioPeaks); } else { if (!window.document.querySelector(selectorOrElt)) { throw new Error('Media Element not found!'); } this._loadAudio(window.document.querySelector(selectorOrElt), audioPeaks); } } // pass audio data to wavesurfer _loadAudio(audioFileOrElt, audioPeaks) { if (audioFileOrElt instanceof window.HTMLElement) { // media element this._wavesurfer.loadMediaElement(audioFileOrElt, audioPeaks); } else if (typeof audioFileOrElt === 'string') { // bog-standard string is handled by load method and ajax call this._wavesurfer.load(audioFileOrElt, audioPeaks); } else if (audioFileOrElt instanceof window.Blob || audioFileOrElt instanceof window.File) { // blob or file is loaded with loadBlob method this._wavesurfer.loadBlob(audioFileOrElt, audioPeaks); } else { throw new Error(`Wavesurfer._loadAudio expects prop audioFile to be either HTMLElement, string or file/blob`); } } render() { let childrenWithProps = (this.props.children) ? React.Children.map( this.props.children, child => React.cloneElement(child, { wavesurfer: this._wavesurfer, isReady: this.state.isReady })) : false; return ( <div> <div ref={(c) => { this.wavesurferEl = c; }} /> {childrenWithProps} </div> ); } } Wavesurfer.propTypes = { playing: PropTypes.bool, pos: PropTypes.number, audioFile: (props, propName, componentName) => { const prop = props[propName]; if (prop && typeof prop !== 'string' && !(prop instanceof window.Blob) && !(prop instanceof window.File)) { return new Error(`Invalid ${propName} supplied to ${componentName} expected either string or file/blob`); } return null; }, mediaElt: PropTypes.oneOfType([ PropTypes.string, PropTypes.instanceOf(window.HTMLElement) ]), audioPeaks: PropTypes.array, volume: PropTypes.number, zoom: PropTypes.number, responsive: PropTypes.bool, onPosChange: PropTypes.func, children: PropTypes.oneOfType([ PropTypes.element, PropTypes.array ]), options: PropTypes.shape({ audioRate: PropTypes.number, backend: PropTypes.oneOf(['WebAudio', 'MediaElement']), barWidth: (props, propName, componentName) => { const prop = props[propName]; if (prop !== undefined && typeof prop !== 'number') { return new Error(`Invalid ${propName} supplied to ${componentName} expected either undefined or number`); } return null; }, cursorColor: PropTypes.string, cursorWidth: positiveIntegerProptype, dragSelection: PropTypes.bool, fillParent: PropTypes.bool, height: positiveIntegerProptype, hideScrollbar: PropTypes.bool, interact: PropTypes.bool, loopSelection: PropTypes.bool, mediaControls: PropTypes.bool, minPxPerSec: positiveIntegerProptype, normalize: PropTypes.bool, pixelRatio: PropTypes.number, progressColor: PropTypes.string, scrollParent: PropTypes.bool, skipLength: PropTypes.number, waveColor: PropTypes.string, autoCenter: PropTypes.bool }) }; Wavesurfer.defaultProps = { playing: false, pos: 0, options: WaveSurfer.defaultParams, responsive: true, onPosChange: () => {} }; export default Wavesurfer;
/* * File: app/view/SampleMenuPanel2.js * * This file was generated by Sencha Architect version 2.2.2. * http://www.sencha.com/products/architect/ * * This file requires use of the Ext JS 4.2.x library, under independent license. * License of Sencha Architect does not include license for Ext JS 4.2.x. For more * details see http://www.sencha.com/license or contact license@sencha.com. * * This file will be auto-generated each and everytime you save your project. * * Do NOT hand edit this file. */ Ext.define('App.view.SampleMenuPanel2', { extend: 'Ext.panel.Panel', alias: 'widget.samplemenupanel2', title: 'Cadastro', initComponent: function() { var me = this; Ext.applyIf(me, { dockedItems: [ { xtype: 'toolbar', dock: 'top', items: [ { xtype: 'button', module: 'startup', allowDepress: false, enableToggle: true, iconAlign: 'top', iconCls: 'teste', scale: 'medium', text: 'Painel', toggleGroup: 'module' }, { xtype: 'button', module: 'container', allowDepress: false, enableToggle: true, iconAlign: 'top', iconCls: 'icon-exit', scale: 'medium', text: 'Container', toggleGroup: 'module' } ] } ] }); me.callParent(arguments); } });
/* global window */ (function (root) { function isProvider(type, row) { return Array.isArray(row) && row[1] === type; } function providerName(row) { return row[2][0]; } // all found modules by name var _modules = {}; var valueProvider, constantProvider, serviceProvider, factoryProvider; var $q; function moduleToNode(name) { if (!name) { throw new Error('Expected angular module name'); } if (_modules[name]) { return $q.when(_modules[name]); } var m = angular.module(name); if (!m) { throw new Error('Cannot find module ' + name); } // console.log(m._invokeQueue); var node = { name: name, dependencies: m.requires, values: m._invokeQueue .filter(valueProvider).map(providerName), constants: m._invokeQueue .filter(constantProvider).map(providerName), services: m._invokeQueue .filter(serviceProvider).map(providerName), factories: m._invokeQueue .filter(factoryProvider).map(providerName), children: [] }; _modules[name] = node; var promises = m.requires.map(function (childName) { var deferred = $q.defer(); setTimeout(function () { deferred.resolve(moduleToNode(childName)); }, 0); return deferred.promise; }); return $q.all(promises).then(function (childrenNodes) { childrenNodes.forEach(function (n) { node.children.push(n); }); return node; }); } function ngAst(name) { _modules = {}; valueProvider = angular.bind(null, isProvider, 'value'); constantProvider = angular.bind(null, isProvider, 'constant'); serviceProvider = angular.bind(null, isProvider, 'service'); factoryProvider = angular.bind(null, isProvider, 'factory'); $q = angular.injector(['ng']).get('$q'); return moduleToNode(name); } root.ngAst = ngAst; }(typeof window === 'object' ? window : this));
'use strict'; module.exports = { API_URI: 'https://api.github.com', SEARCH_URI: '/search/repositories', GITHUB_GIT_URI: 'git@github.com:', GITHUB_HTTPS_URI: 'https://github.com/', loggingConfigs: { outputMode: 'short', }, logPrefix: 'buh.', logfile: 'buh.log', consoleLogLevel: ((process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'debug') ? 'debug' : 'fatal'), logToFile: process.env.NODE_ENV === 'debug', };
const { GraphQLEnumType } = require('graphql') const generateEnum = (array) => array.reduce((accum, next) => { accum[next] = {} return accum }, {}) class EnumType extends GraphQLEnumType { constructor (config) { config.values = Array.isArray(config.values) ? generateEnum(config.values) : config.values super(config) } } module.exports = EnumType
var Yadda = require('yadda'); module.exports = { parseFeatures: function (featuresDir, optTags, optLanguage) { if (optTags) var tags = sortTags(optTags); var features = []; var language = this.getLanguage(optLanguage); new Yadda.FeatureFileSearch(featuresDir).each(function (file) { var parser = new Yadda.parsers.FeatureFileParser(language); var feature = parser.parse(file); if (!optTags || shouldIncludeFeature(feature.annotations, tags)) { features.push(feature); } }); return features; }, getLanguage: function (language) { if (!language) return Yadda.localisation.English; var lang = language.charAt(0).toUpperCase() + language.slice(1); if (Yadda.localisation[lang]) { return Yadda.localisation[lang]; } else { throw new Error("'" + language + "' is not a supported language."); } } }; function sortTags(tagOpts) { var tags = { include: [], ignore: [] }; tagOpts.split(',').forEach(function (tag) { if (tag.indexOf('!@') > -1) { tags.ignore.push(stripTag(tag)); } else { tags.include.push(stripTag(tag)); } }); return tags; } function stripTag(tag) { return tag.replace('!', '').replace('@', ''); } function shouldIncludeFeature(annotations, tags) { if (annotations.pending) return true; if (isTagged(tags.ignore, annotations)) return false; if (isTagged(tags.include, annotations)) return true; if (tags.include.length < 1) return true; } function isTagged(tagsArr, annotations) { var match = false; Object.keys(annotations).forEach(function (key) { if (tagsArr.indexOf(key) > -1) match = true; }); return match; }
import React from "react" import MappingListItem from "./MappingListItem" const MappingList = ({ mappings, sampleChoices }) => { return mappings.map(mapping => ( <MappingListItem key={mapping.id} mapping={mapping} sampleChoices={sampleChoices} /> )) } export default MappingList
"use strict"; var Client = require("./../dist/index"); var testAuth = require("./../test_auth.json"); var github = new Client({ debug: true }); github.authenticate({ type: "oauth", token: testAuth["token"] }); github.search.issues({ q: "bazinga" }, function(err, res) { console.log(err, res); });
/** * We declare the collection just like meteor default way * but changing Meteor.Collection to orion.collection. * * We can set options to that new collection, like which fields * we will show in the index of the collection in the admin */ ChapterLrcs = new orion.collection('chapterlrcs', { singularName: orion.helpers.getTranslation('chapters.singularLrcName'), // The name of one of this items pluralName: orion.helpers.getTranslation('chapters.pluralLrcName'), // The name of more than one of this items title: orion.helpers.getTranslation('chapters.titlelrc'), // The title of the page link: { /** * The text that you want to show in the sidebar. * The default value is the name of the collection, so * in this case is not necesary */ // title: orion.helpers.getTranslation('chapters.title') title: "章节Lrc" }, /** * Tabular settings for this collection */ tabular: { columns: [ {data: 'no', title: orion.helpers.getTranslation('chapters.titlelrc')}, { data: 'chapter', title: orion.helpers.getTranslation('chapters.title'), render: function (val, type, doc) { // var bookId = val; // var bookTitle = Books.findOne({'_id':bookId}).title; // console.log(Chapters.findOne(val).count()) // return Chapters.findOne(val).title; return val; } }, /** * If you want to show a custom orion attribute in * the index table you must call this function * orion.attributeColumn(attributeType, key, label) */ // orion.attributeColumn('file', 'file', orion.helpers.getTranslation('chapters.schema.mp3')), {data: 'percentage', title:'Percentage'}, // orion.attributeColumn('summernote', 'body', orion.helpers.getTranslation('chapters.schema.body')), orion.attributeColumn('createdBy', 'createdBy', orion.helpers.getTranslation('chapters.schema.createdBy')), orion.attributeColumn('createdAt', 'createdAt', orion.helpers.getTranslation('chapters.schema.createdAt')) ] } });
layui.use(['form','layer','jquery'], function () { var $ = layui.jquery, form = layui.form; var is_agree = true; form.on('checkbox(agreement)', function (data) { is_agree = data.elem.checked; //开关是否开启,true或者false }); form.on('submit(apply)', function (data) { var remoteLoading = top.layer.msg('加载中...', {icon: 16, time: false, shade: 0.8}); if (!is_agree) { layer.msg('您需要同意先服务协议') return false; } else { var field = data.field; field.is_agree = is_agree; console.log(field) $.ajax({ url: '/user/store_apply', type: 'post', async: false, dataType: 'json', data: field, success: function (data) { if (data.code == 200) { layer.msg(data.msg, { time: 1000, icon: 6, end: function () { $("#J_progress").removeClass().addClass("step2"); } }); } else { layer.msg(data.msg, { time: 1000, icon: 5, end: function () { top.layer.close(remoteLoading); } }); } }, error: function () { top.layer.close(remoteLoading); layer.msg('网络错误!', {time: 1000, icon: 5}); } }); } return false; }) // 获取一级商品分类 function get_goods_category(id, target) { var category = [] $.ajax({ url:'/main/get_goods_category', type: 'post', dataType: 'json', data:{ cate_id: id }, success: function (data) { if(data.code === 201){ category = data.data.cate; var category_content = '<option value="">请选择</option>'; for(var i = 0; i < category.length; i++){ category_content += "<option value='"+category[i].id+"'>"+category[i].name+"</option>" } $(target).html(category_content); form.render('select'); } }, error: function () { layer.msg('网络错误!', {time: 1000, icon: 5}); } }) } get_goods_category(0,"#J_cate1") form.on('select(cate1)', function (data) { get_goods_category(data.value,"#J_cate2") }) })
var path = require('path') module.exports = { port: 8080, assetsSubDirectory: 'static', assetsPublicPath: '/', // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware proxy: { '/': { // https://github.com/chimurai/http-proxy-middleware#http-proxy-options target: 'http://0.0.0.0:8000/', changeOrigin: true, logLevel: 'warn', // probably you use a backend server for ajax requests filter: function (pathname, req) { return req.headers['x-requested-with'] === 'XMLHttpRequest' } } } }
/* eslint-disable jsx-a11y/href-no-hash */ import { storiesOf } from "@kadira/storybook"; import { linkTo } from "@kadira/storybook-addon-links"; import centered from "../.storybook/decorators/centered"; storiesOf("Junction", module) .addDecorator(centered) .add("Introduction", () => ( <div className="locked-ends locked-sides soft-double background--light-secondary floating"> <div className="floating__item text-left one-whole"> <h1 className="uppercase flush-bottom soft-half-bottom">Junction</h1> <a onClick={linkTo("Junction", "Structure")} href="#" className="italic h6">A Compositional Styling Framework</a> </div> </div> )) .add("Structure", () => ( <div className="locked-ends locked-sides soft-double background--light-secondary floating"> <div className="floating__item text-left one-whole"> <h1 className="flush-bottom soft-half-bottom">Structure</h1> <a href="#" onClick={linkTo("Junction", "Elements")}> <h4 className="flush-bottom soft-half-bottom">Elements</h4> </a> <p>Elements are used to style native html elements and items like native elements (i.e icons). These can vary from headers to images to iframes. Some elements also create helper classes based on the base element.</p> <a href="#" onClick={linkTo("Junction", "Components")}> <h4 className="flush-bottom soft-half-bottom">Components</h4> </a> <p>Components are typically made up of multiple (sometimes nested) markup elements. They are styled more for layout and utility than traditional UI libraries. Components are things like cards, grids, and panels.</p> <a href="#"onClick={linkTo("Junction", "Helpers")}> <h4 className="flush-bottom soft-half-bottom">Helpers</h4> </a> <p>Helpers is where from most of the magic of the echo architecture comes. These are namespaced for breakpoints, and can be used in conjuction to create complex and unique UI without custom css. An example of some helpers are things like text controls, padding controls, and event position controls.</p> <a href="#" onClick={linkTo("Junction", "Overrides")}> <h4 className="flush-bottom soft-half-bottom">Overrides</h4> </a> <p>Used sparingly, overrides allow for forcing a style from higher in the sheet than custom later code. In practice, overrides are rarely needed, but when used, they allow for absolute control over display. An example override is a hidden utility to force an element to not be displayed.</p> </div> </div> )) .add("Elements", () => ( <div className="locked-ends locked-sides soft-double background--light-secondary floating"> <div className="floating__item text-left one-whole"> <h1 className="flush-bottom soft-half-bottom">Elements</h1> <div className="grid"> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Buttons")}> <a href="#"><h6>Buttons</h6></a> </li> <li onClick={linkTo("Social Buttons")}> <a href="#"><h6>Social Buttons</h6></a> </li> <li onClick={linkTo("Form")}> <a href="#"><h6>Forms</h6></a> </li> <li onClick={linkTo("HorizontalRule")}> <a href="#"><h6>Horizontal Rule</h6></a> </li> <li onClick={linkTo("Icons")}> <a href="#"><h6>Icons</h6></a> </li> </ul> </div> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Social Icons")}> <a href="#"><h6>Social Icons</h6></a> </li> <li onClick={linkTo("IFrame")}> <a href="#"><h6>iFrame</h6></a> </li> <li onClick={linkTo("Image")}> <a href="#"><h6>Images</h6></a> </li> <li onClick={linkTo("Input")}> <a href="#"><h6>Inputs</h6></a> </li> <li onClick={linkTo("Labels")}> <a href="#"><h6>Labels</h6></a> </li> </ul> </div> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Labels")}> <a href="#"><h6>Labels</h6></a> </li> <li onClick={linkTo("Links")}> <a href="#"><h6>Links</h6></a> </li> <li onClick={linkTo("Lists")}> <a href="#"><h6>Lists</h6></a> </li> <li onClick={linkTo("Sections")}> <a href="#"><h6>Sections</h6></a> </li> <li onClick={linkTo("Select")}> <a href="#"><h6>Select</h6></a> </li> <li onClick={linkTo("TextArea")}> <a href="#"><h6>TextArea</h6></a> </li> </ul> </div> </div> </div> </div> )) .add("Components", () => ( <div className="locked-ends locked-sides soft-double background--light-secondary floating"> <div className="floating__item text-left one-whole"> <h1 className="flush-bottom soft-half-bottom">Components</h1> <div className="grid"> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Accordions")}> <a href="#"><h6>Accordions</h6></a> </li> <li onClick={linkTo("Background")}> <a href="#"><h6>Backgrounds</h6></a> </li> <li onClick={linkTo("Cards")}> <a href="#"><h6>Cards</h6></a> </li> <li onClick={linkTo("FixedRatios")}> <a href="#"><h6>Fixed Ratios</h6></a> </li> <li onClick={linkTo("Floating")}> <a href="#"><h6>Floating</h6></a> </li> </ul> </div> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Grids")}> <a href="#"><h6>Grids</h6></a> </li> <li onClick={linkTo("Inputs")}> <a href="#"><h6>Inputs</h6></a> </li> <li onClick={linkTo("Modals")}> <a href="#"><h6>Modals</h6></a> </li> <li onClick={linkTo("Overlay")}> <a href="#"><h6>Overlays</h6></a> </li> <li onClick={linkTo("Panels")}> <a href="#"><h6>Panels</h6></a> </li> </ul> </div> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Progress")}> <a href="#"><h6>Progress</h6></a> </li> <li onClick={linkTo("Toggles")}> <a href="#"><h6>Toggles</h6></a> </li> </ul> </div> </div> </div> </div> )) .add("Helpers", () => ( <div className="locked-ends locked-sides soft-double background--light-secondary floating"> <div className="floating__item text-left one-whole"> <h1 className="flush-bottom soft-half-bottom">Helpers</h1> <div className="grid"> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Constrain")}> <a href="#"><h6>Constrain</h6></a> </li> <li onClick={linkTo("Displays")}> <a href="#"><h6>Displays</h6></a> </li> <li onClick={linkTo("Float")}> <a href="#"><h6>Float</h6></a> </li> <li onClick={linkTo("Flush")}> <a href="#"><h6>Flush</h6></a> </li> <li onClick={linkTo("Hard")}> <a href="#"><h6>Hard</h6></a> </li> </ul> </div> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Locked")}> <a href="#"><h6>Locked</h6></a> </li> <li onClick={linkTo("Outlines")}> <a href="#"><h6>Outlines</h6></a> </li> <li onClick={linkTo("Push")}> <a href="#"><h6>Push</h6></a> </li> <li onClick={linkTo("Push Back")}> <a href="#"><h6>Push Back</h6></a> </li> <li onClick={linkTo("Rounded Corners")}> <a href="#"><h6>Rounded Corners</h6></a> </li> </ul> </div> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Scrollable")}> <a href="#"><h6>Scrollable</h6></a> </li> <li onClick={linkTo("Shapes")}> <a href="#"><h6>Shapes</h6></a> </li> <li onClick={linkTo("Soft")}> <a href="#"><h6>Soft</h6></a> </li> <li onClick={linkTo("Text")}> <a href="#"><h6>Text</h6></a> </li> <li onClick={linkTo("Transitions")}> <a href="#"><h6>Transitions</h6></a> </li> <li onClick={linkTo("Type")}> <a href="#"><h6>Type</h6></a> </li> <li onClick={linkTo("Widths")}> <a href="#"><h6>Widths</h6></a> </li> </ul> </div> </div> </div> </div> )) .add("Overrides", () => ( <div className="locked-ends locked-sides soft-double background--light-secondary floating"> <div className="floating__item text-left one-whole"> <h1 className="flush-bottom soft-half-bottom">Overrides</h1> <div className="grid"> <div className="grid__item one-third@palm-wide-and-up"> <ul className="soft-left"> <li onClick={linkTo("Hidden")}> <a href="#"><h6>Hidden</h6></a> </li> </ul> </div> </div> </div> </div> )) ;
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21.29 6.75a.9839.9839 0 0 0-1.4 0l-.89.88.03-.56-3.46-3.48c-.38-.38-.89-.59-1.42-.59h-4.3c-.53 0-1.04.21-1.42.59L4.97 7.07l.03.5-.89-.87c-.39-.38-1.01-.38-1.39.01l-.02.02c-.38.39-.38 1.02.02 1.4L4.66 10h14.69l1.92-1.84c.4-.38.41-1.02.02-1.41zm-15.5 11.4c.08 1.04.95 1.85 2 1.85h8.43c1.05 0 1.92-.81 1.99-1.85l.49-6.6H5.3l.49 6.6z" /> , 'TakeoutDiningRounded');
// Title : Simple AI Agent Demo - using neural nets // Author : David Imrie // Date : April 2017 // Contact : @smallfatcat // Repo : https://github.com/smallfatcat/nettestv1 // version : Alpha 0.1 // // Neural Nets Powered by : http://cs.stanford.edu/people/karpathy/convnetjs/ // : https://github.com/karpathy/convnetjs // : LICENSE - MIT (see LICENSE file) // 'use strict'; const R_UP = 0; const R_RIGHT = 1; const R_DOWN = 2; const R_LEFT = 3; const T_CW = 0; const T_CCW = 1; const B_SMART = 0; const B_DUMB = 1; var frameTime = 0; var numberActions = 6; var numberActionsLabel = [ 'F', 'CW', 'CCW', 'L', 'R', 'E' ] var tickCompleted = true; var trainingRuns = 0; var testdata = []; var label = []; var runs = 0; var cycleTraining = false; var autoTraining = false; var slowDraw = false; var lastError = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; label.push(6); //var net = new convnetjs.Net(); var simRunning = false; var rotLabels = ['up','right','down','left']; var turnLabels = ['cw', 'ccw']; var mapLabels = ['empty','wall','food','poison','water','vis']; var worldMap = new World(); buildWorld(); // Create Agents var agents = []; agents.push(new Agent(150,250,B_SMART,0)); agents.push(new Agent(350,250,B_SMART,1)); //agents.push(new Agent(250,250,B_DUMB)); var routeTimer; var loopTimer; var visualFieldArray = visFieldGen(); $(document).ready( start ); function start() { buildActionButtons(); drawAll(); loopTimer = setInterval(checkSimRunning, 10); } function resetWorld() { worldMap = new World(); buildWorld(); agents[0].x = 150; agents[0].y = 250; agents[1].x = 350; agents[1].y = 250; } function resetAgents(){ var netData1 = JSON.stringify(agents[0].brain.value_net.toJSON()); var netData2 = JSON.stringify(agents[1].brain.value_net.toJSON()); var gen1 = agents[0].brainGen; var gen2 = agents[1].brainGen; agents = []; agents.push(new Agent(150,250,B_SMART,0)); agents.push(new Agent(350,250,B_SMART,1)); agents[0].brain.value_net.fromJSON(JSON.parse(netData1)); agents[1].brain.value_net.fromJSON(JSON.parse(netData2)); agents[0].brainGen = gen1; agents[1].brainGen = gen1; stoplearn(); // also stop learning } function autoTrain(){ savenetLS(); resetWorld(); resetAgents(); loadnetLS(); startlearn(); runs = 0; } function buildWorld() { // Create outer walls for (var x = 50; x < 451; x++){ worldMap.map[x][50] = 1; worldMap.map[x][450] = 1; } for (var y = 50; y < 451; y++){ worldMap.map[50][y] = 1; worldMap.map[450][y] = 1; } // Inside walls for (var i = 50; i < 451; i++){ worldMap.map[250][i] = 1; } // Create food block for(var i=0; i < 50; i++){ var x = Math.floor(Math.random()*180)+ 60; var y = Math.floor(Math.random()*380)+ 60; for(var x2 = 0;x2<10;x2++){ for(var y2 = 0;y2<10;y2++){ if(worldMap.map[x+x2][y+y2] != 2 && worldMap.map[x+x2][y+y2] != 1){ worldMap.map[x+x2][y+y2] = 2; worldMap.foodTotal++; worldMap.map[x+x2+200][y+y2] = 2; worldMap.foodTotal++; } } } } // Create poison block for(var i=0; i < 25; i++){ var x = Math.floor(Math.random()*180)+ 60; var y = Math.floor(Math.random()*380)+ 60; for(var x2 = 0;x2<5;x2++){ for(var y2 = 0;y2<5;y2++){ if(worldMap.map[x+x2][y+y2] != 2 && worldMap.map[x+x2][y+y2] != 1){ worldMap.map[x+x2][y+y2] = 8; worldMap.foodTotal++; worldMap.map[x+x2+200][y+y2] = 8; worldMap.foodTotal++; } } } } /* // Create food for (var i=0; i < 500; i++){ var x = Math.floor(Math.random()*398)+ 51; var y = Math.floor(Math.random()*398)+ 51; if(worldMap.map[x][y] != 2 && worldMap.map[x][y] != 1){ worldMap.map[x][y] = 2; worldMap.foodTotal++; } if(worldMap.map[x+1][y] != 2 && worldMap.map[x+1][y] != 1){ worldMap.map[x+1][y] = 2; worldMap.foodTotal++; } if(worldMap.map[x][y+1] != 2 && worldMap.map[x][y+1] != 1){ worldMap.map[x][y+1] = 2; worldMap.foodTotal++; } if(worldMap.map[x+1][y+1] != 2 && worldMap.map[x+1][y+1] != 1){ worldMap.map[x+1][y+1] = 2; worldMap.foodTotal++; } } */ /* // Create poison for (var i=0; i < 100; i++){ var x = Math.floor(Math.random()*398)+ 51; var y = Math.floor(Math.random()*398)+ 51; if(worldMap.map[x][y] != 2 && worldMap.map[x][y] != 1){ worldMap.map[x][y] = 8; worldMap.poison++; } if(worldMap.map[x+1][y] != 2 && worldMap.map[x+1][y] != 1){ worldMap.map[x+1][y] = 8; worldMap.poison++; } if(worldMap.map[x][y+1] != 2 && worldMap.map[x][y+1] != 1){ worldMap.map[x][y+1] = 8; worldMap.poison++; } if(worldMap.map[x+1][y+1] != 2 && worldMap.map[x+1][y+1] != 1){ worldMap.map[x+1][y+1] = 8; worldMap.poison++; } } */ } function checkFood() { var foodTotal = worldMap.foodTotal; if(foodTotal < 1000){ // Create food block for(var i=0; i < 50; i++){ var x = Math.floor(Math.random()*398)+ 51; var y = Math.floor(Math.random()*398)+ 51; for(var x2 = 0;x2<10;x2++){ for(var y2 = 0;y2<10;y2++){ if(worldMap.map[x+x2][y+y2] != 2 && worldMap.map[x+x2][y+y2] != 1){ worldMap.map[x+x2][y+y2] = 2; worldMap.foodTotal++; } } } } } } function checkSimRunning() { var startTime = Date.now(); if(!tickCompleted){ console.log('slowdown detected'); } if(simRunning && tickCompleted){ if(cycleTraining){ if(runs%100 == 0){ for(var agent of agents){ if(agent.brain.learning){ agent.brain.learning = false; } else{ agent.brain.learning = true; } } } } if(autoTraining){ if(runs%31000 == 0 && runs != 0){ autoTrain(); } } tickCompleted = false; clockTick(); tickCompleted = true; } if(!simRunning && tickCompleted){ //MyAgent.sense(); //MyAgent.calcReward(); } // Draw Everything drawAll(); frameTime = Date.now() - startTime; } function clockTick() { runs++; checkFood(); // Calculate sensor readings //MyAgent.sense(); for(var agent of agents){ // get inputs var brainInputs = []; if(agent.brainType == B_SMART){ for(var pix of agent.sensors[0].outputs[0]){ brainInputs.push(pix); } for(var pix of agent.sensors[0].outputs[1]){ brainInputs.push(pix); } for(var pix of agent.sensors[0].outputs[2]){ brainInputs.push(pix); } brainInputs.push(agent.rot === 0 ? 1:0); brainInputs.push(agent.rot === 1 ? 1:0); brainInputs.push(agent.rot === 2 ? 1:0); brainInputs.push(agent.rot === 3 ? 1:0); brainInputs.push(agent.tasteOutput); brainInputs.push(agent.tastePoison); } // Get action from brain var action = agent.brain.forward(brainInputs); // Do brain action agent.doAction(action); if(agent.brainType == B_SMART){ // Calculate sensor readings agent.sense(); // Calculate rewards agent.calcReward(); // Train brain with reward agent.brain.backward(agent.reward); } } } // Adapted from deepqlearn demo by @karpathy from // http://cs.stanford.edu/people/karpathy/convnetjs/ function brainMaker(brainType, netType) { var num_inputs = 39; // 3 eyes, each sees 11 pixels color (wall, food proximity), 4 rotation, 2 taste var num_actions = 6; // 3 possible actions agent can do var temporal_window = 1; // amount of temporal memory. 0 = agent lives in-the-moment :) if(brainType == B_SMART){ var network_size = num_inputs*temporal_window + num_actions*temporal_window + num_inputs; // the value function network computes a value of taking any of the possible actions // given an input state. Here we specify one explicitly the hard way // but user could also equivalently instead use opt.hidden_layer_sizes = [20,20] // to just insert simple relu hidden layers. var layer_defs = []; layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:network_size}); if(netType == 0){ layer_defs.push({type:'fc', num_neurons: 100, activation:'relu'}); layer_defs.push({type:'fc', num_neurons: 50, activation:'relu'}); } if(netType == 1){ layer_defs.push({type:'fc', num_neurons: 50, activation:'relu'}); layer_defs.push({type:'fc', num_neurons: 50, activation:'relu'}); } layer_defs.push({type:'regression', num_neurons:num_actions}); // options for the Temporal Difference learner that trains the above net // by backpropping the temporal difference learning rule. var tdtrainer_options = {learning_rate:0.001, momentum:0.0, batch_size:64, l2_decay:0.01}; var opt = {}; opt.temporal_window = temporal_window; opt.experience_size = 30000; opt.start_learn_threshold = 1000; opt.gamma = 0.7; opt.learning_steps_total = 30000; opt.learning_steps_burnin = 3000; opt.epsilon_min = 0.05; opt.epsilon_test_time = 0.05; opt.layer_defs = layer_defs; opt.tdtrainer_options = tdtrainer_options; var brain; return brain = new deepqlearn.Brain(num_inputs, num_actions, opt); // woohoo } if(brainType == B_DUMB){ return brain = new DumbBrain(num_actions); } } function savenetLS() { var netData1 = JSON.stringify(agents[0].brain.value_net.toJSON()); var netData2 = JSON.stringify(agents[1].brain.value_net.toJSON()); var netData1History = JSON.stringify({size: netData1.length, generation: agents[0].brainGen}); var netData2History = JSON.stringify({size: netData2.length, generation: agents[1].brainGen}); console.log('Agent 1 saved to LS: '+netData1.length); console.log('Agent 2 saved to LS: '+netData2.length); localStorage.setItem('netData1',netData1); localStorage.setItem('netData1History',netData1History); localStorage.setItem('netData2History',netData2History); localStorage.setItem('netData2',netData2); $('#loadTxt').empty(); $('#loadTxt').append('Current Net Saved To LS'); } function loadnetLS() { var netData1 = localStorage.getItem('netData1'); var netData2 = localStorage.getItem('netData2'); var netData1History = JSON.parse(localStorage.getItem('netData1History')); var netData2History = JSON.parse(localStorage.getItem('netData2History')); console.log('Agent 1 loaded from LS: '+netData1.length); console.log('Agent 2 loaded from LS: '+netData2.length); agents[0].brain.value_net.fromJSON(JSON.parse(netData1)); agents[1].brain.value_net.fromJSON(JSON.parse(netData2)); agents[0].brainGen = netData1History.generation+1; agents[1].brainGen = netData2History.generation+1; stoplearn(); // also stop learning $('#loadTxt').empty(); $('#loadTxt').append('Net Loaded From LS'); } function savenet() { var j = agents[0].brain.value_net.toJSON(); var t = JSON.stringify(j); document.getElementById('brainText').value = t; $('#loadTxt').empty(); $('#loadTxt').append('Current Net Saved'); } function loadnet() { var t = document.getElementById('brainText').value; var j = JSON.parse(t); agents[0].brain.value_net.fromJSON(j); stoplearn(); // also stop learning $('#loadTxt').empty(); $('#loadTxt').append('Net Loaded'); } function startlearn() { for(var agent of agents){ agent.brain.learning = true; cycleTraining = false; } } function stoplearn() { for(var agent of agents){ agent.brain.learning = false; cycleTraining = false; } } function runsim() { simRunning = true; } function pausesim() { simRunning = false; } function cycletrain() { if(cycleTraining){ cycleTraining = false; } else{ cycleTraining = true; } } function autoButton(){ if(autoTraining){ autoTraining = false; } else{ autoTraining = true; } } function slowButton(){ if(slowDraw){ slowDraw = false; } else{ slowDraw = true; } } function butAction(action) { if(!simRunning){ // Do action agents[0].doAction(action); // Calculate sensor readings agents[0].sense(); // Calculate rewards agents[0].calcReward(); } console.log(action); } function buildActionButtons() { var buttonTxt = ''; for(var i =0;i<numberActions;i++){ buttonTxt += '<button id="action'+i+'" class="ui-button ui-widget ui-corner-all my-button" onclick="butAction( '+i+' )">'+numberActionsLabel[i]+'</button>'; } $('#controlButtons').empty(); $('#controlButtons').append(buttonTxt); } function getLineCoords(x1,y1,x2,y2) { var lineCoords = []; if(x1==x2){ if(y1<y2){ for(var i = y1; i <= y2; i++){ lineCoords.push([x1,i]); } } else{ for(var i = y1; i >= y2; i--){ lineCoords.push([x1,i]); } } } if(y1==y2){ if(x1<x2){ for(var i = x1; i <= x2; i++){ lineCoords.push([i,y1]); } } else{ for(var i = x1; i >= x2; i--){ lineCoords.push([i,y1]); } } } return lineCoords; } function buildVisField(width,range,rot) { var visField = []; var dist = 0; var currentWidth = width; var startx = (width-1)/2; var pixelc = []; for(var depth=0;depth<=range;depth++){ var line = []; if(rot == R_UP){ line = getLineCoords(-startx, (depth*-1)-1, startx, (depth*-1)-1); } if(rot == R_DOWN){ line = getLineCoords(startx, depth+1, -startx, depth+1); } if(rot == R_RIGHT){ line = getLineCoords(depth+1, -startx, depth+1, startx); } if(rot == R_LEFT){ line = getLineCoords((depth*-1)-1, startx, (depth*-1)-1, -startx); } if(depth ==0){ pixelc = line; } for(var m = 0; m < line.length; m++){ line[m].push(depth); // Check this works later var pixel = Math.round(m/(line.length-1)*(width-1)); line[m].push(pixel); //calc distance var distance = Math.sqrt(Math.pow( ( line[m][0] - pixelc[pixel][0] ), 2) + Math.pow(line[m][1] - pixelc[pixel][1], 2)); line[m].push(distance); } startx++; visField = visField.concat(line); } return visField; } function visFieldGen() { var visFieldArray = []; visFieldArray.push(buildVisField(11,100,R_UP).filter(isInRange)); visFieldArray.push(buildVisField(11,100,R_RIGHT).filter(isInRange)); visFieldArray.push(buildVisField(11,100,R_DOWN).filter(isInRange)); visFieldArray.push(buildVisField(11,100,R_LEFT).filter(isInRange)); return visFieldArray; } function isInRange(v) { return v[4] <= 100; }
/** * Saving OpenLayers map information via cookies * * Based on code from OpenCycleMap / OpenStreetMap * Licensed under the GPLv2 license: * http://www.gnu.org/licenses/gpl-2.0.html * */ MapDisplay = { map: null, init: function (m) { this.map = m; map.events.register("moveend", map, this.updateLocation); map.events.register("changelayer", map, this.updateLocation); }, updateLocation: function () { if (map.getCenter()) { var lonlat = map.getCenter().clone().transform(map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326")); var zoom = map.getZoom(); var layers = MapDisplay.getMapLayers(); var loc_string = lonlat.lon + "|" + lonlat.lat + "|" + zoom + "|" + layers; $.cookie('_cyclescape_location', loc_string, { path: "/", expires: 30 }); } }, getMapLayers: function () { var layerConfig = ""; for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) { layerConfig += layers[i] == map.baseLayer ? "B" : "0"; } for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) { layerConfig += layers[i].getVisibility() ? "T" : "F"; } return layerConfig; }, setSavedLayers: function() { var savedLayers = MapDisplay.getSavedLayers(); if (savedLayers) { MapDisplay.setMapLayers(savedLayers); } }, setMapLayers: function(layerConfig) { var l = 0; for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) { var c = layerConfig.charAt(l++); if (c == "B") { map.setBaseLayer(layers[i]); } } while (layerConfig.charAt(l) == "B" || layerConfig.charAt(l) == "0") { l++; } for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) { var c = layerConfig.charAt(l++); if (c == "T") { layers[i].setVisibility(true); } else if(c == "F") { layers[i].setVisibility(false); } } }, getSavedLayers: function () { var cookietext = $.cookie('_cyclescape_location'); var layers; if (cookietext) { var cb = cookietext.split('|'); //centre = lonLatToMercator( new OpenLayers.LonLat(cb[0], cb[1])); //zoom = cb[2]; layers = cb[3]; } return layers; } }
/* global angular */ 'use strict'; angular.module('hgApp.service.firebase', ['firebase']) // a simple utility to create references to Firebase paths .factory('firebaseRef', ['Firebase', 'FBURL', function (Firebase, FBURL) { /** * @function * @name firebaseRef * @param {String|Array...} path * @return a Firebase instance */ return function (path) { return new Firebase(pathRef([FBURL].concat(Array.prototype.slice.call(arguments)))); }; } ]) // a simple utility to create $firebase objects from angularFire .service('syncData', ['$firebase', 'firebaseRef', function ($firebase, firebaseRef) { /** * @function * @name syncData * @param {String|Array...} path * @param {int} [limit] * @return a Firebase instance */ return function (path, limit) { var ref = firebaseRef(path); limit && (ref = ref.limit(limit)); return $firebase(ref); }; } ]) .service('repository', ['$q', 'firebaseRef', 'syncData', function ($q, firebaseRef, syncData) { return { /** * Retrieve a list of specified resources for the logged in user. * * @param {string} userId The logged in user's id. * @param {string} collection The name of the resource collection * @param {int} [limit] Optional. The maximum properties to return. * @returns A list of resource objects */ list: function (user, collection, limit) { return user ? syncData(['users', user.id, collection], limit) : syncData(collection, limit); }, find: function (user, collection, refId) { return user ? syncData(['users', user.id, collection, refId]) : syncData([collection, refId]); }, /** * Save a new resource for the logged in user. * * @param {string} userId The logged in user's id * @param {string} collection The name of the resource collection * @param {Object} resourceObj The new resource object * @param {Function} [callback] Optional callback after completion. * @returns {string} the unique id of the new resource */ save: function (user, collection, resourceObj, callback) { return firebaseRef(['users', user.id, collection], resourceObj.id).set(resourceObj, callback); } }; }]); function pathRef(args) { for (var i = 0; i < args.length; i++) { if (typeof (args[i]) === 'object') { args[i] = pathRef(args[i]); } } return args.join('/'); }
import { Suite } from 'benchmark'; import { benchmarkFatestStatus, benchmarkCycle } from '../../.fixtures/benchmark'; import keys from './Object.keys.next'; const value = { "A": 329.5562145531701, "r": 26.143494324762816, "a": 30.839810129349885, "y": 382.8652049927137, ".": 209.46051680295318, "p": 137.36783262171326, "o": 219.8572800988794, "t": 288.9968742238308, "e": 194.62894110794738, "s": 224.23908483789333, "l": 424.41911251825417, "i": 477.9652177588223, "c": 330.74371750226663, "(": 104.86047260472742, ")": 272.78370122420034, " ": 4.4292658503792826, "T": 378.70883698486125, "h": 259.51928886360355, "m": 84.64812804711951, "d": 22.069789149926745, "u": 239.72145926209964, "n": 227.63784974188695, "w": 6.747560890985382, "f": 352.7482758607275, "b": 251.69349658342287, "j": 203.1028006554987, "g": 436.6636307730445 }; const cachedKeys = Object.keys; new Suite() .add('Object.keys', () => { Object.keys(value); }) .add('Object.keys cached', () => { cachedKeys(value); }) .add('describeType.internal.keys', () => { keys(value); }) .on('cycle', benchmarkCycle()) .on('complete', benchmarkFatestStatus(/[^describeType]/)) .run({ async: false });
import React from "react"; import TextareaBase from "./component/TextareaBase"; export default class TextareaF extends React.Component { render() { const { label, labelHide, kind, ...others } = this.props; if (kind && kind.startsWith('form')) { return ( <div className="form-group"> <label className={kind.endsWith('label') ? null : 'sr-only'}>{label}</label> <TextareaBase {...others} /> </div> ) } else if (kind == 'base') { return ( <TextareaBase {...others} /> ) } else { return ( <TextareaBase {...others} /> ) } } }
"use strict"; var utils = exports; /** * @returns {window} */ utils.getWindow = function () { return window; }; /** * @returns {HTMLDocument} */ utils.getDocument = function () { return document; }; /** * @returns {HTMLElement} */ utils.getBody = function () { return document.getElementsByTagName("body")[0]; }; /** * Get the current x/y position crossbow * @returns {{x: *, y: *}} */ utils.getBrowserScrollPosition = function () { var $window = exports.getWindow(); var $document = exports.getDocument(); var scrollX; var scrollY; var dElement = $document.documentElement; var dBody = $document.body; if ($window.pageYOffset !== undefined) { scrollX = $window.pageXOffset; scrollY = $window.pageYOffset; } else { scrollX = dElement.scrollLeft || dBody.scrollLeft || 0; scrollY = dElement.scrollTop || dBody.scrollTop || 0; } return { x: scrollX, y: scrollY }; }; /** * @returns {{x: number, y: number}} */ utils.getScrollSpace = function () { var $document = exports.getDocument(); var dElement = $document.documentElement; var dBody = $document.body; return { x: dBody.scrollHeight - dElement.clientWidth, y: dBody.scrollHeight - dElement.clientHeight }; }; /** * Saves scroll position into cookies */ utils.saveScrollPosition = function () { var pos = utils.getBrowserScrollPosition(); pos = [pos.x, pos.y]; utils.getDocument.cookie = "bs_scroll_pos=" + pos.join(","); }; /** * Restores scroll position from cookies */ utils.restoreScrollPosition = function () { var pos = utils.getDocument().cookie.replace(/(?:(?:^|.*;\s*)bs_scroll_pos\s*\=\s*([^;]*).*$)|^.*$/, "$1").split(","); utils.getWindow().scrollTo(pos[0], pos[1]); }; /** * @param tagName * @param elem * @returns {*|number} */ utils.getElementIndex = function (tagName, elem) { var allElems = utils.getDocument().getElementsByTagName(tagName); return Array.prototype.indexOf.call(allElems, elem); }; /** * Force Change event on radio & checkboxes (IE) */ utils.forceChange = function (elem) { elem.blur(); elem.focus(); }; /** * @param elem * @returns {{tagName: (elem.tagName|*), index: *}} */ utils.getElementData = function (elem) { var tagName = elem.tagName; var index = utils.getElementIndex(tagName, elem); return { tagName: tagName, index: index }; }; /** * @param {string} tagName * @param {number} index */ utils.getSingleElement = function (tagName, index) { var elems = utils.getDocument().getElementsByTagName(tagName); return elems[index]; }; /** * Get the body element */ utils.getBody = function () { return utils.getDocument().getElementsByTagName("body")[0]; }; /** * @param {{x: number, y: number}} pos */ utils.setScroll = function (pos) { utils.getWindow().scrollTo(pos.x, pos.y); }; /** * Hard reload */ utils.reloadBrowser = function () { utils.getWindow().location.reload(true); }; /** * Foreach polyfill * @param coll * @param fn */ utils.forEach = function (coll, fn) { for (var i = 0, n = coll.length; i < n; i += 1) { fn(coll[i], i, coll); } }; /** * Are we dealing with old IE? * @returns {boolean} */ utils.isOldIe = function () { return typeof utils.getWindow().attachEvent !== "undefined"; }; /** * Split the URL information * @returns {object} */ utils.getLocation = function (url) { var location = utils.getDocument().createElement("a"); location.href = url; if (location.host === "") { location.href = location.href; } return location; };
/* * jPlayer Plugin for jQuery JavaScript Library * http://www.jplayer.org * * Copyright (c) 2009 - 2014 Happyworm Ltd * Licensed under the MIT license. * http://opensource.org/licenses/MIT * * Author: Mark J Panaghiston * Version: 2.9.2 * Date: 14th December 2014 */ /* Support for Zepto 1.0 compiled with optional data module. * For AMD or NODE/CommonJS support, you will need to manually switch the related 2 lines in the code below. * Search terms: "jQuery Switch" and "Zepto Switch" */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); // jQuery Switch // define(['zepto'], factory); // Zepto Switch } else if (typeof exports === 'object') { // Node/CommonJS factory(require('jquery')); // jQuery Switch //factory(require('zepto')); // Zepto Switch } else { // Browser globals if(root.jQuery) { // Use jQuery if available factory(root.jQuery); } else { // Otherwise, use Zepto factory(root.Zepto); } } }(this, function ($, undefined) { // Adapted from jquery.ui.widget.js (1.8.7): $.widget.bridge - Tweaked $.data(this,XYZ) to $(this).data(XYZ) for Zepto $.fn.jPlayer = function( options ) { var name = "jPlayer"; var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $(this).data( name ), methodValue = instance && $.isFunction( instance[options] ) ? instance[ options ].apply( instance, args ) : instance; if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $(this).data( name ); if ( instance ) { // instance.option( options || {} )._init(); // Orig jquery.ui.widget.js code: Not recommend for jPlayer. ie., Applying new options to an existing instance (via the jPlayer constructor) and performing the _init(). The _init() is what concerns me. It would leave a lot of event handlers acting on jPlayer instance and the interface. instance.option( options || {} ); // The new constructor only changes the options. Changing options only has basic support atm. } else { $(this).data( name, new $.jPlayer( options, this ) ); } }); } return returnValue; }; $.jPlayer = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this.element = $(element); this.options = $.extend(true, {}, this.options, options ); var self = this; this.element.bind( "remove.jPlayer", function() { self.destroy(); }); this._init(); } }; // End of: (Adapted from jquery.ui.widget.js (1.8.7)) // Zepto is missing one of the animation methods. if(typeof $.fn.stop !== 'function') { $.fn.stop = function() {}; } // Emulated HTML5 methods and properties $.jPlayer.emulateMethods = "load play pause"; $.jPlayer.emulateStatus = "src readyState networkState currentTime duration paused ended playbackRate"; $.jPlayer.emulateOptions = "muted volume"; // Reserved event names generated by jPlayer that are not part of the HTML5 Media element spec $.jPlayer.reservedEvent = "ready flashreset resize repeat error warning"; // Events generated by jPlayer $.jPlayer.event = {}; $.each( [ 'ready', 'setmedia', // Fires when the media is set 'flashreset', // Similar to the ready event if the Flash solution is set to display:none and then shown again or if it's reloaded for another reason by the browser. For example, using CSS position:fixed on Firefox for the full screen feature. 'resize', // Occurs when the size changes through a full/restore screen operation or if the size/sizeFull options are changed. 'repeat', // Occurs when the repeat status changes. Usually through clicks on the repeat button of the interface. 'click', // Occurs when the user clicks on one of the following: poster image, html video, flash video. 'error', // Event error code in event.jPlayer.error.type. See $.jPlayer.error 'warning', // Event warning code in event.jPlayer.warning.type. See $.jPlayer.warning // Other events match HTML5 spec. 'loadstart', 'progress', 'suspend', 'abort', 'emptied', 'stalled', 'play', 'pause', 'loadedmetadata', 'loadeddata', 'waiting', 'playing', 'canplay', 'canplaythrough', 'seeking', 'seeked', 'timeupdate', 'ended', 'ratechange', 'durationchange', 'volumechange' ], function() { $.jPlayer.event[ this ] = 'jPlayer_' + this; } ); $.jPlayer.htmlEvent = [ // These HTML events are bubbled through to the jPlayer event, without any internal action. "loadstart", // "progress", // jPlayer uses internally before bubbling. // "suspend", // jPlayer uses internally before bubbling. "abort", // "error", // jPlayer uses internally before bubbling. "emptied", "stalled", // "play", // jPlayer uses internally before bubbling. // "pause", // jPlayer uses internally before bubbling. "loadedmetadata", // "loadeddata", // jPlayer uses internally before bubbling. // "waiting", // jPlayer uses internally before bubbling. // "playing", // jPlayer uses internally before bubbling. "canplay", "canplaythrough" // "seeking", // jPlayer uses internally before bubbling. // "seeked", // jPlayer uses internally before bubbling. // "timeupdate", // jPlayer uses internally before bubbling. // "ended", // jPlayer uses internally before bubbling. // "ratechange" // jPlayer uses internally before bubbling. // "durationchange" // jPlayer uses internally before bubbling. // "volumechange" // jPlayer uses internally before bubbling. ]; $.jPlayer.pause = function() { $.jPlayer.prototype.destroyRemoved(); $.each($.jPlayer.prototype.instances, function(i, element) { if(element.data("jPlayer").status.srcSet) { // Check that media is set otherwise would cause error event. element.jPlayer("pause"); } }); }; // Default for jPlayer option.timeFormat $.jPlayer.timeFormat = { showHour: false, showMin: true, showSec: true, padHour: false, padMin: true, padSec: true, sepHour: ":", sepMin: ":", sepSec: "" }; var ConvertTime = function() { this.init(); }; ConvertTime.prototype = { init: function() { this.options = { timeFormat: $.jPlayer.timeFormat }; }, time: function(s) { // function used on jPlayer.prototype._convertTime to enable per instance options. s = (s && typeof s === 'number') ? s : 0; var myTime = new Date(s * 1000), hour = myTime.getUTCHours(), min = this.options.timeFormat.showHour ? myTime.getUTCMinutes() : myTime.getUTCMinutes() + hour * 60, sec = this.options.timeFormat.showMin ? myTime.getUTCSeconds() : myTime.getUTCSeconds() + min * 60, strHour = (this.options.timeFormat.padHour && hour < 10) ? "0" + hour : hour, strMin = (this.options.timeFormat.padMin && min < 10) ? "0" + min : min, strSec = (this.options.timeFormat.padSec && sec < 10) ? "0" + sec : sec, strTime = ""; strTime += this.options.timeFormat.showHour ? strHour + this.options.timeFormat.sepHour : ""; strTime += this.options.timeFormat.showMin ? strMin + this.options.timeFormat.sepMin : ""; strTime += this.options.timeFormat.showSec ? strSec + this.options.timeFormat.sepSec : ""; return strTime; } }; var myConvertTime = new ConvertTime(); $.jPlayer.convertTime = function(s) { return myConvertTime.time(s); }; // Adapting jQuery 1.4.4 code for jQuery.browser. Required since jQuery 1.3.2 does not detect Chrome as webkit. $.jPlayer.uaBrowser = function( userAgent ) { var ua = userAgent.toLowerCase(); // Useragent RegExp var rwebkit = /(webkit)[ \/]([\w.]+)/; var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/; var rmsie = /(msie) ([\w.]+)/; var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/; var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }; // Platform sniffer for detecting mobile devices $.jPlayer.uaPlatform = function( userAgent ) { var ua = userAgent.toLowerCase(); // Useragent RegExp var rplatform = /(ipad|iphone|ipod|android|blackberry|playbook|windows ce|webos)/; var rtablet = /(ipad|playbook)/; var randroid = /(android)/; var rmobile = /(mobile)/; var platform = rplatform.exec( ua ) || []; var tablet = rtablet.exec( ua ) || !rmobile.exec( ua ) && randroid.exec( ua ) || []; if(platform[1]) { platform[1] = platform[1].replace(/\s/g, "_"); // Change whitespace to underscore. Enables dot notation. } return { platform: platform[1] || "", tablet: tablet[1] || "" }; }; $.jPlayer.browser = { }; $.jPlayer.platform = { }; var browserMatch = $.jPlayer.uaBrowser(navigator.userAgent); if ( browserMatch.browser ) { $.jPlayer.browser[ browserMatch.browser ] = true; $.jPlayer.browser.version = browserMatch.version; } var platformMatch = $.jPlayer.uaPlatform(navigator.userAgent); if ( platformMatch.platform ) { $.jPlayer.platform[ platformMatch.platform ] = true; $.jPlayer.platform.mobile = !platformMatch.tablet; $.jPlayer.platform.tablet = !!platformMatch.tablet; } // Internet Explorer (IE) Browser Document Mode Sniffer. Based on code at: // http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#GetMode $.jPlayer.getDocMode = function() { var docMode; if ($.jPlayer.browser.msie) { if (document.documentMode) { // IE8 or later docMode = document.documentMode; } else { // IE 5-7 docMode = 5; // Assume quirks mode unless proven otherwise if (document.compatMode) { if (document.compatMode === "CSS1Compat") { docMode = 7; // standards mode } } } } return docMode; }; $.jPlayer.browser.documentMode = $.jPlayer.getDocMode(); $.jPlayer.nativeFeatures = { init: function() { /* Fullscreen function naming influenced by W3C naming. * No support for: Mozilla Proposal: https://wiki.mozilla.org/Gecko:FullScreenAPI */ var d = document, v = d.createElement('video'), spec = { // http://www.w3.org/TR/fullscreen/ w3c: [ 'fullscreenEnabled', 'fullscreenElement', 'requestFullscreen', 'exitFullscreen', 'fullscreenchange', 'fullscreenerror' ], // https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode moz: [ 'mozFullScreenEnabled', 'mozFullScreenElement', 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozfullscreenchange', 'mozfullscreenerror' ], // http://developer.apple.com/library/safari/#documentation/WebKit/Reference/ElementClassRef/Element/Element.html // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html webkit: [ '', 'webkitCurrentFullScreenElement', 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitfullscreenchange', '' ], // http://developer.apple.com/library/safari/#documentation/AudioVideo/Reference/HTMLVideoElementClassReference/HTMLVideoElement/HTMLVideoElement.html // https://developer.apple.com/library/safari/samplecode/HTML5VideoEventFlow/Listings/events_js.html#//apple_ref/doc/uid/DTS40010085-events_js-DontLinkElementID_5 // Events: 'webkitbeginfullscreen' and 'webkitendfullscreen' webkitVideo: [ 'webkitSupportsFullscreen', 'webkitDisplayingFullscreen', 'webkitEnterFullscreen', 'webkitExitFullscreen', '', '' ], ms: [ '', 'msFullscreenElement', 'msRequestFullscreen', 'msExitFullscreen', 'MSFullscreenChange', 'MSFullscreenError' ] }, specOrder = [ 'w3c', 'moz', 'webkit', 'webkitVideo', 'ms' ], fs, i, il; this.fullscreen = fs = { support: { w3c: !!d[spec.w3c[0]], moz: !!d[spec.moz[0]], webkit: typeof d[spec.webkit[3]] === 'function', webkitVideo: typeof v[spec.webkitVideo[2]] === 'function', ms: typeof v[spec.ms[2]] === 'function' }, used: {} }; // Store the name of the spec being used and as a handy boolean. for(i = 0, il = specOrder.length; i < il; i++) { var n = specOrder[i]; if(fs.support[n]) { fs.spec = n; fs.used[n] = true; break; } } if(fs.spec) { var s = spec[fs.spec]; fs.api = { fullscreenEnabled: true, fullscreenElement: function(elem) { elem = elem ? elem : d; // Video element required for webkitVideo return elem[s[1]]; }, requestFullscreen: function(elem) { return elem[s[2]](); // Chrome and Opera want parameter (Element.ALLOW_KEYBOARD_INPUT) but Safari fails if flag used. }, exitFullscreen: function(elem) { elem = elem ? elem : d; // Video element required for webkitVideo return elem[s[3]](); } }; fs.event = { fullscreenchange: s[4], fullscreenerror: s[5] }; } else { fs.api = { fullscreenEnabled: false, fullscreenElement: function() { return null; }, requestFullscreen: function() {}, exitFullscreen: function() {} }; fs.event = {}; } } }; $.jPlayer.nativeFeatures.init(); // The keyboard control system. // The current jPlayer instance in focus. $.jPlayer.focus = null; // The list of element node names to ignore with key controls. $.jPlayer.keyIgnoreElementNames = "A INPUT TEXTAREA SELECT BUTTON"; // The function that deals with key presses. var keyBindings = function(event) { var f = $.jPlayer.focus, ignoreKey; // A jPlayer instance must be in focus. ie., keyEnabled and the last one played. if(f) { // What generated the key press? $.each( $.jPlayer.keyIgnoreElementNames.split(/\s+/g), function(i, name) { // The strings should already be uppercase. if(event.target.nodeName.toUpperCase() === name.toUpperCase()) { ignoreKey = true; return false; // exit each. } }); if(!ignoreKey) { // See if the key pressed matches any of the bindings. $.each(f.options.keyBindings, function(action, binding) { // The binding could be a null when the default has been disabled. ie., 1st clause in if() if( (binding && $.isFunction(binding.fn)) && ((typeof binding.key === 'number' && event.which === binding.key) || (typeof binding.key === 'string' && event.key === binding.key)) ) { event.preventDefault(); // Key being used by jPlayer, so prevent default operation. binding.fn(f); return false; // exit each. } }); } } }; $.jPlayer.keys = function(en) { var event = "keydown.jPlayer"; // Remove any binding, just in case enabled more than once. $(document.documentElement).unbind(event); if(en) { $(document.documentElement).bind(event, keyBindings); } }; // Enable the global key control handler ready for any jPlayer instance with the keyEnabled option enabled. $.jPlayer.keys(true); $.jPlayer.prototype = { count: 0, // Static Variable: Change it via prototype. version: { // Static Object script: "2.9.2", needFlash: "2.9.0", flash: "unknown" }, options: { // Instanced in $.jPlayer() constructor swfPath: "js", // Path to jquery.jplayer.swf. Can be relative, absolute or server root relative. solution: "html, flash", // Valid solutions: html, flash, aurora. Order defines priority. 1st is highest, supplied: "mp3", // Defines which formats jPlayer will try and support and the priority by the order. 1st is highest, auroraFormats: "wav", // List the aurora.js codecs being loaded externally. Its core supports "wav". Specify format in jPlayer context. EG., The aac.js codec gives the "m4a" format. preload: 'metadata', // HTML5 Spec values: none, metadata, auto. volume: 0.8, // The volume. Number 0 to 1. muted: false, remainingDuration: false, // When true, the remaining time is shown in the duration GUI element. toggleDuration: false, // When true, clicks on the duration toggle between the duration and remaining display. captureDuration: true, // When true, clicks on the duration are captured and no longer propagate up the DOM. playbackRate: 1, defaultPlaybackRate: 1, minPlaybackRate: 0.5, maxPlaybackRate: 4, wmode: "opaque", // Valid wmode: window, transparent, opaque, direct, gpu. backgroundColor: "#000000", // To define the jPlayer div and Flash background color. cssSelectorAncestor: "#jp_container_1", cssSelector: { // * denotes properties that should only be required when video media type required. _cssSelector() would require changes to enable splitting these into Audio and Video defaults. videoPlay: ".jp-video-play", // * play: ".jp-play", pause: ".jp-pause", stop: ".jp-stop", seekBar: ".jp-seek-bar", playBar: ".jp-play-bar", mute: ".jp-mute", unmute: ".jp-unmute", volumeBar: ".jp-volume-bar", volumeBarValue: ".jp-volume-bar-value", volumeMax: ".jp-volume-max", playbackRateBar: ".jp-playback-rate-bar", playbackRateBarValue: ".jp-playback-rate-bar-value", currentTime: ".jp-current-time", duration: ".jp-duration", title: ".jp-title", fullScreen: ".jp-full-screen", // * restoreScreen: ".jp-restore-screen", // * repeat: ".jp-repeat", repeatOff: ".jp-repeat-off", gui: ".jp-gui", // The interface used with autohide feature. noSolution: ".jp-no-solution" // For error feedback when jPlayer cannot find a solution. }, stateClass: { // Classes added to the cssSelectorAncestor to indicate the state. playing: "jp-state-playing", seeking: "jp-state-seeking", muted: "jp-state-muted", looped: "jp-state-looped", fullScreen: "jp-state-full-screen", noVolume: "jp-state-no-volume" }, useStateClassSkin: false, // A state class skin relies on the state classes to change the visual appearance. The single control toggles the effect, for example: play then pause, mute then unmute. autoBlur: true, // GUI control handlers will drop focus after clicks. smoothPlayBar: false, // Smooths the play bar transitions, which affects clicks and short media with big changes per second. fullScreen: false, // Native Full Screen fullWindow: false, autohide: { restored: false, // Controls the interface autohide feature. full: true, // Controls the interface autohide feature. fadeIn: 200, // Milliseconds. The period of the fadeIn anim. fadeOut: 600, // Milliseconds. The period of the fadeOut anim. hold: 1000 // Milliseconds. The period of the pause before autohide beings. }, loop: false, repeat: function(event) { // The default jPlayer repeat event handler if(event.jPlayer.options.loop) { $(this).unbind(".jPlayerRepeat").bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function() { $(this).jPlayer("play"); }); } else { $(this).unbind(".jPlayerRepeat"); } }, nativeVideoControls: { // Works well on standard browsers. // Phone and tablet browsers can have problems with the controls disappearing. }, noFullWindow: { msie: /msie [0-6]\./, ipad: /ipad.*?os [0-4]\./, iphone: /iphone/, ipod: /ipod/, android_pad: /android [0-3]\.(?!.*?mobile)/, android_phone: /(?=.*android)(?!.*chrome)(?=.*mobile)/, blackberry: /blackberry/, windows_ce: /windows ce/, iemobile: /iemobile/, webos: /webos/ }, noVolume: { ipad: /ipad/, iphone: /iphone/, ipod: /ipod/, android_pad: /android(?!.*?mobile)/, android_phone: /android.*?mobile/, blackberry: /blackberry/, windows_ce: /windows ce/, iemobile: /iemobile/, webos: /webos/, playbook: /playbook/ }, timeFormat: { // Specific time format for this instance. The supported options are defined in $.jPlayer.timeFormat // For the undefined options we use the default from $.jPlayer.timeFormat }, keyEnabled: false, // Enables keyboard controls. audioFullScreen: false, // Enables keyboard controls to enter full screen with audio media. keyBindings: { // The key control object, defining the key codes and the functions to execute. // The parameter, f = $.jPlayer.focus, will be checked truethy before attempting to call any of these functions. // Properties may be added to this object, in key/fn pairs, to enable other key controls. EG, for the playlist add-on. play: { key: 80, // p fn: function(f) { if(f.status.paused) { f.play(); } else { f.pause(); } } }, fullScreen: { key: 13, // enter fn: function(f) { if(f.status.video || f.options.audioFullScreen) { f._setOption("fullScreen", !f.options.fullScreen); } } }, muted: { key: 77, // m fn: function(f) { f._muted(!f.options.muted); } }, volumeUp: { key: 38, // flecha arriba fn: function(f) { f.volume(f.options.volume + 0.1); } }, volumeDown: { key: 40, // flecha abajo fn: function(f) { f.volume(f.options.volume - 0.1); } }, loop: { key: 76, // l fn: function(f) { f._loop(!f.options.loop); } } }, verticalVolume: false, // Calculate volume from the bottom of the volume bar. Default is from the left. Also volume affects either width or height. verticalPlaybackRate: false, globalVolume: false, // Set to make volume and muted changes affect all jPlayer instances with this option enabled idPrefix: "jp", // Prefix for the ids of html elements created by jPlayer. For flash, this must not include characters: . - + * / \ noConflict: "jQuery", emulateHtml: false, // Emulates the HTML5 Media element on the jPlayer element. consoleAlerts: true, // Alerts are sent to the console.log() instead of alert(). errorAlerts: false, warningAlerts: false }, optionsAudio: { size: { width: "100%", height: "480px", cssClass: "jp-video-270p" }, sizeFull: { width: "100%", height: "480px", cssClass: "jp-video-270p" } }, optionsVideo: { size: { width: "100%", height: "480px", cssClass: "jp-video-270p" }, sizeFull: { width: "100%", height: "100%", cssClass: "jp-video-full" } }, instances: {}, // Static Object status: { // Instanced in _init() src: "", media: {}, paused: true, format: {}, formatType: "", waitForPlay: true, // Same as waitForLoad except in case where preloading. waitForLoad: true, srcSet: false, video: false, // True if playing a video seekPercent: 0, currentPercentRelative: 0, currentPercentAbsolute: 0, currentTime: 0, duration: 0, remaining: 0, videoWidth: 0, // Intrinsic width of the video in pixels. videoHeight: 0, // Intrinsic height of the video in pixels. readyState: 0, networkState: 0, playbackRate: 1, // Warning - Now both an option and a status property ended: 0 /* Persistant status properties created dynamically at _init(): width height cssClass nativeVideoControls noFullWindow noVolume playbackRateEnabled // Warning - Technically, we can have both Flash and HTML, so this might not be correct if the Flash is active. That is a niche case. */ }, internal: { // Instanced in _init() ready: false // instance: undefined // domNode: undefined // htmlDlyCmdId: undefined // autohideId: undefined // mouse: undefined // cmdsIgnored }, solution: { // Static Object: Defines the solutions built in jPlayer. html: true, aurora: true, flash: true }, // 'MPEG-4 support' : canPlayType('video/mp4; codecs="mp4v.20.8"') format: { // Static Object mp3: { codec: 'audio/mpeg', flashCanPlay: true, media: 'audio' }, m4a: { // AAC / MP4 codec: 'audio/mp4; codecs="mp4a.40.2"', flashCanPlay: true, media: 'audio' }, m3u8a: { // AAC / MP4 / Apple HLS codec: 'application/vnd.apple.mpegurl; codecs="mp4a.40.2"', flashCanPlay: false, media: 'audio' }, m3ua: { // M3U codec: 'audio/mpegurl', flashCanPlay: false, media: 'audio' }, oga: { // OGG codec: 'audio/ogg; codecs="vorbis, opus"', flashCanPlay: false, media: 'audio' }, flac: { // FLAC codec: 'audio/x-flac', flashCanPlay: false, media: 'audio' }, wav: { // PCM codec: 'audio/wav; codecs="1"', flashCanPlay: false, media: 'audio' }, webma: { // WEBM codec: 'audio/webm; codecs="vorbis"', flashCanPlay: false, media: 'audio' }, fla: { // FLV / F4A codec: 'audio/x-flv', flashCanPlay: true, media: 'audio' }, rtmpa: { // RTMP AUDIO codec: 'audio/rtmp; codecs="rtmp"', flashCanPlay: true, media: 'audio' }, m4v: { // H.264 / MP4 codec: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"', flashCanPlay: true, media: 'video' }, m3u8v: { // H.264 / AAC / MP4 / Apple HLS codec: 'application/vnd.apple.mpegurl; codecs="avc1.42E01E, mp4a.40.2"', flashCanPlay: false, media: 'video' }, m3uv: { // M3U codec: 'audio/mpegurl', flashCanPlay: false, media: 'video' }, ogv: { // OGG codec: 'video/ogg; codecs="theora, vorbis"', flashCanPlay: false, media: 'video' }, webmv: { // WEBM codec: 'video/webm; codecs="vorbis, vp8"', flashCanPlay: false, media: 'video' }, flv: { // FLV / F4V codec: 'video/x-flv', flashCanPlay: true, media: 'video' }, rtmpv: { // RTMP VIDEO codec: 'video/rtmp; codecs="rtmp"', flashCanPlay: true, media: 'video' } }, _init: function() { var self = this; this.element.empty(); this.status = $.extend({}, this.status); // Copy static to unique instance. this.internal = $.extend({}, this.internal); // Copy static to unique instance. // Initialize the time format this.options.timeFormat = $.extend({}, $.jPlayer.timeFormat, this.options.timeFormat); // On iOS, assume commands will be ignored before user initiates them. this.internal.cmdsIgnored = $.jPlayer.platform.ipad || $.jPlayer.platform.iphone || $.jPlayer.platform.ipod; this.internal.domNode = this.element.get(0); // Add key bindings focus to 1st jPlayer instanced with key control enabled. if(this.options.keyEnabled && !$.jPlayer.focus) { $.jPlayer.focus = this; } // A fix for Android where older (2.3) and even some 4.x devices fail to work when changing the *audio* SRC and then playing immediately. this.androidFix = { setMedia: false, // True when media set play: false, // True when a progress event will instruct the media to play pause: false, // True when a progress event will instruct the media to pause at a time. time: NaN // The play(time) parameter }; if($.jPlayer.platform.android) { this.options.preload = this.options.preload !== 'auto' ? 'metadata' : 'auto'; // Default to metadata, but allow auto. } this.formats = []; // Array based on supplied string option. Order defines priority. this.solutions = []; // Array based on solution string option. Order defines priority. this.require = {}; // Which media types are required: video, audio. this.htmlElement = {}; // DOM elements created by jPlayer this.html = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.html.audio = {}; this.html.video = {}; this.aurora = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.aurora.formats = []; this.aurora.properties = []; this.flash = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.css = {}; this.css.cs = {}; // Holds the css selector strings this.css.jq = {}; // Holds jQuery selectors. ie., $(css.cs.method) this.ancestorJq = []; // Holds jQuery selector of cssSelectorAncestor. Init would use $() instead of [], but it is only 1.4+ this.options.volume = this._limitValue(this.options.volume, 0, 1); // Limit volume value's bounds. // Create the formats array, with prority based on the order of the supplied formats string $.each(this.options.supplied.toLowerCase().split(","), function(index1, value1) { var format = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.format[format]) { // Check format is valid. var dupFound = false; $.each(self.formats, function(index2, value2) { // Check for duplicates if(format === value2) { dupFound = true; return false; } }); if(!dupFound) { self.formats.push(format); } } }); // Create the solutions array, with prority based on the order of the solution string $.each(this.options.solution.toLowerCase().split(","), function(index1, value1) { var solution = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.solution[solution]) { // Check solution is valid. var dupFound = false; $.each(self.solutions, function(index2, value2) { // Check for duplicates if(solution === value2) { dupFound = true; return false; } }); if(!dupFound) { self.solutions.push(solution); } } }); // Create Aurora.js formats array $.each(this.options.auroraFormats.toLowerCase().split(","), function(index1, value1) { var format = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.format[format]) { // Check format is valid. var dupFound = false; $.each(self.aurora.formats, function(index2, value2) { // Check for duplicates if(format === value2) { dupFound = true; return false; } }); if(!dupFound) { self.aurora.formats.push(format); } } }); this.internal.instance = "jp_" + this.count; this.instances[this.internal.instance] = this.element; // Check the jPlayer div has an id and create one if required. Important for Flash to know the unique id for comms. if(!this.element.attr("id")) { this.element.attr("id", this.options.idPrefix + "_jplayer_" + this.count); } this.internal.self = $.extend({}, { id: this.element.attr("id"), jq: this.element }); this.internal.audio = $.extend({}, { id: this.options.idPrefix + "_audio_" + this.count, jq: undefined }); this.internal.video = $.extend({}, { id: this.options.idPrefix + "_video_" + this.count, jq: undefined }); this.internal.flash = $.extend({}, { id: this.options.idPrefix + "_flash_" + this.count, jq: undefined, swf: this.options.swfPath + (this.options.swfPath.toLowerCase().slice(-4) !== ".swf" ? (this.options.swfPath && this.options.swfPath.slice(-1) !== "/" ? "/" : "") + "jquery.jplayer.swf" : "") }); this.internal.poster = $.extend({}, { id: this.options.idPrefix + "_poster_" + this.count, jq: undefined }); // Register listeners defined in the constructor $.each($.jPlayer.event, function(eventName,eventType) { if(self.options[eventName] !== undefined) { self.element.bind(eventType + ".jPlayer", self.options[eventName]); // With .jPlayer namespace. self.options[eventName] = undefined; // Destroy the handler pointer copy on the options. Reason, events can be added/removed in other ways so this could be obsolete and misleading. } }); // Determine if we require solutions for audio, video or both media types. this.require.audio = false; this.require.video = false; $.each(this.formats, function(priority, format) { self.require[self.format[format].media] = true; }); // Now required types are known, finish the options default settings. if(this.require.video) { this.options = $.extend(true, {}, this.optionsVideo, this.options ); } else { this.options = $.extend(true, {}, this.optionsAudio, this.options ); } this._setSize(); // update status and jPlayer element size // Determine the status for Blocklisted options. this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); this.status.noFullWindow = this._uaBlocklist(this.options.noFullWindow); this.status.noVolume = this._uaBlocklist(this.options.noVolume); // Create event handlers if native fullscreen is supported if($.jPlayer.nativeFeatures.fullscreen.api.fullscreenEnabled) { this._fullscreenAddEventListeners(); } // The native controls are only for video and are disabled when audio is also used. this._restrictNativeVideoControls(); // Create the poster image. this.htmlElement.poster = document.createElement('img'); this.htmlElement.poster.id = this.internal.poster.id; this.htmlElement.poster.onload = function() { // Note that this did not work on Firefox 3.6: poster.addEventListener("onload", function() {}, false); Did not investigate x-browser. if(!self.status.video || self.status.waitForPlay) { self.internal.poster.jq.show(); } }; this.element.append(this.htmlElement.poster); this.internal.poster.jq = $("#" + this.internal.poster.id); this.internal.poster.jq.css({'width': this.status.width, 'height': this.status.height}); this.internal.poster.jq.hide(); this.internal.poster.jq.bind("click.jPlayer", function() { self._trigger($.jPlayer.event.click); }); // Generate the required media elements this.html.audio.available = false; if(this.require.audio) { // If a supplied format is audio this.htmlElement.audio = document.createElement('audio'); this.htmlElement.audio.id = this.internal.audio.id; this.html.audio.available = !!this.htmlElement.audio.canPlayType && this._testCanPlayType(this.htmlElement.audio); // Test is for IE9 on Win Server 2008. } this.html.video.available = false; if(this.require.video) { // If a supplied format is video this.htmlElement.video = document.createElement('video'); this.htmlElement.video.id = this.internal.video.id; this.html.video.available = !!this.htmlElement.video.canPlayType && this._testCanPlayType(this.htmlElement.video); // Test is for IE9 on Win Server 2008. } this.flash.available = this._checkForFlash(10.1); this.html.canPlay = {}; this.aurora.canPlay = {}; this.flash.canPlay = {}; $.each(this.formats, function(priority, format) { self.html.canPlay[format] = self.html[self.format[format].media].available && "" !== self.htmlElement[self.format[format].media].canPlayType(self.format[format].codec); self.aurora.canPlay[format] = ($.inArray(format, self.aurora.formats) > -1); self.flash.canPlay[format] = self.format[format].flashCanPlay && self.flash.available; }); this.html.desired = false; this.aurora.desired = false; this.flash.desired = false; $.each(this.solutions, function(solutionPriority, solution) { if(solutionPriority === 0) { self[solution].desired = true; } else { var audioCanPlay = false; var videoCanPlay = false; $.each(self.formats, function(formatPriority, format) { if(self[self.solutions[0]].canPlay[format]) { // The other solution can play if(self.format[format].media === 'video') { videoCanPlay = true; } else { audioCanPlay = true; } } }); self[solution].desired = (self.require.audio && !audioCanPlay) || (self.require.video && !videoCanPlay); } }); // This is what jPlayer will support, based on solution and supplied. this.html.support = {}; this.aurora.support = {}; this.flash.support = {}; $.each(this.formats, function(priority, format) { self.html.support[format] = self.html.canPlay[format] && self.html.desired; self.aurora.support[format] = self.aurora.canPlay[format] && self.aurora.desired; self.flash.support[format] = self.flash.canPlay[format] && self.flash.desired; }); // If jPlayer is supporting any format in a solution, then the solution is used. this.html.used = false; this.aurora.used = false; this.flash.used = false; $.each(this.solutions, function(solutionPriority, solution) { $.each(self.formats, function(formatPriority, format) { if(self[solution].support[format]) { self[solution].used = true; return false; } }); }); // Init solution active state and the event gates to false. this._resetActive(); this._resetGate(); // Set up the css selectors for the control and feedback entities. this._cssSelectorAncestor(this.options.cssSelectorAncestor); // If neither html nor aurora nor flash are being used by this browser, then media playback is not possible. Trigger an error event. if(!(this.html.used || this.aurora.used || this.flash.used)) { this._error( { type: $.jPlayer.error.NO_SOLUTION, context: "{solution:'" + this.options.solution + "', supplied:'" + this.options.supplied + "'}", message: $.jPlayer.errorMsg.NO_SOLUTION, hint: $.jPlayer.errorHint.NO_SOLUTION }); if(this.css.jq.noSolution.length) { this.css.jq.noSolution.show(); } } else { if(this.css.jq.noSolution.length) { this.css.jq.noSolution.hide(); } } // Add the flash solution if it is being used. if(this.flash.used) { var htmlObj, flashVars = 'jQuery=' + encodeURI(this.options.noConflict) + '&id=' + encodeURI(this.internal.self.id) + '&vol=' + this.options.volume + '&muted=' + this.options.muted; // Code influenced by SWFObject 2.2: http://code.google.com/p/swfobject/ // Non IE browsers have an initial Flash size of 1 by 1 otherwise the wmode affected the Flash ready event. if($.jPlayer.browser.msie && (Number($.jPlayer.browser.version) < 9 || $.jPlayer.browser.documentMode < 9)) { var objStr = '<object id="' + this.internal.flash.id + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="0" height="0" tabindex="-1"></object>'; var paramStr = [ '<param name="movie" value="' + this.internal.flash.swf + '" />', '<param name="FlashVars" value="' + flashVars + '" />', '<param name="allowScriptAccess" value="always" />', '<param name="bgcolor" value="' + this.options.backgroundColor + '" />', '<param name="wmode" value="' + this.options.wmode + '" />' ]; htmlObj = document.createElement(objStr); for(var i=0; i < paramStr.length; i++) { htmlObj.appendChild(document.createElement(paramStr[i])); } } else { var createParam = function(el, n, v) { var p = document.createElement("param"); p.setAttribute("name", n); p.setAttribute("value", v); el.appendChild(p); }; htmlObj = document.createElement("object"); htmlObj.setAttribute("id", this.internal.flash.id); htmlObj.setAttribute("name", this.internal.flash.id); htmlObj.setAttribute("data", this.internal.flash.swf); htmlObj.setAttribute("type", "application/x-shockwave-flash"); htmlObj.setAttribute("width", "1"); // Non-zero htmlObj.setAttribute("height", "1"); // Non-zero htmlObj.setAttribute("tabindex", "-1"); createParam(htmlObj, "flashvars", flashVars); createParam(htmlObj, "allowscriptaccess", "always"); createParam(htmlObj, "bgcolor", this.options.backgroundColor); createParam(htmlObj, "wmode", this.options.wmode); } this.element.append(htmlObj); this.internal.flash.jq = $(htmlObj); } // Setup playbackRate ability before using _addHtmlEventListeners() if(this.html.used && !this.flash.used) { // If only HTML // Using the audio element capabilities for playbackRate. ie., Assuming video element is the same. this.status.playbackRateEnabled = this._testPlaybackRate('audio'); } else { this.status.playbackRateEnabled = false; } this._updatePlaybackRate(); // Add the HTML solution if being used. if(this.html.used) { // The HTML Audio handlers if(this.html.audio.available) { this._addHtmlEventListeners(this.htmlElement.audio, this.html.audio); this.element.append(this.htmlElement.audio); this.internal.audio.jq = $("#" + this.internal.audio.id); } // The HTML Video handlers if(this.html.video.available) { this._addHtmlEventListeners(this.htmlElement.video, this.html.video); this.element.append(this.htmlElement.video); this.internal.video.jq = $("#" + this.internal.video.id); if(this.status.nativeVideoControls) { this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else { this.internal.video.jq.css({'width':'0px', 'height':'0px'}); // Using size 0x0 since a .hide() causes issues in iOS } this.internal.video.jq.bind("click.jPlayer", function() { self._trigger($.jPlayer.event.click); }); } } // Add the Aurora.js solution if being used. if(this.aurora.used) { // Aurora.js player need to be created for each media, see setMedia function. } // Create the bridge that emulates the HTML Media element on the jPlayer DIV if( this.options.emulateHtml ) { this._emulateHtmlBridge(); } if((this.html.used || this.aurora.used) && !this.flash.used) { // If only HTML, then emulate flash ready() call after 100ms. setTimeout( function() { self.internal.ready = true; self.version.flash = "n/a"; self._trigger($.jPlayer.event.repeat); // Trigger the repeat event so its handler can initialize itself with the loop option. self._trigger($.jPlayer.event.ready); }, 100); } // Initialize the interface components with the options. this._updateNativeVideoControls(); // The other controls are now setup in _cssSelectorAncestor() if(this.css.jq.videoPlay.length) { this.css.jq.videoPlay.hide(); } $.jPlayer.prototype.count++; // Change static variable via prototype. }, destroy: function() { // MJP: The background change remains. Would need to store the original to restore it correctly. // MJP: The jPlayer element's size change remains. // Clear the media to reset the GUI and stop any downloads. Streams on some browsers had persited. (Chrome) this.clearMedia(); // Remove the size/sizeFull cssClass from the cssSelectorAncestor this._removeUiClass(); // Remove the times from the GUI if(this.css.jq.currentTime.length) { this.css.jq.currentTime.text(""); } if(this.css.jq.duration.length) { this.css.jq.duration.text(""); } // Remove any bindings from the interface controls. $.each(this.css.jq, function(fn, jq) { // Check selector is valid before trying to execute method. if(jq.length) { jq.unbind(".jPlayer"); } }); // Remove the click handlers for $.jPlayer.event.click this.internal.poster.jq.unbind(".jPlayer"); if(this.internal.video.jq) { this.internal.video.jq.unbind(".jPlayer"); } // Remove the fullscreen event handlers this._fullscreenRemoveEventListeners(); // Remove key bindings if(this === $.jPlayer.focus) { $.jPlayer.focus = null; } // Destroy the HTML bridge. if(this.options.emulateHtml) { this._destroyHtmlBridge(); } this.element.removeData("jPlayer"); // Remove jPlayer data this.element.unbind(".jPlayer"); // Remove all event handlers created by the jPlayer constructor this.element.empty(); // Remove the inserted child elements delete this.instances[this.internal.instance]; // Clear the instance on the static instance object }, destroyRemoved: function() { // Destroy any instances that have gone away. var self = this; $.each(this.instances, function(i, element) { if(self.element !== element) { // Do not destroy this instance. if(!element.data("jPlayer")) { // Check that element is a real jPlayer. element.jPlayer("destroy"); delete self.instances[i]; } } }); }, enable: function() { // Plan to implement // options.disabled = false }, disable: function () { // Plan to implement // options.disabled = true }, _testCanPlayType: function(elem) { // IE9 on Win Server 2008 did not implement canPlayType(), but it has the property. try { elem.canPlayType(this.format.mp3.codec); // The type is irrelevant. return true; } catch(err) { return false; } }, _testPlaybackRate: function(type) { // type: String 'audio' or 'video' var el, rate = 0.5; type = typeof type === 'string' ? type : 'audio'; el = document.createElement(type); // Wrapping in a try/catch, just in case older HTML5 browsers throw and error. try { if('playbackRate' in el) { el.playbackRate = rate; return el.playbackRate === rate; } else { return false; } } catch(err) { return false; } }, _uaBlocklist: function(list) { // list : object with properties that are all regular expressions. Property names are irrelevant. // Returns true if the user agent is matched in list. var ua = navigator.userAgent.toLowerCase(), block = false; $.each(list, function(p, re) { if(re && re.test(ua)) { block = true; return false; // exit $.each. } }); return block; }, _restrictNativeVideoControls: function() { // Fallback to noFullWindow when nativeVideoControls is true and audio media is being used. Affects when both media types are used. if(this.require.audio) { if(this.status.nativeVideoControls) { this.status.nativeVideoControls = false; this.status.noFullWindow = true; } } }, _updateNativeVideoControls: function() { if(this.html.video.available && this.html.used) { // Turn the HTML Video controls on/off this.htmlElement.video.controls = this.status.nativeVideoControls; // Show/hide the jPlayer GUI. this._updateAutohide(); // For when option changed. The poster image is not updated, as it is dealt with in setMedia(). Acceptable degradation since seriously doubt these options will change on the fly. Can again review later. if(this.status.nativeVideoControls && this.require.video) { this.internal.poster.jq.hide(); this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else if(this.status.waitForPlay && this.status.video) { this.internal.poster.jq.show(); this.internal.video.jq.css({'width': '0px', 'height': '0px'}); } } }, _addHtmlEventListeners: function(mediaElement, entity) { var self = this; mediaElement.preload = this.options.preload; mediaElement.muted = this.options.muted; mediaElement.volume = this.options.volume; if(this.status.playbackRateEnabled) { mediaElement.defaultPlaybackRate = this.options.defaultPlaybackRate; mediaElement.playbackRate = this.options.playbackRate; } // Create the event listeners // Only want the active entity to affect jPlayer and bubble events. // Using entity.gate so that object is referenced and gate property always current mediaElement.addEventListener("progress", function() { if(entity.gate) { if(self.internal.cmdsIgnored && this.readyState > 0) { // Detect iOS executed the command self.internal.cmdsIgnored = false; } self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.progress); } }, false); mediaElement.addEventListener("loadeddata", function() { if(entity.gate) { self.androidFix.setMedia = false; // Disable the fix after the first progress event. if(self.androidFix.play) { // Play Android audio - performing the fix. self.androidFix.play = false; self.play(self.androidFix.time); } if(self.androidFix.pause) { // Pause Android audio at time - performing the fix. self.androidFix.pause = false; self.pause(self.androidFix.time); } self._trigger($.jPlayer.event.loadeddata); } }, false); mediaElement.addEventListener("timeupdate", function() { if(entity.gate) { self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.timeupdate); } }, false); mediaElement.addEventListener("durationchange", function() { if(entity.gate) { self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.durationchange); } }, false); mediaElement.addEventListener("play", function() { if(entity.gate) { self._updateButtons(true); self._html_checkWaitForPlay(); // So the native controls update this variable and puts the hidden interface in the correct state. Affects toggling native controls. self._trigger($.jPlayer.event.play); } }, false); mediaElement.addEventListener("playing", function() { if(entity.gate) { self._updateButtons(true); self._seeked(); self._trigger($.jPlayer.event.playing); } }, false); mediaElement.addEventListener("pause", function() { if(entity.gate) { self._updateButtons(false); self._trigger($.jPlayer.event.pause); } }, false); mediaElement.addEventListener("waiting", function() { if(entity.gate) { self._seeking(); self._trigger($.jPlayer.event.waiting); } }, false); mediaElement.addEventListener("seeking", function() { if(entity.gate) { self._seeking(); self._trigger($.jPlayer.event.seeking); } }, false); mediaElement.addEventListener("seeked", function() { if(entity.gate) { self._seeked(); self._trigger($.jPlayer.event.seeked); } }, false); mediaElement.addEventListener("volumechange", function() { if(entity.gate) { // Read the values back from the element as the Blackberry PlayBook shares the volume with the physical buttons master volume control. // However, when tested 6th July 2011, those buttons do not generate an event. The physical play/pause button does though. self.options.volume = mediaElement.volume; self.options.muted = mediaElement.muted; self._updateMute(); self._updateVolume(); self._trigger($.jPlayer.event.volumechange); } }, false); mediaElement.addEventListener("ratechange", function() { if(entity.gate) { self.options.defaultPlaybackRate = mediaElement.defaultPlaybackRate; self.options.playbackRate = mediaElement.playbackRate; self._updatePlaybackRate(); self._trigger($.jPlayer.event.ratechange); } }, false); mediaElement.addEventListener("suspend", function() { // Seems to be the only way of capturing that the iOS4 browser did not actually play the media from the page code. ie., It needs a user gesture. if(entity.gate) { self._seeked(); self._trigger($.jPlayer.event.suspend); } }, false); mediaElement.addEventListener("ended", function() { if(entity.gate) { // Order of the next few commands are important. Change the time and then pause. // Solves a bug in Firefox, where issuing pause 1st causes the media to play from the start. ie., The pause is ignored. if(!$.jPlayer.browser.webkit) { // Chrome crashes if you do this in conjunction with a setMedia command in an ended event handler. ie., The playlist demo. self.htmlElement.media.currentTime = 0; // Safari does not care about this command. ie., It works with or without this line. (Both Safari and Chrome are Webkit.) } self.htmlElement.media.pause(); // Pause otherwise a click on the progress bar will play from that point, when it shouldn't, since it stopped playback. self._updateButtons(false); self._getHtmlStatus(mediaElement, true); // With override true. Otherwise Chrome leaves progress at full. self._updateInterface(); self._trigger($.jPlayer.event.ended); } }, false); mediaElement.addEventListener("error", function() { if(entity.gate) { self._updateButtons(false); self._seeked(); if(self.status.srcSet) { // Deals with case of clearMedia() causing an error event. clearTimeout(self.internal.htmlDlyCmdId); // Clears any delayed commands used in the HTML solution. self.status.waitForLoad = true; // Allows the load operation to try again. self.status.waitForPlay = true; // Reset since a play was captured. if(self.status.video && !self.status.nativeVideoControls) { self.internal.video.jq.css({'width':'0px', 'height':'0px'}); } if(self._validString(self.status.media.poster) && !self.status.nativeVideoControls) { self.internal.poster.jq.show(); } if(self.css.jq.videoPlay.length) { self.css.jq.videoPlay.show(); } self._error( { type: $.jPlayer.error.URL, context: self.status.src, // this.src shows absolute urls. Want context to show the url given. message: $.jPlayer.errorMsg.URL, hint: $.jPlayer.errorHint.URL }); } } }, false); // Create all the other event listeners that bubble up to a jPlayer event from html, without being used by jPlayer. $.each($.jPlayer.htmlEvent, function(i, eventType) { mediaElement.addEventListener(this, function() { if(entity.gate) { self._trigger($.jPlayer.event[eventType]); } }, false); }); }, _addAuroraEventListeners : function(player, entity) { var self = this; //player.preload = this.options.preload; //player.muted = this.options.muted; player.volume = this.options.volume * 100; // Create the event listeners // Only want the active entity to affect jPlayer and bubble events. // Using entity.gate so that object is referenced and gate property always current player.on("progress", function() { if(entity.gate) { if(self.internal.cmdsIgnored && this.readyState > 0) { // Detect iOS executed the command self.internal.cmdsIgnored = false; } self._getAuroraStatus(player); self._updateInterface(); self._trigger($.jPlayer.event.progress); // Progress with song duration, we estimate timeupdate need to be triggered too. if (player.duration > 0) { self._trigger($.jPlayer.event.timeupdate); } } }, false); player.on("ready", function() { if(entity.gate) { self._trigger($.jPlayer.event.loadeddata); } }, false); player.on("duration", function() { if(entity.gate) { self._getAuroraStatus(player); self._updateInterface(); self._trigger($.jPlayer.event.durationchange); } }, false); player.on("end", function() { if(entity.gate) { // Order of the next few commands are important. Change the time and then pause. self._updateButtons(false); self._getAuroraStatus(player, true); self._updateInterface(); self._trigger($.jPlayer.event.ended); } }, false); player.on("error", function() { if(entity.gate) { self._updateButtons(false); self._seeked(); if(self.status.srcSet) { // Deals with case of clearMedia() causing an error event. self.status.waitForLoad = true; // Allows the load operation to try again. self.status.waitForPlay = true; // Reset since a play was captured. if(self.status.video && !self.status.nativeVideoControls) { self.internal.video.jq.css({'width':'0px', 'height':'0px'}); } if(self._validString(self.status.media.poster) && !self.status.nativeVideoControls) { self.internal.poster.jq.show(); } if(self.css.jq.videoPlay.length) { self.css.jq.videoPlay.show(); } self._error( { type: $.jPlayer.error.URL, context: self.status.src, // this.src shows absolute urls. Want context to show the url given. message: $.jPlayer.errorMsg.URL, hint: $.jPlayer.errorHint.URL }); } } }, false); }, _getHtmlStatus: function(media, override) { var ct = 0, cpa = 0, sp = 0, cpr = 0; // Fixes the duration bug in iOS, where the durationchange event occurs when media.duration is not always correct. // Fixes the initial duration bug in BB OS7, where the media.duration is infinity and displays as NaN:NaN due to Date() using inifity. if(isFinite(media.duration)) { this.status.duration = media.duration; } ct = media.currentTime; cpa = (this.status.duration > 0) ? 100 * ct / this.status.duration : 0; if((typeof media.seekable === "object") && (media.seekable.length > 0)) { sp = (this.status.duration > 0) ? 100 * media.seekable.end(media.seekable.length-1) / this.status.duration : 100; cpr = (this.status.duration > 0) ? 100 * media.currentTime / media.seekable.end(media.seekable.length-1) : 0; // Duration conditional for iOS duration bug. ie., seekable.end is a NaN in that case. } else { sp = 100; cpr = cpa; } if(override) { ct = 0; cpr = 0; cpa = 0; } this.status.seekPercent = sp; this.status.currentPercentRelative = cpr; this.status.currentPercentAbsolute = cpa; this.status.currentTime = ct; this.status.remaining = this.status.duration - this.status.currentTime; this.status.videoWidth = media.videoWidth; this.status.videoHeight = media.videoHeight; this.status.readyState = media.readyState; this.status.networkState = media.networkState; this.status.playbackRate = media.playbackRate; this.status.ended = media.ended; }, _getAuroraStatus: function(player, override) { var ct = 0, cpa = 0, sp = 0, cpr = 0; this.status.duration = player.duration / 1000; ct = player.currentTime / 1000; cpa = (this.status.duration > 0) ? 100 * ct / this.status.duration : 0; if(player.buffered > 0) { sp = (this.status.duration > 0) ? (player.buffered * this.status.duration) / this.status.duration : 100; cpr = (this.status.duration > 0) ? ct / (player.buffered * this.status.duration) : 0; } else { sp = 100; cpr = cpa; } if(override) { ct = 0; cpr = 0; cpa = 0; } this.status.seekPercent = sp; this.status.currentPercentRelative = cpr; this.status.currentPercentAbsolute = cpa; this.status.currentTime = ct; this.status.remaining = this.status.duration - this.status.currentTime; this.status.readyState = 4; // status.readyState; this.status.networkState = 0; // status.networkState; this.status.playbackRate = 1; // status.playbackRate; this.status.ended = false; // status.ended; }, _resetStatus: function() { this.status = $.extend({}, this.status, $.jPlayer.prototype.status); // Maintains the status properties that persist through a reset. }, _trigger: function(eventType, error, warning) { // eventType always valid as called using $.jPlayer.event.eventType var event = $.Event(eventType); event.jPlayer = {}; event.jPlayer.version = $.extend({}, this.version); event.jPlayer.options = $.extend(true, {}, this.options); // Deep copy event.jPlayer.status = $.extend(true, {}, this.status); // Deep copy event.jPlayer.html = $.extend(true, {}, this.html); // Deep copy event.jPlayer.aurora = $.extend(true, {}, this.aurora); // Deep copy event.jPlayer.flash = $.extend(true, {}, this.flash); // Deep copy if(error) { event.jPlayer.error = $.extend({}, error); } if(warning) { event.jPlayer.warning = $.extend({}, warning); } this.element.trigger(event); }, jPlayerFlashEvent: function(eventType, status) { // Called from Flash if(eventType === $.jPlayer.event.ready) { if(!this.internal.ready) { this.internal.ready = true; this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); // Once Flash generates the ready event, minimise to zero as it is not affected by wmode anymore. this.version.flash = status.version; if(this.version.needFlash !== this.version.flash) { this._error( { type: $.jPlayer.error.VERSION, context: this.version.flash, message: $.jPlayer.errorMsg.VERSION + this.version.flash, hint: $.jPlayer.errorHint.VERSION }); } this._trigger($.jPlayer.event.repeat); // Trigger the repeat event so its handler can initialize itself with the loop option. this._trigger(eventType); } else { // This condition occurs if the Flash is hidden and then shown again. // Firefox also reloads the Flash if the CSS position changes. position:fixed is used for full screen. // Only do this if the Flash is the solution being used at the moment. Affects Media players where both solution may be being used. if(this.flash.gate) { // Send the current status to the Flash now that it is ready (available) again. if(this.status.srcSet) { // Need to read original status before issuing the setMedia command. var currentTime = this.status.currentTime, paused = this.status.paused; this.setMedia(this.status.media); this.volumeWorker(this.options.volume); if(currentTime > 0) { if(paused) { this.pause(currentTime); } else { this.play(currentTime); } } } this._trigger($.jPlayer.event.flashreset); } } } if(this.flash.gate) { switch(eventType) { case $.jPlayer.event.progress: this._getFlashStatus(status); this._updateInterface(); this._trigger(eventType); break; case $.jPlayer.event.timeupdate: this._getFlashStatus(status); this._updateInterface(); this._trigger(eventType); break; case $.jPlayer.event.play: this._seeked(); this._updateButtons(true); this._trigger(eventType); break; case $.jPlayer.event.pause: this._updateButtons(false); this._trigger(eventType); break; case $.jPlayer.event.ended: this._updateButtons(false); this._trigger(eventType); break; case $.jPlayer.event.click: this._trigger(eventType); // This could be dealt with by the default break; case $.jPlayer.event.error: this.status.waitForLoad = true; // Allows the load operation to try again. this.status.waitForPlay = true; // Reset since a play was captured. if(this.status.video) { this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); } if(this._validString(this.status.media.poster)) { this.internal.poster.jq.show(); } if(this.css.jq.videoPlay.length && this.status.video) { this.css.jq.videoPlay.show(); } if(this.status.video) { // Set up for another try. Execute before error event. this._flash_setVideo(this.status.media); } else { this._flash_setAudio(this.status.media); } this._updateButtons(false); this._error( { type: $.jPlayer.error.URL, context:status.src, message: $.jPlayer.errorMsg.URL, hint: $.jPlayer.errorHint.URL }); break; case $.jPlayer.event.seeking: this._seeking(); this._trigger(eventType); break; case $.jPlayer.event.seeked: this._seeked(); this._trigger(eventType); break; case $.jPlayer.event.ready: // The ready event is handled outside the switch statement. // Captured here otherwise 2 ready events would be generated if the ready event handler used setMedia. break; default: this._trigger(eventType); } } return false; }, _getFlashStatus: function(status) { this.status.seekPercent = status.seekPercent; this.status.currentPercentRelative = status.currentPercentRelative; this.status.currentPercentAbsolute = status.currentPercentAbsolute; this.status.currentTime = status.currentTime; this.status.duration = status.duration; this.status.remaining = status.duration - status.currentTime; this.status.videoWidth = status.videoWidth; this.status.videoHeight = status.videoHeight; // The Flash does not generate this information in this release this.status.readyState = 4; // status.readyState; this.status.networkState = 0; // status.networkState; this.status.playbackRate = 1; // status.playbackRate; this.status.ended = false; // status.ended; }, _updateButtons: function(playing) { if(playing === undefined) { playing = !this.status.paused; } else { this.status.paused = !playing; } // Apply the state classes. (For the useStateClassSkin:true option) if(playing) { this.addStateClass('playing'); } else { this.removeStateClass('playing'); } if(!this.status.noFullWindow && this.options.fullWindow) { this.addStateClass('fullScreen'); } else { this.removeStateClass('fullScreen'); } if(this.options.loop) { this.addStateClass('looped'); } else { this.removeStateClass('looped'); } // Toggle the GUI element pairs. (For the useStateClassSkin:false option) if(this.css.jq.play.length && this.css.jq.pause.length) { if(playing) { this.css.jq.play.hide(); this.css.jq.pause.show(); } else { this.css.jq.play.show(); this.css.jq.pause.hide(); } } if(this.css.jq.restoreScreen.length && this.css.jq.fullScreen.length) { if(this.status.noFullWindow) { this.css.jq.fullScreen.hide(); this.css.jq.restoreScreen.hide(); } else if(this.options.fullWindow) { this.css.jq.fullScreen.hide(); this.css.jq.restoreScreen.show(); } else { this.css.jq.fullScreen.show(); this.css.jq.restoreScreen.hide(); } } if(this.css.jq.repeat.length && this.css.jq.repeatOff.length) { if(this.options.loop) { this.css.jq.repeat.hide(); this.css.jq.repeatOff.show(); } else { this.css.jq.repeat.show(); this.css.jq.repeatOff.hide(); } } }, _updateInterface: function() { if(this.css.jq.seekBar.length) { this.css.jq.seekBar.width(this.status.seekPercent+"%"); } if(this.css.jq.playBar.length) { if(this.options.smoothPlayBar) { this.css.jq.playBar.stop().animate({ width: this.status.currentPercentAbsolute+"%" }, 250, "linear"); } else { this.css.jq.playBar.width(this.status.currentPercentRelative+"%"); } } var currentTimeText = ''; if(this.css.jq.currentTime.length) { currentTimeText = this._convertTime(this.status.currentTime); if(currentTimeText !== this.css.jq.currentTime.text()) { this.css.jq.currentTime.text(this._convertTime(this.status.currentTime)); } } var durationText = '', duration = this.status.duration, remaining = this.status.remaining; if(this.css.jq.duration.length) { if(typeof this.status.media.duration === 'string') { durationText = this.status.media.duration; } else { if(typeof this.status.media.duration === 'number') { duration = this.status.media.duration; remaining = duration - this.status.currentTime; } if(this.options.remainingDuration) { durationText = (remaining > 0 ? '-' : '') + this._convertTime(remaining); } else { durationText = this._convertTime(duration); } } if(durationText !== this.css.jq.duration.text()) { this.css.jq.duration.text(durationText); } } }, _convertTime: ConvertTime.prototype.time, _seeking: function() { if(this.css.jq.seekBar.length) { this.css.jq.seekBar.addClass("jp-seeking-bg"); } this.addStateClass('seeking'); }, _seeked: function() { if(this.css.jq.seekBar.length) { this.css.jq.seekBar.removeClass("jp-seeking-bg"); } this.removeStateClass('seeking'); }, _resetGate: function() { this.html.audio.gate = false; this.html.video.gate = false; this.aurora.gate = false; this.flash.gate = false; }, _resetActive: function() { this.html.active = false; this.aurora.active = false; this.flash.active = false; }, _escapeHtml: function(s) { return s.split('&').join('&amp;').split('<').join('&lt;').split('>').join('&gt;').split('"').join('&quot;'); }, _qualifyURL: function(url) { var el = document.createElement('div'); el.innerHTML= '<a href="' + this._escapeHtml(url) + '">x</a>'; return el.firstChild.href; }, _absoluteMediaUrls: function(media) { var self = this; $.each(media, function(type, url) { if(url && self.format[type] && url.substr(0, 5) !== "data:") { media[type] = self._qualifyURL(url); } }); return media; }, addStateClass: function(state) { if(this.ancestorJq.length) { this.ancestorJq.addClass(this.options.stateClass[state]); } }, removeStateClass: function(state) { if(this.ancestorJq.length) { this.ancestorJq.removeClass(this.options.stateClass[state]); } }, setMedia: function(media) { /* media[format] = String: URL of format. Must contain all of the supplied option's video or audio formats. * media.poster = String: Video poster URL. * media.track = Array: Of objects defining the track element: kind, src, srclang, label, def. * media.stream = Boolean: * NOT IMPLEMENTED * Designating actual media streams. ie., "false/undefined" for files. Plan to refresh the flash every so often. */ var self = this, supported = false, posterChanged = this.status.media.poster !== media.poster; // Compare before reset. Important for OSX Safari as this.htmlElement.poster.src is absolute, even if original poster URL was relative. this._resetMedia(); this._resetGate(); this._resetActive(); // Clear the Android Fix. this.androidFix.setMedia = false; this.androidFix.play = false; this.androidFix.pause = false; // Convert all media URLs to absolute URLs. media = this._absoluteMediaUrls(media); $.each(this.formats, function(formatPriority, format) { var isVideo = self.format[format].media === 'video'; $.each(self.solutions, function(solutionPriority, solution) { if(self[solution].support[format] && self._validString(media[format])) { // Format supported in solution and url given for format. var isHtml = solution === 'html'; var isAurora = solution === 'aurora'; if(isVideo) { if(isHtml) { self.html.video.gate = true; self._html_setVideo(media); self.html.active = true; } else { self.flash.gate = true; self._flash_setVideo(media); self.flash.active = true; } if(self.css.jq.videoPlay.length) { self.css.jq.videoPlay.show(); } self.status.video = true; } else { if(isHtml) { self.html.audio.gate = true; self._html_setAudio(media); self.html.active = true; // Setup the Android Fix - Only for HTML audio. if($.jPlayer.platform.android) { self.androidFix.setMedia = true; } } else if(isAurora) { self.aurora.gate = true; self._aurora_setAudio(media); self.aurora.active = true; } else { self.flash.gate = true; self._flash_setAudio(media); self.flash.active = true; } if(self.css.jq.videoPlay.length) { self.css.jq.videoPlay.hide(); } self.status.video = false; } supported = true; return false; // Exit $.each } }); if(supported) { return false; // Exit $.each } }); if(supported) { if(!(this.status.nativeVideoControls && this.html.video.gate)) { // Set poster IMG if native video controls are not being used // Note: With IE the IMG onload event occurs immediately when cached. // Note: Poster hidden by default in _resetMedia() if(this._validString(media.poster)) { if(posterChanged) { // Since some browsers do not generate img onload event. this.htmlElement.poster.src = media.poster; } else { this.internal.poster.jq.show(); } } } if(typeof media.title === 'string') { if(this.css.jq.title.length) { this.css.jq.title.html(media.title); } if(this.htmlElement.audio) { this.htmlElement.audio.setAttribute('title', media.title); } if(this.htmlElement.video) { this.htmlElement.video.setAttribute('title', media.title); } } this.status.srcSet = true; this.status.media = $.extend({}, media); this._updateButtons(false); this._updateInterface(); this._trigger($.jPlayer.event.setmedia); } else { // jPlayer cannot support any formats provided in this browser // Send an error event this._error( { type: $.jPlayer.error.NO_SUPPORT, context: "{supplied:'" + this.options.supplied + "'}", message: $.jPlayer.errorMsg.NO_SUPPORT, hint: $.jPlayer.errorHint.NO_SUPPORT }); } }, _resetMedia: function() { this._resetStatus(); this._updateButtons(false); this._updateInterface(); this._seeked(); this.internal.poster.jq.hide(); clearTimeout(this.internal.htmlDlyCmdId); if(this.html.active) { this._html_resetMedia(); } else if(this.aurora.active) { this._aurora_resetMedia(); } else if(this.flash.active) { this._flash_resetMedia(); } }, clearMedia: function() { this._resetMedia(); if(this.html.active) { this._html_clearMedia(); } else if(this.aurora.active) { this._aurora_clearMedia(); } else if(this.flash.active) { this._flash_clearMedia(); } this._resetGate(); this._resetActive(); }, load: function() { if(this.status.srcSet) { if(this.html.active) { this._html_load(); } else if(this.aurora.active) { this._aurora_load(); } else if(this.flash.active) { this._flash_load(); } } else { this._urlNotSetError("load"); } }, focus: function() { if(this.options.keyEnabled) { $.jPlayer.focus = this; } }, play: function(time) { var guiAction = typeof time === "object"; // Flags GUI click events so we know this was not a direct command, but an action taken by the user on the GUI. if(guiAction && this.options.useStateClassSkin && !this.status.paused) { this.pause(time); // The time would be the click event, but passing it over so info is not lost. } else { time = (typeof time === "number") ? time : NaN; // Remove jQuery event from click handler if(this.status.srcSet) { this.focus(); if(this.html.active) { this._html_play(time); } else if(this.aurora.active) { this._aurora_play(time); } else if(this.flash.active) { this._flash_play(time); } } else { this._urlNotSetError("play"); } } }, videoPlay: function() { // Handles clicks on the play button over the video poster this.play(); }, pause: function(time) { time = (typeof time === "number") ? time : NaN; // Remove jQuery event from click handler if(this.status.srcSet) { if(this.html.active) { this._html_pause(time); } else if(this.aurora.active) { this._aurora_pause(time); } else if(this.flash.active) { this._flash_pause(time); } } else { this._urlNotSetError("pause"); } }, tellOthers: function(command, conditions) { var self = this, hasConditions = typeof conditions === 'function', args = Array.prototype.slice.call(arguments); // Convert arguments to an Array. if(typeof command !== 'string') { // Ignore, since no command. return; // Return undefined to maintain chaining. } if(hasConditions) { args.splice(1, 1); // Remove the conditions from the arguments } $.jPlayer.prototype.destroyRemoved(); $.each(this.instances, function() { // Remember that "this" is the instance's "element" in the $.each() loop. if(self.element !== this) { // Do not tell my instance. if(!hasConditions || conditions.call(this.data("jPlayer"), self)) { this.jPlayer.apply(this, args); } } }); }, pauseOthers: function(time) { this.tellOthers("pause", function() { // In the conditions function, the "this" context is the other instance's jPlayer object. return this.status.srcSet; }, time); }, stop: function() { if(this.status.srcSet) { if(this.html.active) { this._html_pause(0); } else if(this.aurora.active) { this._aurora_pause(0); } else if(this.flash.active) { this._flash_pause(0); } } else { this._urlNotSetError("stop"); } }, playHead: function(p) { p = this._limitValue(p, 0, 100); if(this.status.srcSet) { if(this.html.active) { this._html_playHead(p); } else if(this.aurora.active) { this._aurora_playHead(p); } else if(this.flash.active) { this._flash_playHead(p); } } else { this._urlNotSetError("playHead"); } }, _muted: function(muted) { this.mutedWorker(muted); if(this.options.globalVolume) { this.tellOthers("mutedWorker", function() { // Check the other instance has global volume enabled. return this.options.globalVolume; }, muted); } }, mutedWorker: function(muted) { this.options.muted = muted; if(this.html.used) { this._html_setProperty('muted', muted); } if(this.aurora.used) { this._aurora_mute(muted); } if(this.flash.used) { this._flash_mute(muted); } // The HTML solution generates this event from the media element itself. if(!this.html.video.gate && !this.html.audio.gate) { this._updateMute(muted); this._updateVolume(this.options.volume); this._trigger($.jPlayer.event.volumechange); } }, mute: function(mute) { // mute is either: undefined (true), an event object (true) or a boolean (muted). var guiAction = typeof mute === "object"; // Flags GUI click events so we know this was not a direct command, but an action taken by the user on the GUI. if(guiAction && this.options.useStateClassSkin && this.options.muted) { this._muted(false); } else { mute = mute === undefined ? true : !!mute; this._muted(mute); } }, unmute: function(unmute) { // unmute is either: undefined (true), an event object (true) or a boolean (!muted). unmute = unmute === undefined ? true : !!unmute; this._muted(!unmute); }, _updateMute: function(mute) { if(mute === undefined) { mute = this.options.muted; } if(mute) { this.addStateClass('muted'); } else { this.removeStateClass('muted'); } if(this.css.jq.mute.length && this.css.jq.unmute.length) { if(this.status.noVolume) { this.css.jq.mute.hide(); this.css.jq.unmute.hide(); } else if(mute) { this.css.jq.mute.hide(); this.css.jq.unmute.show(); } else { this.css.jq.mute.show(); this.css.jq.unmute.hide(); } } }, volume: function(v) { this.volumeWorker(v); if(this.options.globalVolume) { this.tellOthers("volumeWorker", function() { // Check the other instance has global volume enabled. return this.options.globalVolume; }, v); } }, volumeWorker: function(v) { v = this._limitValue(v, 0, 1); this.options.volume = v; if(this.html.used) { this._html_setProperty('volume', v); } if(this.aurora.used) { this._aurora_volume(v); } if(this.flash.used) { this._flash_volume(v); } // The HTML solution generates this event from the media element itself. if(!this.html.video.gate && !this.html.audio.gate) { this._updateVolume(v); this._trigger($.jPlayer.event.volumechange); } }, volumeBar: function(e) { // Handles clicks on the volumeBar if(this.css.jq.volumeBar.length) { // Using $(e.currentTarget) to enable multiple volume bars var $bar = $(e.currentTarget), offset = $bar.offset(), x = e.pageX - offset.left, w = $bar.width(), y = $bar.height() - e.pageY + offset.top, h = $bar.height(); if(this.options.verticalVolume) { this.volume(y/h); } else { this.volume(x/w); } } if(this.options.muted) { this._muted(false); } }, _updateVolume: function(v) { if(v === undefined) { v = this.options.volume; } v = this.options.muted ? 0 : v; if(this.status.noVolume) { this.addStateClass('noVolume'); if(this.css.jq.volumeBar.length) { this.css.jq.volumeBar.hide(); } if(this.css.jq.volumeBarValue.length) { this.css.jq.volumeBarValue.hide(); } if(this.css.jq.volumeMax.length) { this.css.jq.volumeMax.hide(); } } else { this.removeStateClass('noVolume'); if(this.css.jq.volumeBar.length) { this.css.jq.volumeBar.show(); } if(this.css.jq.volumeBarValue.length) { this.css.jq.volumeBarValue.show(); this.css.jq.volumeBarValue[this.options.verticalVolume ? "height" : "width"]((v*100)+"%"); } if(this.css.jq.volumeMax.length) { this.css.jq.volumeMax.show(); } } }, volumeMax: function() { // Handles clicks on the volume max this.volume(1); if(this.options.muted) { this._muted(false); } }, _cssSelectorAncestor: function(ancestor) { var self = this; this.options.cssSelectorAncestor = ancestor; this._removeUiClass(); this.ancestorJq = ancestor ? $(ancestor) : []; // Would use $() instead of [], but it is only 1.4+ if(ancestor && this.ancestorJq.length !== 1) { // So empty strings do not generate the warning. this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_COUNT, context: ancestor, message: $.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.ancestorJq.length + " found for cssSelectorAncestor.", hint: $.jPlayer.warningHint.CSS_SELECTOR_COUNT }); } this._addUiClass(); $.each(this.options.cssSelector, function(fn, cssSel) { self._cssSelector(fn, cssSel); }); // Set the GUI to the current state. this._updateInterface(); this._updateButtons(); this._updateAutohide(); this._updateVolume(); this._updateMute(); }, _cssSelector: function(fn, cssSel) { var self = this; if(typeof cssSel === 'string') { if($.jPlayer.prototype.options.cssSelector[fn]) { if(this.css.jq[fn] && this.css.jq[fn].length) { this.css.jq[fn].unbind(".jPlayer"); } this.options.cssSelector[fn] = cssSel; this.css.cs[fn] = this.options.cssSelectorAncestor + " " + cssSel; if(cssSel) { // Checks for empty string this.css.jq[fn] = $(this.css.cs[fn]); } else { this.css.jq[fn] = []; // To comply with the css.jq[fn].length check before its use. As of jQuery 1.4 could have used $() for an empty set. } if(this.css.jq[fn].length && this[fn]) { var handler = function(e) { e.preventDefault(); self[fn](e); if(self.options.autoBlur) { $(this).blur(); } else { $(this).focus(); // Force focus for ARIA. } }; this.css.jq[fn].bind("click.jPlayer", handler); // Using jPlayer namespace } if(cssSel && this.css.jq[fn].length !== 1) { // So empty strings do not generate the warning. ie., they just remove the old one. this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_COUNT, context: this.css.cs[fn], message: $.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.css.jq[fn].length + " found for " + fn + " method.", hint: $.jPlayer.warningHint.CSS_SELECTOR_COUNT }); } } else { this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_METHOD, context: fn, message: $.jPlayer.warningMsg.CSS_SELECTOR_METHOD, hint: $.jPlayer.warningHint.CSS_SELECTOR_METHOD }); } } else { this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_STRING, context: cssSel, message: $.jPlayer.warningMsg.CSS_SELECTOR_STRING, hint: $.jPlayer.warningHint.CSS_SELECTOR_STRING }); } }, duration: function(e) { if(this.options.toggleDuration) { if(this.options.captureDuration) { e.stopPropagation(); } this._setOption("remainingDuration", !this.options.remainingDuration); } }, seekBar: function(e) { // Handles clicks on the seekBar if(this.css.jq.seekBar.length) { // Using $(e.currentTarget) to enable multiple seek bars var $bar = $(e.currentTarget), offset = $bar.offset(), x = e.pageX - offset.left, w = $bar.width(), p = 100 * x / w; this.playHead(p); } }, playbackRate: function(pbr) { this._setOption("playbackRate", pbr); }, playbackRateBar: function(e) { // Handles clicks on the playbackRateBar if(this.css.jq.playbackRateBar.length) { // Using $(e.currentTarget) to enable multiple playbackRate bars var $bar = $(e.currentTarget), offset = $bar.offset(), x = e.pageX - offset.left, w = $bar.width(), y = $bar.height() - e.pageY + offset.top, h = $bar.height(), ratio, pbr; if(this.options.verticalPlaybackRate) { ratio = y/h; } else { ratio = x/w; } pbr = ratio * (this.options.maxPlaybackRate - this.options.minPlaybackRate) + this.options.minPlaybackRate; this.playbackRate(pbr); } }, _updatePlaybackRate: function() { var pbr = this.options.playbackRate, ratio = (pbr - this.options.minPlaybackRate) / (this.options.maxPlaybackRate - this.options.minPlaybackRate); if(this.status.playbackRateEnabled) { if(this.css.jq.playbackRateBar.length) { this.css.jq.playbackRateBar.show(); } if(this.css.jq.playbackRateBarValue.length) { this.css.jq.playbackRateBarValue.show(); this.css.jq.playbackRateBarValue[this.options.verticalPlaybackRate ? "height" : "width"]((ratio*100)+"%"); } } else { if(this.css.jq.playbackRateBar.length) { this.css.jq.playbackRateBar.hide(); } if(this.css.jq.playbackRateBarValue.length) { this.css.jq.playbackRateBarValue.hide(); } } }, repeat: function(event) { // Handle clicks on the repeat button var guiAction = typeof event === "object"; // Flags GUI click events so we know this was not a direct command, but an action taken by the user on the GUI. if(guiAction && this.options.useStateClassSkin && this.options.loop) { this._loop(false); } else { this._loop(true); } }, repeatOff: function() { // Handle clicks on the repeatOff button this._loop(false); }, _loop: function(loop) { if(this.options.loop !== loop) { this.options.loop = loop; this._updateButtons(); this._trigger($.jPlayer.event.repeat); } }, // Options code adapted from ui.widget.js (1.8.7). Made changes so the key can use dot notation. To match previous getData solution in jPlayer 1. option: function(key, value) { var options = key; // Enables use: options(). Returns a copy of options object if ( arguments.length === 0 ) { return $.extend( true, {}, this.options ); } if(typeof key === "string") { var keys = key.split("."); // Enables use: options("someOption") Returns a copy of the option. Supports dot notation. if(value === undefined) { var opt = $.extend(true, {}, this.options); for(var i = 0; i < keys.length; i++) { if(opt[keys[i]] !== undefined) { opt = opt[keys[i]]; } else { this._warning( { type: $.jPlayer.warning.OPTION_KEY, context: key, message: $.jPlayer.warningMsg.OPTION_KEY, hint: $.jPlayer.warningHint.OPTION_KEY }); return undefined; } } return opt; } // Enables use: options("someOptionObject", someObject}). Creates: {someOptionObject:someObject} // Enables use: options("someOption", someValue). Creates: {someOption:someValue} // Enables use: options("someOptionObject.someOption", someValue). Creates: {someOptionObject:{someOption:someValue}} options = {}; var opts = options; for(var j = 0; j < keys.length; j++) { if(j < keys.length - 1) { opts[keys[j]] = {}; opts = opts[keys[j]]; } else { opts[keys[j]] = value; } } } // Otherwise enables use: options(optionObject). Uses original object (the key) this._setOptions(options); return this; }, _setOptions: function(options) { var self = this; $.each(options, function(key, value) { // This supports the 2 level depth that the options of jPlayer has. Would review if we ever need more depth. self._setOption(key, value); }); return this; }, _setOption: function(key, value) { var self = this; // The ability to set options is limited at this time. switch(key) { case "volume" : this.volume(value); break; case "muted" : this._muted(value); break; case "globalVolume" : this.options[key] = value; break; case "cssSelectorAncestor" : this._cssSelectorAncestor(value); // Set and refresh all associations for the new ancestor. break; case "cssSelector" : $.each(value, function(fn, cssSel) { self._cssSelector(fn, cssSel); // NB: The option is set inside this function, after further validity checks. }); break; case "playbackRate" : this.options[key] = value = this._limitValue(value, this.options.minPlaybackRate, this.options.maxPlaybackRate); if(this.html.used) { this._html_setProperty('playbackRate', value); } this._updatePlaybackRate(); break; case "defaultPlaybackRate" : this.options[key] = value = this._limitValue(value, this.options.minPlaybackRate, this.options.maxPlaybackRate); if(this.html.used) { this._html_setProperty('defaultPlaybackRate', value); } this._updatePlaybackRate(); break; case "minPlaybackRate" : this.options[key] = value = this._limitValue(value, 0.1, this.options.maxPlaybackRate - 0.1); this._updatePlaybackRate(); break; case "maxPlaybackRate" : this.options[key] = value = this._limitValue(value, this.options.minPlaybackRate + 0.1, 16); this._updatePlaybackRate(); break; case "fullScreen" : if(this.options[key] !== value) { // if changed var wkv = $.jPlayer.nativeFeatures.fullscreen.used.webkitVideo; if(!wkv || wkv && !this.status.waitForPlay) { if(!wkv) { // No sensible way to unset option on these devices. this.options[key] = value; } if(value) { this._requestFullscreen(); } else { this._exitFullscreen(); } if(!wkv) { this._setOption("fullWindow", value); } } } break; case "fullWindow" : if(this.options[key] !== value) { // if changed this._removeUiClass(); this.options[key] = value; this._refreshSize(); } break; case "size" : if(!this.options.fullWindow && this.options[key].cssClass !== value.cssClass) { this._removeUiClass(); } this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this._refreshSize(); break; case "sizeFull" : if(this.options.fullWindow && this.options[key].cssClass !== value.cssClass) { this._removeUiClass(); } this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this._refreshSize(); break; case "autohide" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this._updateAutohide(); break; case "loop" : this._loop(value); break; case "remainingDuration" : this.options[key] = value; this._updateInterface(); break; case "toggleDuration" : this.options[key] = value; break; case "nativeVideoControls" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); this._restrictNativeVideoControls(); this._updateNativeVideoControls(); break; case "noFullWindow" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); // Need to check again as noFullWindow can depend on this flag and the restrict() can override it. this.status.noFullWindow = this._uaBlocklist(this.options.noFullWindow); this._restrictNativeVideoControls(); this._updateButtons(); break; case "noVolume" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this.status.noVolume = this._uaBlocklist(this.options.noVolume); this._updateVolume(); this._updateMute(); break; case "emulateHtml" : if(this.options[key] !== value) { // To avoid multiple event handlers being created, if true already. this.options[key] = value; if(value) { this._emulateHtmlBridge(); } else { this._destroyHtmlBridge(); } } break; case "timeFormat" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. break; case "keyEnabled" : this.options[key] = value; if(!value && this === $.jPlayer.focus) { $.jPlayer.focus = null; } break; case "keyBindings" : this.options[key] = $.extend(true, {}, this.options[key], value); // store a merged DEEP copy of it, incase not all properties changed. break; case "audioFullScreen" : this.options[key] = value; break; case "autoBlur" : this.options[key] = value; break; } return this; }, // End of: (Options code adapted from ui.widget.js) _refreshSize: function() { this._setSize(); // update status and jPlayer element size this._addUiClass(); // update the ui class this._updateSize(); // update internal sizes this._updateButtons(); this._updateAutohide(); this._trigger($.jPlayer.event.resize); }, _setSize: function() { // Determine the current size from the options if(this.options.fullWindow) { this.status.width = this.options.sizeFull.width; this.status.height = this.options.sizeFull.height; this.status.cssClass = this.options.sizeFull.cssClass; } else { this.status.width = this.options.size.width; this.status.height = this.options.size.height; this.status.cssClass = this.options.size.cssClass; } // Set the size of the jPlayer area. this.element.css({'width': this.status.width, 'height': this.status.height}); }, _addUiClass: function() { if(this.ancestorJq.length) { this.ancestorJq.addClass(this.status.cssClass); } }, _removeUiClass: function() { if(this.ancestorJq.length) { this.ancestorJq.removeClass(this.status.cssClass); } }, _updateSize: function() { // The poster uses show/hide so can simply resize it. this.internal.poster.jq.css({'width': this.status.width, 'height': this.status.height}); // Video html or flash resized if necessary at this time, or if native video controls being used. if(!this.status.waitForPlay && this.html.active && this.status.video || this.html.video.available && this.html.used && this.status.nativeVideoControls) { this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else if(!this.status.waitForPlay && this.flash.active && this.status.video) { this.internal.flash.jq.css({'width': this.status.width, 'height': this.status.height}); } }, _updateAutohide: function() { var self = this, event = "mousemove.jPlayer", namespace = ".jPlayerAutohide", eventType = event + namespace, handler = function(event) { var moved = false, deltaX, deltaY; if(typeof self.internal.mouse !== "undefined") { //get the change from last position to this position deltaX = self.internal.mouse.x - event.pageX; deltaY = self.internal.mouse.y - event.pageY; moved = (Math.floor(deltaX) > 0) || (Math.floor(deltaY)>0); } else { moved = true; } // store current position for next method execution self.internal.mouse = { x : event.pageX, y : event.pageY }; // if mouse has been actually moved, do the gui fadeIn/fadeOut if (moved) { self.css.jq.gui.fadeIn(self.options.autohide.fadeIn, function() { clearTimeout(self.internal.autohideId); self.internal.autohideId = setTimeout( function() { self.css.jq.gui.fadeOut(self.options.autohide.fadeOut); }, self.options.autohide.hold); }); } }; if(this.css.jq.gui.length) { // End animations first so that its callback is executed now. // Otherwise an in progress fadeIn animation still has the callback to fadeOut again. this.css.jq.gui.stop(true, true); // Removes the fadeOut operation from the fadeIn callback. clearTimeout(this.internal.autohideId); // undefine mouse delete this.internal.mouse; this.element.unbind(namespace); this.css.jq.gui.unbind(namespace); if(!this.status.nativeVideoControls) { if(this.options.fullWindow && this.options.autohide.full || !this.options.fullWindow && this.options.autohide.restored) { this.element.bind(eventType, handler); this.css.jq.gui.bind(eventType, handler); this.css.jq.gui.hide(); } else { this.css.jq.gui.show(); } } else { this.css.jq.gui.hide(); } } }, fullScreen: function(event) { var guiAction = typeof event === "object"; // Flags GUI click events so we know this was not a direct command, but an action taken by the user on the GUI. if(guiAction && this.options.useStateClassSkin && this.options.fullScreen) { this._setOption("fullScreen", false); } else { this._setOption("fullScreen", true); } }, restoreScreen: function() { this._setOption("fullScreen", false); }, _fullscreenAddEventListeners: function() { var self = this, fs = $.jPlayer.nativeFeatures.fullscreen; if(fs.api.fullscreenEnabled) { if(fs.event.fullscreenchange) { // Create the event handler function and store it for removal. if(typeof this.internal.fullscreenchangeHandler !== 'function') { this.internal.fullscreenchangeHandler = function() { self._fullscreenchange(); }; } document.addEventListener(fs.event.fullscreenchange, this.internal.fullscreenchangeHandler, false); } // No point creating handler for fullscreenerror. // Either logic avoids fullscreen occurring (w3c/moz), or their is no event on the browser (webkit). } }, _fullscreenRemoveEventListeners: function() { var fs = $.jPlayer.nativeFeatures.fullscreen; if(this.internal.fullscreenchangeHandler) { document.removeEventListener(fs.event.fullscreenchange, this.internal.fullscreenchangeHandler, false); } }, _fullscreenchange: function() { // If nothing is fullscreen, then we cannot be in fullscreen mode. if(this.options.fullScreen && !$.jPlayer.nativeFeatures.fullscreen.api.fullscreenElement()) { this._setOption("fullScreen", false); } }, _requestFullscreen: function() { // Either the container or the jPlayer div var e = this.ancestorJq.length ? this.ancestorJq[0] : this.element[0], fs = $.jPlayer.nativeFeatures.fullscreen; // This method needs the video element. For iOS and Android. if(fs.used.webkitVideo) { e = this.htmlElement.video; } if(fs.api.fullscreenEnabled) { fs.api.requestFullscreen(e); } }, _exitFullscreen: function() { var fs = $.jPlayer.nativeFeatures.fullscreen, e; // This method needs the video element. For iOS and Android. if(fs.used.webkitVideo) { e = this.htmlElement.video; } if(fs.api.fullscreenEnabled) { fs.api.exitFullscreen(e); } }, _html_initMedia: function(media) { // Remove any existing track elements var $media = $(this.htmlElement.media).empty(); // Create any track elements given with the media, as an Array of track Objects. $.each(media.track || [], function(i,v) { var track = document.createElement('track'); track.setAttribute("kind", v.kind ? v.kind : ""); track.setAttribute("src", v.src ? v.src : ""); track.setAttribute("srclang", v.srclang ? v.srclang : ""); track.setAttribute("label", v.label ? v.label : ""); if(v.def) { track.setAttribute("default", v.def); } $media.append(track); }); this.htmlElement.media.src = this.status.src; if(this.options.preload !== 'none') { this._html_load(); // See function for comments } this._trigger($.jPlayer.event.timeupdate); // The flash generates this event for its solution. }, _html_setFormat: function(media) { var self = this; // Always finds a format due to checks in setMedia() $.each(this.formats, function(priority, format) { if(self.html.support[format] && media[format]) { self.status.src = media[format]; self.status.format[format] = true; self.status.formatType = format; return false; } }); }, _html_setAudio: function(media) { this._html_setFormat(media); this.htmlElement.media = this.htmlElement.audio; this._html_initMedia(media); }, _html_setVideo: function(media) { this._html_setFormat(media); if(this.status.nativeVideoControls) { this.htmlElement.video.poster = this._validString(media.poster) ? media.poster : ""; } this.htmlElement.media = this.htmlElement.video; this._html_initMedia(media); }, _html_resetMedia: function() { if(this.htmlElement.media) { if(this.htmlElement.media.id === this.internal.video.id && !this.status.nativeVideoControls) { this.internal.video.jq.css({'width':'0px', 'height':'0px'}); } this.htmlElement.media.pause(); } }, _html_clearMedia: function() { if(this.htmlElement.media) { this.htmlElement.media.src = "about:blank"; // The following load() is only required for Firefox 3.6 (PowerMacs). // Recent HTMl5 browsers only require the src change. Due to changes in W3C spec and load() effect. this.htmlElement.media.load(); // Stops an old, "in progress" download from continuing the download. Triggers the loadstart, error and emptied events, due to the empty src. Also an abort event if a download was in progress. } }, _html_load: function() { // This function remains to allow the early HTML5 browsers to work, such as Firefox 3.6 // A change in the W3C spec for the media.load() command means that this is no longer necessary. // This command should be removed and actually causes minor undesirable effects on some browsers. Such as loading the whole file and not only the metadata. if(this.status.waitForLoad) { this.status.waitForLoad = false; this.htmlElement.media.load(); } clearTimeout(this.internal.htmlDlyCmdId); }, _html_play: function(time) { var self = this, media = this.htmlElement.media; this.androidFix.pause = false; // Cancel the pause fix. this._html_load(); // Loads if required and clears any delayed commands. // Setup the Android Fix. if(this.androidFix.setMedia) { this.androidFix.play = true; this.androidFix.time = time; } else if(!isNaN(time)) { // Attempt to play it, since iOS has been ignoring commands if(this.internal.cmdsIgnored) { media.play(); } try { // !media.seekable is for old HTML5 browsers, like Firefox 3.6. // Checking seekable.length is important for iOS6 to work with setMedia().play(time) if(!media.seekable || typeof media.seekable === "object" && media.seekable.length > 0) { media.currentTime = time; media.play(); } else { throw 1; } } catch(err) { this.internal.htmlDlyCmdId = setTimeout(function() { self.play(time); }, 250); return; // Cancel execution and wait for the delayed command. } } else { media.play(); } this._html_checkWaitForPlay(); }, _html_pause: function(time) { var self = this, media = this.htmlElement.media; this.androidFix.play = false; // Cancel the play fix. if(time > 0) { // We do not want the stop() command, which does pause(0), causing a load operation. this._html_load(); // Loads if required and clears any delayed commands. } else { clearTimeout(this.internal.htmlDlyCmdId); } // Order of these commands is important for Safari (Win) and IE9. Pause then change currentTime. media.pause(); // Setup the Android Fix. if(this.androidFix.setMedia) { this.androidFix.pause = true; this.androidFix.time = time; } else if(!isNaN(time)) { try { if(!media.seekable || typeof media.seekable === "object" && media.seekable.length > 0) { media.currentTime = time; } else { throw 1; } } catch(err) { this.internal.htmlDlyCmdId = setTimeout(function() { self.pause(time); }, 250); return; // Cancel execution and wait for the delayed command. } } if(time > 0) { // Avoids a setMedia() followed by stop() or pause(0) hiding the video play button. this._html_checkWaitForPlay(); } }, _html_playHead: function(percent) { var self = this, media = this.htmlElement.media; this._html_load(); // Loads if required and clears any delayed commands. // This playHead() method needs a refactor to apply the android fix. try { if(typeof media.seekable === "object" && media.seekable.length > 0) { media.currentTime = percent * media.seekable.end(media.seekable.length-1) / 100; } else if(media.duration > 0 && !isNaN(media.duration)) { media.currentTime = percent * media.duration / 100; } else { throw "e"; } } catch(err) { this.internal.htmlDlyCmdId = setTimeout(function() { self.playHead(percent); }, 250); return; // Cancel execution and wait for the delayed command. } if(!this.status.waitForLoad) { this._html_checkWaitForPlay(); } }, _html_checkWaitForPlay: function() { if(this.status.waitForPlay) { this.status.waitForPlay = false; if(this.css.jq.videoPlay.length) { this.css.jq.videoPlay.hide(); } if(this.status.video) { this.internal.poster.jq.hide(); this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } } }, _html_setProperty: function(property, value) { if(this.html.audio.available) { this.htmlElement.audio[property] = value; } if(this.html.video.available) { this.htmlElement.video[property] = value; } }, _aurora_setAudio: function(media) { var self = this; // Always finds a format due to checks in setMedia() $.each(this.formats, function(priority, format) { if(self.aurora.support[format] && media[format]) { self.status.src = media[format]; self.status.format[format] = true; self.status.formatType = format; return false; } }); this.aurora.player = new AV.Player.fromURL(this.status.src); this._addAuroraEventListeners(this.aurora.player, this.aurora); if(this.options.preload === 'auto') { this._aurora_load(); this.status.waitForLoad = false; } }, _aurora_resetMedia: function() { if (this.aurora.player) { this.aurora.player.stop(); } }, _aurora_clearMedia: function() { // Nothing to clear. }, _aurora_load: function() { if(this.status.waitForLoad) { this.status.waitForLoad = false; this.aurora.player.preload(); } }, _aurora_play: function(time) { if (!this.status.waitForLoad) { if (!isNaN(time)) { this.aurora.player.seek(time); } } if (!this.aurora.player.playing) { this.aurora.player.play(); } this.status.waitForLoad = false; this._aurora_checkWaitForPlay(); // No event from the player, update UI now. this._updateButtons(true); this._trigger($.jPlayer.event.play); }, _aurora_pause: function(time) { if (!isNaN(time)) { this.aurora.player.seek(time * 1000); } this.aurora.player.pause(); if(time > 0) { // Avoids a setMedia() followed by stop() or pause(0) hiding the video play button. this._aurora_checkWaitForPlay(); } // No event from the player, update UI now. this._updateButtons(false); this._trigger($.jPlayer.event.pause); }, _aurora_playHead: function(percent) { if(this.aurora.player.duration > 0) { // The seek() sould be in milliseconds, but the only codec that works with seek (aac.js) uses seconds. this.aurora.player.seek(percent * this.aurora.player.duration / 100); // Using seconds } if(!this.status.waitForLoad) { this._aurora_checkWaitForPlay(); } }, _aurora_checkWaitForPlay: function() { if(this.status.waitForPlay) { this.status.waitForPlay = false; } }, _aurora_volume: function(v) { this.aurora.player.volume = v * 100; }, _aurora_mute: function(m) { if (m) { this.aurora.properties.lastvolume = this.aurora.player.volume; this.aurora.player.volume = 0; } else { this.aurora.player.volume = this.aurora.properties.lastvolume; } this.aurora.properties.muted = m; }, _flash_setAudio: function(media) { var self = this; try { // Always finds a format due to checks in setMedia() $.each(this.formats, function(priority, format) { if(self.flash.support[format] && media[format]) { switch (format) { case "m4a" : case "fla" : self._getMovie().fl_setAudio_m4a(media[format]); break; case "mp3" : self._getMovie().fl_setAudio_mp3(media[format]); break; case "rtmpa": self._getMovie().fl_setAudio_rtmp(media[format]); break; } self.status.src = media[format]; self.status.format[format] = true; self.status.formatType = format; return false; } }); if(this.options.preload === 'auto') { this._flash_load(); this.status.waitForLoad = false; } } catch(err) { this._flashError(err); } }, _flash_setVideo: function(media) { var self = this; try { // Always finds a format due to checks in setMedia() $.each(this.formats, function(priority, format) { if(self.flash.support[format] && media[format]) { switch (format) { case "m4v" : case "flv" : self._getMovie().fl_setVideo_m4v(media[format]); break; case "rtmpv": self._getMovie().fl_setVideo_rtmp(media[format]); break; } self.status.src = media[format]; self.status.format[format] = true; self.status.formatType = format; return false; } }); if(this.options.preload === 'auto') { this._flash_load(); this.status.waitForLoad = false; } } catch(err) { this._flashError(err); } }, _flash_resetMedia: function() { this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); // Must do via CSS as setting attr() to zero causes a jQuery error in IE. this._flash_pause(NaN); }, _flash_clearMedia: function() { try { this._getMovie().fl_clearMedia(); } catch(err) { this._flashError(err); } }, _flash_load: function() { try { this._getMovie().fl_load(); } catch(err) { this._flashError(err); } this.status.waitForLoad = false; }, _flash_play: function(time) { try { this._getMovie().fl_play(time); } catch(err) { this._flashError(err); } this.status.waitForLoad = false; this._flash_checkWaitForPlay(); }, _flash_pause: function(time) { try { this._getMovie().fl_pause(time); } catch(err) { this._flashError(err); } if(time > 0) { // Avoids a setMedia() followed by stop() or pause(0) hiding the video play button. this.status.waitForLoad = false; this._flash_checkWaitForPlay(); } }, _flash_playHead: function(p) { try { this._getMovie().fl_play_head(p); } catch(err) { this._flashError(err); } if(!this.status.waitForLoad) { this._flash_checkWaitForPlay(); } }, _flash_checkWaitForPlay: function() { if(this.status.waitForPlay) { this.status.waitForPlay = false; if(this.css.jq.videoPlay.length) { this.css.jq.videoPlay.hide(); } if(this.status.video) { this.internal.poster.jq.hide(); this.internal.flash.jq.css({'width': this.status.width, 'height': this.status.height}); } } }, _flash_volume: function(v) { try { this._getMovie().fl_volume(v); } catch(err) { this._flashError(err); } }, _flash_mute: function(m) { try { this._getMovie().fl_mute(m); } catch(err) { this._flashError(err); } }, _getMovie: function() { return document[this.internal.flash.id]; }, _getFlashPluginVersion: function() { // _getFlashPluginVersion() code influenced by: // - FlashReplace 1.01: http://code.google.com/p/flashreplace/ // - SWFObject 2.2: http://code.google.com/p/swfobject/ var version = 0, flash; if(window.ActiveXObject) { try { flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); if (flash) { // flash will return null when ActiveX is disabled var v = flash.GetVariable("$version"); if(v) { v = v.split(" ")[1].split(","); version = parseInt(v[0], 10) + "." + parseInt(v[1], 10); } } } catch(e) {} } else if(navigator.plugins && navigator.mimeTypes.length > 0) { flash = navigator.plugins["Shockwave Flash"]; if(flash) { version = navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/, "$1"); } } return version * 1; // Converts to a number }, _checkForFlash: function (version) { var flashOk = false; if(this._getFlashPluginVersion() >= version) { flashOk = true; } return flashOk; }, _validString: function(url) { return (url && typeof url === "string"); // Empty strings return false }, _limitValue: function(value, min, max) { return (value < min) ? min : ((value > max) ? max : value); }, _urlNotSetError: function(context) { this._error( { type: $.jPlayer.error.URL_NOT_SET, context: context, message: $.jPlayer.errorMsg.URL_NOT_SET, hint: $.jPlayer.errorHint.URL_NOT_SET }); }, _flashError: function(error) { var errorType; if(!this.internal.ready) { errorType = "FLASH"; } else { errorType = "FLASH_DISABLED"; } this._error( { type: $.jPlayer.error[errorType], context: this.internal.flash.swf, message: $.jPlayer.errorMsg[errorType] + error.message, hint: $.jPlayer.errorHint[errorType] }); // Allow the audio player to recover if display:none and then shown again, or with position:fixed on Firefox. // This really only affects audio in a media player, as an audio player could easily move the jPlayer element away from such issues. this.internal.flash.jq.css({'width':'1px', 'height':'1px'}); }, _error: function(error) { this._trigger($.jPlayer.event.error, error); if(this.options.errorAlerts) { this._alert("Error!" + (error.message ? "\n" + error.message : "") + (error.hint ? "\n" + error.hint : "") + "\nContext: " + error.context); } }, _warning: function(warning) { this._trigger($.jPlayer.event.warning, undefined, warning); if(this.options.warningAlerts) { this._alert("Warning!" + (warning.message ? "\n" + warning.message : "") + (warning.hint ? "\n" + warning.hint : "") + "\nContext: " + warning.context); } }, _alert: function(message) { var msg = "jPlayer " + this.version.script + " : id='" + this.internal.self.id +"' : " + message; if(!this.options.consoleAlerts) { alert(msg); } else if(window.console && window.console.log) { window.console.log(msg); } }, _emulateHtmlBridge: function() { var self = this; // Emulate methods on jPlayer's DOM element. $.each( $.jPlayer.emulateMethods.split(/\s+/g), function(i, name) { self.internal.domNode[name] = function(arg) { self[name](arg); }; }); // Bubble jPlayer events to its DOM element. $.each($.jPlayer.event, function(eventName,eventType) { var nativeEvent = true; $.each( $.jPlayer.reservedEvent.split(/\s+/g), function(i, name) { if(name === eventName) { nativeEvent = false; return false; } }); if(nativeEvent) { self.element.bind(eventType + ".jPlayer.jPlayerHtml", function() { // With .jPlayer & .jPlayerHtml namespaces. self._emulateHtmlUpdate(); var domEvent = document.createEvent("Event"); domEvent.initEvent(eventName, false, true); self.internal.domNode.dispatchEvent(domEvent); }); } // The error event would require a special case }); // IE9 has a readyState property on all elements. The document should have it, but all (except media) elements inherit it in IE9. This conflicts with Popcorn, which polls the readyState. }, _emulateHtmlUpdate: function() { var self = this; $.each( $.jPlayer.emulateStatus.split(/\s+/g), function(i, name) { self.internal.domNode[name] = self.status[name]; }); $.each( $.jPlayer.emulateOptions.split(/\s+/g), function(i, name) { self.internal.domNode[name] = self.options[name]; }); }, _destroyHtmlBridge: function() { var self = this; // Bridge event handlers are also removed by destroy() through .jPlayer namespace. this.element.unbind(".jPlayerHtml"); // Remove all event handlers created by the jPlayer bridge. So you can change the emulateHtml option. // Remove the methods and properties var emulated = $.jPlayer.emulateMethods + " " + $.jPlayer.emulateStatus + " " + $.jPlayer.emulateOptions; $.each( emulated.split(/\s+/g), function(i, name) { delete self.internal.domNode[name]; }); } }; $.jPlayer.error = { FLASH: "e_flash", FLASH_DISABLED: "e_flash_disabled", NO_SOLUTION: "e_no_solution", NO_SUPPORT: "e_no_support", URL: "e_url", URL_NOT_SET: "e_url_not_set", VERSION: "e_version" }; $.jPlayer.errorMsg = { FLASH: "jPlayer's Flash fallback is not configured correctly, or a command was issued before the jPlayer Ready event. Details: ", // Used in: _flashError() FLASH_DISABLED: "jPlayer's Flash fallback has been disabled by the browser due to the CSS rules you have used. Details: ", // Used in: _flashError() NO_SOLUTION: "No solution can be found by jPlayer in this browser. Neither HTML nor Flash can be used.", // Used in: _init() NO_SUPPORT: "It is not possible to play any media format provided in setMedia() on this browser using your current options.", // Used in: setMedia() URL: "Media URL could not be loaded.", // Used in: jPlayerFlashEvent() and _addHtmlEventListeners() URL_NOT_SET: "Attempt to issue media playback commands, while no media url is set.", // Used in: load(), play(), pause(), stop() and playHead() VERSION: "jPlayer " + $.jPlayer.prototype.version.script + " needs Jplayer.swf version " + $.jPlayer.prototype.version.needFlash + " but found " // Used in: jPlayerReady() }; $.jPlayer.errorHint = { FLASH: "Check your swfPath option and that Jplayer.swf is there.", FLASH_DISABLED: "Check that you have not display:none; the jPlayer entity or any ancestor.", NO_SOLUTION: "Review the jPlayer options: support and supplied.", NO_SUPPORT: "Video or audio formats defined in the supplied option are missing.", URL: "Check media URL is valid.", URL_NOT_SET: "Use setMedia() to set the media URL.", VERSION: "Update jPlayer files." }; $.jPlayer.warning = { CSS_SELECTOR_COUNT: "e_css_selector_count", CSS_SELECTOR_METHOD: "e_css_selector_method", CSS_SELECTOR_STRING: "e_css_selector_string", OPTION_KEY: "e_option_key" }; $.jPlayer.warningMsg = { CSS_SELECTOR_COUNT: "The number of css selectors found did not equal one: ", CSS_SELECTOR_METHOD: "The methodName given in jPlayer('cssSelector') is not a valid jPlayer method.", CSS_SELECTOR_STRING: "The methodCssSelector given in jPlayer('cssSelector') is not a String or is empty.", OPTION_KEY: "The option requested in jPlayer('option') is undefined." }; $.jPlayer.warningHint = { CSS_SELECTOR_COUNT: "Check your css selector and the ancestor.", CSS_SELECTOR_METHOD: "Check your method name.", CSS_SELECTOR_STRING: "Check your css selector is a string.", OPTION_KEY: "Check your option name." }; }));
{ // Map BGM addAudio:[ ["map-bgm",[audioserver+"cave.mp3",audioserver+"cave.ogg"],{channel:"bgmusic",loop:true}] ], // Map graphics addImage:[ ["tiles","resources/gfx-cave.png"] ], // Map Tileset addTiles:[ {id:"tiles",image:"tiles",tileh:30,tilew:30,tilerow:10,gapx:0,gapy:0} ], setObject:[ // Dialogues on this map { object:"dialogues", property:"arrowstutorial", value:{ istutorial:true, font:"smalltut", skipkey:"a", esckey:"b", who: noface, scenes:[ { speed:1, who:"noone", audio:"beep", talk:["Use the B button to switch between","weapons. Now you can fire lighting","arrows! Try to hit the B button and","then fire with A!"]} ] } },{ object:"dialogues", property:"usebtutorial", value:{ istutorial:true, font:"smalltut", skipkey:"a", esckey:"b", who: noface, scenes:[ { speed:1, who:"noone", audio:"beep", talk:["Use the B button to interact","with objects, that means that you can","open doors, tresaure chests, talk","with villagers etc."]} ] } },{ object:"dialogues", property:"soul", value:{ endgame:true, font:"small", skipkey:"a", esckey:null, who: noface, scenes:[ { speed:1, who:"noone", audio:"beepbad", talk:["Your eyes... I know you, my little","guy..."]}, { speed:1, who:"noone", audio:"beepbad", talk:["I'm the guardian of all the souls","who died here, tricked by the evil","villagers of the Kariko village."]}, { speed:1, who:"noone", audio:"beepbad", talk:["I'll teach everything I know. A","day you'll be able to go out","and bring the rage of the tricked."]}, { speed:6, who:"noone", audio:"beepbad", talk:["You are the Hero of the Legend.","The Legend of Sadness."]} ] } // Map data and actions },{ object:"tilemaps", property:"map", value:{ tileset:"tiles", map:[ [ 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12], [ 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12], [ 12, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 12, 0, 0, 13, 13, 13, 13, 13, 13, 13, 0, 0, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 0, 0, 14, 14, 14, 14, 6, 6, 14, 0, 0, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 11, 11, 13, 13, 14, 14, 14, 14, 6, 6, 14, 13, 13, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 10, 10, 14, 14, 14, 14, 14, 14, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 3, 6, 6, 6, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 0, 0, 0, 6, 6, 6, 12, 12, 13, 13, 13, 13, 13, 13, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 0, 0, 0, 6, 6, 6, 12, 12, 14, 14, 14, 14, 14, 14, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 14, 14, 14, 14, 14, 14, 6, 6, 14, 14, 14, 12], [ 12, 6, 1, 6, 6, 6, 6, 6, 6, 6, 12, 12, 0, 0, 14, 14, 14, 14, 6, 6, 14, 0, 0, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 0, 0, 14, 14, 14, 14, 13, 13, 14, 0, 0, 12], [ 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12] ], addObjects:function() { if (!tilemaps.queststatus["oldmanstory"]) gbox.playAudio("map-bgm"); if (tilemaps.queststatus["oldmanstory"]) // If you've heard the old man story... maingame.addNpc(555,180,[8,9],"soul"); // The soul of the tricked appears. if (!tilemaps.queststatus["floor2trapped"]) { maingame.setTileInMap(14,6,4,false); } if (!tilemaps.queststatus["floor2arrows"]) { maingame.addChest(19,6,null,false,"arrow",null,0); } if (tilemaps.queststatus["floor1eyeswitch"]&&!tilemaps.queststatus["bosskey"]) { maingame.addEnemy("fifth1","octo",3,4,true); maingame.addEnemy("fifth2","octo",5,4,true); maingame.addEnemy("fifth3","octo",6,4,true); maingame.addEnemy("fifth4","octo",7,4,true); tilemaps.queststatus["_tmpbosskey"]=false; } }, mapActions:function() { var pl=gbox.getObject("player","player"); var ontile=help.getTileInMap(pl.x+pl.colx+pl.colhw,pl.y+pl.coly+pl.colhh,tilemaps.map,tilemaps._defaultblock,"map"); if (!tilemaps.queststatus["floor2trapped"]&&!tilemaps.queststatus["floor2untrapped"]){ // the trap on floor 2 if (ontile==4) { gbox.hitAudio("beep"); // Switch sound maingame.addDoor("sidedoor","doorv",10,4,true); maingame.addEnemy("third1","octo",13,2,true); maingame.addEnemy("third2","octo",21,2,true); maingame.addEnemy("third3","octo",13,10,true); maingame.addEnemy("third4","octo",21,10,true); tilemaps.queststatus["floor2trapped"]=true; // Trap on maingame.addQuestClear("TRAPPED!"); maingame.startDialogue("usebtutorial"); // Explain how to open the first tresaure chest. maingame.setTileInMap(14,6,3,true); } } if (tilemaps.queststatus["floor2trapped"]&&!tilemaps.queststatus["floor2untrapped"]) { if (!gbox.getObject("foes","third1")&&!gbox.getObject("foes","third2")&&!gbox.getObject("foes","third3")&&!gbox.getObject("foes","third4")) { // check them. If beaten... gbox.getObject("walls","sidedoor").doOpen(); tilemaps.queststatus["floor2untrapped"]=true; // Set the quest as done... maingame.addQuestClear(); // Arcade-ish message "QUEST CLEAR"! } } if (tilemaps.queststatus["floor1eyeswitch"]&&!tilemaps.queststatus["bosskey"]&&!tilemaps.queststatus["_tmpbosskey"]) { if (!gbox.getObject("foes","fifth1")&&!gbox.getObject("foes","fifth2")&&!gbox.getObject("foes","fifth3")&&!gbox.getObject("foes","fifth4")) { // check them. If beaten... maingame.addQuestClear(); // Quest clear maingame.addChest(5,7,null,true,"BOSSKEY","bosskey",0); tilemaps.queststatus["_tmpbosskey"]=true; } } var pl=gbox.getObject("player","player"); var ontile=help.getTileInMap(pl.x+pl.colx+pl.colhw,pl.y+pl.coly+pl.colhh,tilemaps.map,tilemaps._defaultblock,"map"); if (ontile==1) maingame.gotoLevel({level:"floor1",x:60,y:530,label:"Floor 1 stairs"}); }, tileIsSolid:function(obj,t){ return (obj._bullet?(t!=13)&&(t!=14):true)&&(t>9) } // Bullets flies over the pits. } } ] }
export { default as deepClone } from './deepClone'; export { default as isPrimitive } from './isPrimitive'; export { default as getVariable } from './getVariable'; export { default as isPlainObject } from 'is-plain-obj'; export { default as deepEqual } from 'deep-equal';
/* External dependencies */ import React from 'react' import classNames from 'classnames' /* Internal dependencies */ import styles from './Input.scss' class Input extends React.Component { constructor() { super() this.inputRef = null } componentDidMount() { if (this.props.autoFocus) { this.inputRef.focus() } } render() { const { className, inputClassName, ...props } = this.props return ( <div className={classNames(styles.wrapper, className)}> <input {...props} ref={e => this.inputRef = e} className={classNames(styles.input, inputClassName)} /> </div> ) } } export default Input
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/Table/TableRowColumn": require('material-ui/Table/TableRowColumn') } }, name: "TableRowColumn", ports: { input: { children: { type: "array", propType: "node", name: "children", required: false }, className: { type: "string", name: "className", required: false }, columnNumber: { type: "number", name: "columnNumber", required: false }, hoverable: { type: "boolean", name: "hoverable", "default": false }, onClick: { title: "Enable onClick", type: "boolean", name: "onClick", required: false }, onHover: { title: "Enable onHover", type: "boolean", name: "onHover", required: false }, onHoverExit: { title: "Enable onHoverExit", type: "boolean", name: "onHoverExit", required: false }, style: { type: "object", name: "style", required: false } }, output: { component: { title: "TableRowColumn", type: "Component" }, onClick: { type: "any" }, onHover: { type: "any" }, onHoverExit: { type: "any" } } } }
import React from 'react' import Map from '../Map/Map' import Sidebar from '../Sidebar/Sidebar' import { restaurantsRef, restaurantImgRef } from '../lib/firebase' import * as Modes from '../modes' import Navbar from './Navbar' import LocationSelector from './LocationSelector' import uuid from 'uuid/v1' class App extends React.Component { state = { mode: Modes.EXPLORE, markers: [], selectedMarker: undefined, center: undefined, myLocation: undefined, selectedLocation: undefined, isSidebarActive: false, } constructor() { super() this.handleMapLoad = this.handleMapLoad.bind(this) this.handleMapClick = this.handleMapClick.bind(this) this.handleMarkerClick = this.handleMarkerClick.bind(this) this.handleCenterChanged = this.handleCenterChanged.bind(this) this.handleToggleSidebar = this.handleToggleSidebar.bind(this) this.handleChangeMode = this.handleChangeMode.bind(this) this.handleChooseLocation = this.handleChooseLocation.bind(this) this.handleResetMode = this.handleResetMode.bind(this) this.handleSelectionMode = this.handleSelectionMode.bind(this) this.handlePartialUpdate = this.handlePartialUpdate.bind(this) this.handleUpload = this.handleUpload.bind(this) this.handleDeleteFile = this.handleDeleteFile.bind(this) this.handleDeleteRef = this.handleDeleteRef.bind(this) this.handleCreateLocation = this.handleCreateLocation.bind(this) this.handleCreateMenu = this.handleCreateMenu.bind(this) this.handleUpdateLocation = this.handleUpdateLocation.bind(this) this.handleRemoveLocation = this.handleRemoveLocation.bind(this) } componentDidMount() { this.getCurrentPosition() this.handleRestaurantData() } handleUpload(file, customName) { if (!file) return Promise.resolve({ src: '', ref: '', }) const name = customName || uuid() + file.name return restaurantImgRef.child(name).put(file).then(snapshot => { const src = snapshot.downloadURL const img = { src, ref: name, } return img }) } handleDeleteFile(ref) { return restaurantImgRef.child(ref).delete() } handleCreateLocation({ name, img, menus }) { const { lat, lng } = this.state.selectedLocation const newRestaurant = restaurantsRef.push() newRestaurant.set({ name, img, latLng: { lat: lat(), lng: lng() }, }) .then(_ => menus.map(m => newRestaurant.child('menus').push().set(m).then(_ => ({ ...m })))) .then(ps => Promise.all(ps)) .then(this.handleResetMode) } handleCreateMenu(id, menu) { console.log('create menu', id, menu) const newMenu = restaurantsRef.child(id).child('menus').push() return newMenu.set(menu).then(_ => ({ id: newMenu.key, ...menu, })) } handlePartialUpdate(ref, partialUpdate) { return restaurantsRef.child(ref).update(partialUpdate) } handleDeleteRef(ref) { return restaurantsRef.child(ref).remove() } handleUpdateLocation(restaurant) { const { id: restaurantId, name, img, latLng, menus } = restaurant const ps = menus.map(a => { const { id, name, price, img } = a if (!!id) { return Promise.resolve(a) } const m = restaurantsRef.child(restaurantId).child('menus').push() return m.set({ name, price, img, }) .then(_ => ({ id: m.key, ...a })) }) Promise.all(ps).then(ms => ms.reduce((b, { id, name, price, img }) => ({ ...b, [id]: { name, price, img }, }), {})) .then(menus => restaurantsRef.child(restaurantId).set({ name, img, latLng, menus, })) .then(this.handleResetMode) } handleRemoveLocation(id) { restaurantsRef.child(id).remove().then(_ => { const markers = this.state.markers.filter(m => m.id !== id) this.setState({ markers }) this.handleResetMode() }) } handleChangeMode(mode) { this.setState({ mode }) } handleToggleSidebar() { this.setState(prev => ({ isSidebarActive: !prev.isSidebarActive, })) } handleMarkerClick(targetMarker) { this.setState({ mode: Modes.DETAIL, selectedMarker: targetMarker, selectedLocation: undefined, isSidebarActive: true, }) } handleRestaurantData() { restaurantsRef.on('value', (snap) => { const restaurants = snap.val() if (!restaurants) return const mapMenus = menus => menus ? Object.keys(menus).map(id => ({ id, img: menus[id].img, name: menus[id].name, price: menus[id].price, })) : [] const markers = Object.keys(restaurants).map(id => ({ id, img: restaurants[id].img, name: restaurants[id].name, latLng: restaurants[id].latLng, menus: mapMenus(restaurants[id].menus), })) console.log('new markers', markers) this.setState({ markers }) }) } getCurrentPosition() { if ('geolocation' in navigator) { const handleCurrentPosition = (position) => { const { latitude: lat, longitude: lng } = position.coords this._map.panTo({ lat, lng }) const center = this._map.getCenter() this.setState({ center, myLocation: { lat, lng }, }) } const handleError = (err) => console.error(err) const options = { enableHighAccuracy: true, } navigator.geolocation.getCurrentPosition(handleCurrentPosition, handleError, options) } } handleMapLoad(map) { this._map = map const center = this._map.getCenter() this.setState({ center }) } handleMapClick({ latLng }) { console.log(latLng.lat(), latLng.lng()) } handleCenterChanged() { const center = this._map.getCenter() this.setState({ center }) } handleChooseLocation() { const mode = Modes.ADD_LOCATION this.setState(prev => ({ mode, selectedLocation: prev.center })) this.handleToggleSidebar() } handleResetMode() { this.setState({ mode: Modes.EXPLORE, selectedLocation: undefined, isSidebarActive: false, }) } handleSelectionMode() { this.handleChangeMode(Modes.SELECT_LOCATION) this.handleToggleSidebar() } render() { const fullHeight = { height: '100%' } const mapContainer = <div id="map-container" style={fullHeight} /> const mapElement = <div id="map-element" style={fullHeight} /> const { selectedLocation, isSidebarActive, mode, myLocation, center, markers, selectedMarker } = this.state return ( <div id="app-container" style={fullHeight}> <Sidebar selectedMarker={selectedMarker} mode={mode} active={isSidebarActive} onSelectionMode={this.handleSelectionMode} onResetMode={this.handleResetMode} onChangeMode={this.handleChangeMode} onClose={this.handleToggleSidebar} onPartialUpdate={this.handlePartialUpdate} onRemoveLocation={this.handleRemoveLocation} onUpdateLocation={this.handleUpdateLocation} onCreateLocation={this.handleCreateLocation} onCreateMenu={this.handleCreateMenu} onUpload={this.handleUpload} onDeleteFile={this.handleDeleteFile} onDeleteRef={this.handleDeleteRef} /> <Navbar mode={mode} onCancel={this.handleResetMode} onToggle={this.handleToggleSidebar} /> {mode === Modes.SELECT_LOCATION && <LocationSelector onClick={this.handleChooseLocation} />} <Map selectedLocation={selectedLocation} myLocation={myLocation} center={center} markers={markers} containerElement={mapContainer} mapElement={mapElement} onMapLoad={this.handleMapLoad} onMapClick={this.handleMapClick} onCenterChanged={this.handleCenterChanged} onMarkerClick={this.handleMarkerClick} /> </div> ) } } export default App
'use strict'; /* * Defining the Package */ var Module = require('meanio').Module; var Theme = new Module('theme'); /* * All MEAN packages require registration * Dependency injection is used to define required modules */ Theme.register(function(app, auth, database) { //We enable routing. By default the Package Object is passed to the routes Theme.routes(app, auth, database); //We are adding a link to the main menu for all authenticated users //Theme.menus.add({ //title: 'theme example page', //link: 'theme example page', //roles: ['authenticated'], //menu: 'main' //}); Theme.aggregateAsset('css', 'loginForms.css'); Theme.aggregateAsset('css', 'theme.css'); /** //Uncomment to use. Requires meanio@0.3.7 or above // Save settings with callback // Use this for saving data from administration pages Theme.settings({ 'someSetting': 'some value' }, function(err, settings) { //you now have the settings object }); // Another save settings example this time with no callback // This writes over the last settings. Theme.settings({ 'anotherSettings': 'some value' }); // Get settings. Retrieves latest saved settings Theme.settings(function(err, settings) { //you now have the settings object }); */ return Theme; });
/* =================================================== * bootstrap-transition.js v2.0.3 * http://twitter.github.com/bootstrap/javascript.html#transitions * =================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { $(function () { "use strict"; // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $.support.transition = (function () { var transitionEnd = (function () { var el = document.createElement('bootstrap') , transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd' , 'msTransition' : 'MSTransitionEnd' , 'transition' : 'transitionend' } , name for (name in transEndEventNames){ if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery); /* ============================================================= * bootstrap-collapse.js v2.0.3 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSIBLE PLUGIN DEFINITION * ============================== */ $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = typeof option == 'object' && option if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSIBLE DATA-API * ==================== */ $(function () { $('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $(target).collapse(option) }) }) }(window.jQuery);
import sinon from 'sinon'; import simulate from 'simulate'; import { h, mountSync, unmountSync } from '../../src/vidom'; describe('domEvents', () => { let domNode; beforeEach(() => { document.body.appendChild(domNode = document.createElement('div')); }); afterEach(() => { unmountSync(domNode); document.body.removeChild(domNode); }); describe('bubbleable events', () => { it('should properly add handler', () => { const spy1 = sinon.spy(), spy2 = sinon.spy(), spy3 = sinon.spy(); mountSync( domNode, h('div', { onClick : spy1 }, [ h('div', { onClick : spy2 }, h('div', { id : 'id1' })), h('div', { onClick : spy3 }, h('div', { id : 'id2' })) ])); simulate.click(document.getElementById('id1')); expect(spy1.called).to.be.ok(); expect(spy2.called).to.be.ok(); expect(spy3.called).not.to.be.ok(); simulate.click(document.getElementById('id2')); expect(spy1.calledTwice).to.be.ok(); expect(spy2.calledOnce).to.be.ok(); expect(spy3.called).to.be.ok(); }); it('should properly call handler with Event object', () => { const spy = sinon.spy(); mountSync( domNode, h('div', { id : 'id1', onClick : spy })); simulate.click(document.getElementById('id1')); const [[e]] = spy.args; expect(e instanceof Event).to.be.ok(); expect(e.type).to.be.equal('click'); }); it('should properly stop propagation', () => { const spy = sinon.spy(); mountSync( domNode, h( 'div', { onClick : spy }, h('div', { id : 'id1', onClick(e) { e.stopPropagation(); e.cancelBubble = true; // emulate browser behaviour } }) )); simulate.click(document.getElementById('id1')); expect(spy.called).not.to.be.ok(); }); it('should properly prevent default', () => { mountSync( domNode, h('input', { type : 'checkbox', id : 'id1', onClick(e) { e.preventDefault(); } })); simulate.click(document.getElementById('id1')); expect(document.getElementById('id1').checked).not.to.be.ok(); }); it('should properly remove handler', () => { const spy1 = sinon.spy(), spy2 = sinon.spy(); mountSync( domNode, h('div', { id : 'id1', onClick : spy1 })); mountSync( domNode, h('div', { id : 'id1', onDblClick : spy2 })); simulate.click(document.getElementById('id1')); simulate.dblclick(document.getElementById('id1')); expect(spy1.called).not.to.be.ok(); expect(spy2.called).to.be.ok(); }); it('should properly replace handler for bubbleable events', () => { const spy1 = sinon.spy(), spy2 = sinon.spy(); mountSync( domNode, h('div', { id : 'id1', onClick : spy1 })); mountSync( domNode, h('div', { id : 'id1', onClick : spy2 })); simulate.click(document.getElementById('id1')); expect(spy1.called).not.to.be.ok(); expect(spy2.called).to.be.ok(); }); it('should properly simulate bubbling of focus event', () => { const spy = sinon.spy(); mountSync( domNode, h('div', { id : 'id1', onFocus : spy }, h('input'))); simulate.focusin(document.getElementById('id1')); expect(spy.called).to.be.ok(); }); it('should properly simulate bubbling of blur event', () => { const spy = sinon.spy(); mountSync( domNode, h('div', { onBlur : spy }, h('input', { id : 'id1' }))); simulate.focus(document.getElementById('id1')); simulate.focusout(document.getElementById('id1')); expect(spy.called).to.be.ok(); }); it('should properly add handler when existing dom is adopted', () => { const spy1 = sinon.spy(), spy2 = sinon.spy(); domNode.innerHTML= '<div><div><div id="id1"></div></div></div>'; mountSync( domNode, h('div', { onClick : spy1 }, h('div', { onClick : spy2 }, h('div', { id : 'id1' })))); simulate.click(document.getElementById('id1')); expect(spy1.called).to.be.ok(); expect(spy2.called).to.be.ok(); }); }); describe('non-bubbleable events', () => { it('should properly add handler', () => { const spy1 = sinon.spy(), spy2 = sinon.spy(), spy3 = sinon.spy(); mountSync( domNode, h('div', { onScroll : spy1 }, [ h('div', { id : 'id1', onScroll : spy2 }), h('div', { id : 'id2', onScroll : spy3 }) ])); simulate.scroll(document.getElementById('id1')); expect(spy1.called).not.to.be.ok(); expect(spy2.called).to.be.ok(); expect(spy3.called).not.to.be.ok(); }); it('should properly call handler with Event object', () => { const spy = sinon.spy(); mountSync( domNode, h('div', { id : 'id1', onScroll : spy })); simulate.scroll(document.getElementById('id1')); const [[e]] = spy.args; expect(e instanceof Event).to.be.ok(); expect(e.type).to.be.equal('scroll'); }); it('should properly remove handler', () => { const spy = sinon.spy(); mountSync( domNode, h('div', { id : 'id1', onScroll : spy })); mountSync( domNode, h('div', { id : 'id1' })); simulate.scroll(document.getElementById('id1')); expect(spy.called).not.to.be.ok(); }); it('should properly replace handler for non-bubbleable events', () => { const spy1 = sinon.spy(), spy2 = sinon.spy(); mountSync( domNode, h('div', { id : 'id1', onScroll : spy1 })); mountSync( domNode, h('div', { id : 'id1', onScroll : spy2 })); simulate.scroll(document.getElementById('id1')); expect(spy1.called).not.to.be.ok(); expect(spy2.called).to.be.ok(); }); }); });
jQuery(document).ready(function() { updateHeaderTransparency(); $(window).scroll(function(){ updateHeaderTransparency(); }); $(window).resize(function(){ updateHeaderTransparency(); }); function updateHeaderTransparency() { var offset = ($('header').height() + parseInt($('main').css('padding-top')) ) * -1; $('.main-feature').css("margin-top", offset); if ($('header').hasClass('scrolled') || $('#search-box').hasClass("open")) { transparencyOff(); } else if ($('.main-feature').length && !$("body").hasClass("template-home-page")) { transparencyOn(); } } function transparencyOn() { $('header').addClass("transparency"); $('#toggle-mobile').hide(); $('#search-box-toggle').hide(); $('#main-menu').hide(); } function transparencyOff() { $('header').removeClass("transparency"); $('#toggle-mobile').show(); $('#search-box-toggle').show(); $('#main-menu').show(); if ($('#search-box').hasClass("open") && $(window).width() >= breakpoint) { if ($('header').hasClass('collapsed')) { $('#toggle-mobile').show(); } else { $('#toggle-mobile').hide(); } } } });
$('#data_mahasiswa_tanggal_lahir').datepicker({ dateFormat: 'yy-mm-dd'});
document.addEventListener('DOMContentLoaded', function() { actionHelper.checkPluginEnabled(); $('#pop').click(function(e) { e.stopPropagation(); e.preventDefault(); window.open(chrome.extension.getURL("popup.html"),"gc-popout-window","width =560,height=550"); }); $("#enabled").click(function(e) { e.stopPropagation(); e.preventDefault(); var enabled = actionHelper.isEnabled(); if(enabled === "true") actionHelper.setEnabled(false); else actionHelper.setEnabled(true); actionHelper.checkPluginEnabled(); }); $('.btn.btn-xs.btn-primary').on( 'click', function() { actionHelper.generateData(this); }); });
// Regular expression that matches all symbols in the `Avestan` script as per Unicode v8.0.0: /\uD802[\uDF00-\uDF35\uDF39-\uDF3F]/;
$(document).ready(function(){ $('.parallax').parallax();}); $(document).ready(function(){ $('.carousel').carousel(); }); $(document).ready(function(){ $('.slider').slider(); }); $(document).ready(function(){ $(".button-collapse").sideNav(); }); // Initialize collapse button $(".button-collapse").sideNav(); // Initialize collapsible (uncomment the line below if you use the dropdown variation) //$('.collapsible').collapsible(); $(".bg").interactive_bg({ strength: 25, scale: 1.05, animationSpeed: "100ms", contain: true, wrapContent: false });
'use strict'; /** * Module dependencies */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Document Schema */ var DocumentSchema = new Schema({ created: { type: Date, default: Date.now }, values: { type: Array, default: [] }, form: { type: Schema.ObjectId, ref: 'Form' }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Document', DocumentSchema);
/** File: strophe.js * A JavaScript library for XMPP BOSH. * * This is the JavaScript version of the Strophe library. Since JavaScript * has no facilities for persistent TCP connections, this library uses * Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate * a persistent, stateful, two-way connection to an XMPP server. More * information on BOSH can be found in XEP 124. * * This program is distributed under the terms of the MIT license. * Please see the LICENSE file for details. * Copyright 2006-2008, OGG, LLC */ /*global DOMParser: false, XMLHttpRequest: false, ActiveXObject: false, Strophe: true, msos: false, _: false, $build: true, $msg: true, $iq: true, $pres: true, */ (function (callback) { "use strict"; var Strophe, stph_bld = 'Strophe.Builder - ', stph_con = 'Strophe.Connection - ', stph_hdl = 'Strophe.Handler - '; function $build(name, attrs) { return new Strophe.Builder(name, attrs); } function $msg(attrs) { return new Strophe.Builder("message", attrs); } function $iq(attrs) { return new Strophe.Builder("iq", attrs); } function $pres(attrs) { return new Strophe.Builder("presence", attrs); } Strophe = { VERSION: "1.0.2", /* XMPP Namespace Constants */ NS: { HTTPBIND: "http://jabber.org/protocol/httpbind", BOSH: "urn:xmpp:xbosh", CLIENT: "jabber:client", AUTH: "jabber:iq:auth", ROSTER: "jabber:iq:roster", PROFILE: "jabber:iq:profile", DISCO_INFO: "http://jabber.org/protocol/disco#info", DISCO_ITEMS: "http://jabber.org/protocol/disco#items", MUC: "http://jabber.org/protocol/muc", SASL: "urn:ietf:params:xml:ns:xmpp-sasl", STREAM: "http://etherx.jabber.org/streams", BIND: "urn:ietf:params:xml:ns:xmpp-bind", SESSION: "urn:ietf:params:xml:ns:xmpp-session", VERSION: "jabber:iq:version", STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas", XHTML_IM: "http://jabber.org/protocol/xhtml-im", XHTML: "http://www.w3.org/1999/xhtml" }, XHTML: { tags: ['a', 'blockquote', 'br', 'cite', 'em', 'img', 'li', 'ol', 'p', 'span', 'strong', 'ul', 'body'], attributes: { 'a': ['href'], 'blockquote': ['style'], 'br': [], 'cite': ['style'], 'em': [], 'img': ['src', 'alt', 'style', 'height', 'width'], 'li': ['style'], 'ol': ['style'], 'p': ['style'], 'span': ['style'], 'strong': [], 'ul': ['style'], 'body': [] }, css: [ 'background-color', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'margin-left', 'margin-right', 'text-align', 'text-decoration' ], validTag: function (tag) { var i = 0; for (i = 0; i < Strophe.XHTML.tags.length; i += 1) { if (tag === Strophe.XHTML.tags[i]) { return true; } } return false; }, validAttribute: function (tag, attribute) { var i = 0; if (Strophe.XHTML.attributes[tag] !== undefined && Strophe.XHTML.attributes[tag].length > 0) { for (i = 0; i < Strophe.XHTML.attributes[tag].length; i += 1) { if (attribute === Strophe.XHTML.attributes[tag][i]) { return true; } } } return false; }, validCSS: function (style) { var i = 0; for (i = 0; i < Strophe.XHTML.css.length; i += 1) { if (style === Strophe.XHTML.css[i]) { return true; } } return false; } }, addNamespace: function (name, value) { Strophe.NS[name] = value; }, /* Connection Status Constants */ Status: { ERROR: 0, CONNECTING: 1, CONNFAIL: 2, AUTHENTICATING: 3, AUTHFAIL: 4, CONNECTED: 5, DISCONNECTED: 6, DISCONNECTING: 7, ATTACHED: 8 }, status_name : ['ERROR', 'CONNECTING', 'CONNFAIL', 'AUTHENTICATING', 'AUTHFAIL', 'CONNECTED', 'DISCONNECTED', 'DISCONNECTING', 'ATTACHED'], ElementType: { NORMAL: 1, TEXT: 3, CDATA: 4, FRAGMENT: 11 }, /* PrivateConstants: Timeout Values * TIMEOUT - Math.floor(TIMEOUT * wait) seconds have elapsed, (default: 1.1, for a wait of 66 seconds). * SECONDARY_TIMEOUT - Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed, (default: 0.1, for a wait of 6 seconds). */ TIMEOUT: 1.1, SECONDARY_TIMEOUT: 0.1, forEachChild: function (elem, func) { var i, childNode; for (i = 0; i < elem.childNodes.length; i += 1) { childNode = elem.childNodes[i]; if (childNode.nodeType === Strophe.ElementType.NORMAL) { func(childNode); } } }, _xmlGenerator: null, xmlGenerator: function () { if (!Strophe._xmlGenerator) { var doc = document.implementation.createDocument('jabber:client', 'strophe', null); Strophe._xmlGenerator = doc; } return Strophe._xmlGenerator; }, xmlElement: function (name) { if (!name) { return null; } var node = Strophe.xmlGenerator().createElement(name), a = 0, i = 0, k = ''; for (a = 1; a < arguments.length; a += 1) { if (!msos.var_is_empty(arguments[a])) { if (typeof arguments[a] === "string" || typeof arguments[a] === "number") { node.appendChild(Strophe.xmlTextNode(arguments[a])); } else if (typeof arguments[a] === "object" && typeof arguments[a].sort === "function") { for (i = 0; i < arguments[a].length; i += 1) { if (typeof arguments[a][i] === "object" && typeof arguments[a][i].sort === "function") { node.setAttribute(arguments[a][i][0], arguments[a][i][1]); } } } else if (typeof arguments[a] === "object") { for (k in arguments[a]) { node.setAttribute(k, arguments[a][k]); } } } } return node; }, xmlescape: function (text) { if (msos.var_is_empty(text)) { msos.console.warn('Strophe.xmlescape -> missing input!'); return ''; } text = text.replace(/\&/g, "&amp;"); text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); text = text.replace(/'/g, "&apos;"); text = text.replace(/"/g, "&quot;"); return text; }, xmlTextNode: function (text) { return Strophe.xmlGenerator().createTextNode(text); }, xmlHtmlNode: function (html) { var doc = null, dbg = '', parser; if (window.DOMParser) { dbg = 'DOMParser'; parser = new DOMParser(); // Because FF wants valid XML, with correct namespaces! doc = parser.parseFromString("<body xmlns:stream='foo' >" + html + "</body>", "text/xml").documentElement.firstChild; } else if (window.ActiveXObject) { dbg = 'ActiveXObject'; doc = new ActiveXObject("MSXML2.DOMDocument"); doc.async = false; doc.preserveWhiteSpace = true; doc.loadXML(html); } else { msos.console.error("Strophe.xmlHtmlNode -> error: parser na!"); } if (msos.config.query.domparse) { msos.console.debug("Strophe.xmlHtmlNode -> via: " + dbg + ", from: " + html); } return doc; }, getText: function (elem) { if (!elem) { return null; } var str = '', i = 0; if (elem.childNodes.length === 0 && elem.nodeType === Strophe.ElementType.TEXT) { str += elem.nodeValue; } for (i = 0; i < elem.childNodes.length; i += 1) { if (elem.childNodes[i].nodeType === Strophe.ElementType.TEXT) { str += elem.childNodes[i].nodeValue; } } return Strophe.xmlescape(str); }, copyElement: function (elem) { var i = 0, el; if (elem.nodeType === Strophe.ElementType.NORMAL) { el = Strophe.xmlElement(elem.tagName); for (i = 0; i < elem.attributes.length; i += 1) { el.setAttribute( elem.attributes[i].nodeName.toLowerCase(), elem.attributes[i].value ); } for (i = 0; i < elem.childNodes.length; i += 1) { el.appendChild(Strophe.copyElement(elem.childNodes[i])); } } else if (elem.nodeType === Strophe.ElementType.TEXT) { el = Strophe.xmlGenerator().createTextNode(elem.nodeValue); } return el; }, createHtml: function (elem) { var i = 0, el, j = 0, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue; msos.console.debug('Strophe.createHtml -> called.'); if (elem.nodeType === Strophe.ElementType.NORMAL) { tag = elem.nodeName.toLowerCase(); if (Strophe.XHTML.validTag(tag)) { try { el = Strophe.xmlElement(tag); for (i = 0; i < Strophe.XHTML.attributes[tag].length; i += 1) { attribute = Strophe.XHTML.attributes[tag][i]; value = elem.getAttribute(attribute); if (!msos.var_is_empty(value) && value !== false && value !== 0) { if (attribute === 'style' && typeof value === 'object') { if (value.cssText !== undefined) { value = value.cssText; } } // filter out invalid css styles if (attribute === 'style') { css = []; cssAttrs = value.split(';'); for (j = 0; j < cssAttrs.length; j += 1) { attr = cssAttrs[j].split(':'); cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase(); if (Strophe.XHTML.validCSS(cssName)) { cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, ""); css.push(cssName + ': ' + cssValue); } } if (css.length > 0) { value = css.join('; '); el.setAttribute(attribute, value); } } else { el.setAttribute(attribute, value); } } } for (i = 0; i < elem.childNodes.length; i += 1) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } catch (e) { // invalid elements el = Strophe.xmlTextNode(''); msos.console.warn('Strophe - createHtml -> invalid elements in: ' + tag + ', error: ' + e); } } else { el = Strophe.xmlGenerator().createDocumentFragment(); for (i = 0; i < elem.childNodes.length; i += 1) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } } else if (elem.nodeType === Strophe.ElementType.FRAGMENT) { el = Strophe.xmlGenerator().createDocumentFragment(); for (i = 0; i < elem.childNodes.length; i += 1) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } else if (elem.nodeType === Strophe.ElementType.TEXT) { el = Strophe.xmlTextNode(elem.nodeValue); } return el; }, escapeNode: function (node) { if (msos.var_is_empty(node)) { msos.console.warn('Strophe.escapeNode -> missing input!'); return ''; } return node.replace(/^\s+|\s+$/g, '') .replace(/\\/g, "\\5c") .replace(/ /g, "\\20") .replace(/\"/g, "\\22") .replace(/\&/g, "\\26") .replace(/\'/g, "\\27") .replace(/\//g, "\\2f") .replace(/:/g, "\\3a") .replace(/</g, "\\3c") .replace(/>/g, "\\3e") .replace(/@/g, "\\40"); }, unescapeNode: function (node) { if (msos.var_is_empty(node)) { msos.console.warn('Strophe.unescapeNode -> missing input!'); return ''; } return node.replace(/\\20/g, " ") .replace(/\\22/g, '"') .replace(/\\26/g, "&") .replace(/\\27/g, "'") .replace(/\\2f/g, "/") .replace(/\\3a/g, ":") .replace(/\\3c/g, "<") .replace(/\\3e/g, ">") .replace(/\\40/g, "@") .replace(/\\5c/g, "\\"); }, getNodeFromJid: function (jid) { var out = null; if (jid.indexOf("@") < 0) { msos.console.debug('Strophe.getNodeFromJid -> called, node: null'); return out; } out = jid.split("@")[0]; if (msos.config.verbose) { msos.console.debug('Strophe.getNodeFromJid -> called, node: ' + out); } return out; }, getDomainFromJid: function (jid) { var bare = Strophe.getBareJidFromJid(jid), parts = [], out; if (bare.indexOf("@") < 0) { msos.console.debug('Strophe.getDomainFromJid -> called, domain: ' + bare); return bare; } parts = bare.split("@"); parts.splice(0, 1); out = parts.join('@'); if (msos.config.verbose) { msos.console.debug('Strophe.getDomainFromJid -> called, domain: ' + out); } return out; }, getResourceFromJid: function (jid) { var s = jid.split("/"), out = null; if (s.length < 2) { msos.console.debug('Strophe.getResourceFromJid -> called, resource: null'); return out; } s.splice(0, 1); out = s.join('/'); if (msos.config.verbose) { msos.console.debug('Strophe.getResourceFromJid -> called, resource: ' + out); } return out; }, getBareJidFromJid: function (jid) { var out = jid ? jid.split("/")[0] : null; msos.console.debug('Strophe.getBareJidFromJid -> called, bare: ' + out); return out; }, serialize: function (elem) { var nodeName, result, i, child; if (msos.config.query.serialize) { msos.console.debug('Strophe.serialize -> start.'); } if (msos.var_is_empty(elem)) { msos.console.warn('Strophe.serialize -> done, no elem!'); return null; } if (typeof elem.tree === "function") { elem = elem.tree(); } nodeName = elem.nodeName; if (elem.getAttribute("_realname")) { nodeName = elem.getAttribute("_realname"); } result = "<" + nodeName; for (i = 0; i < elem.attributes.length; i += 1) { if (elem.attributes[i].nodeName !== "_realname") { result += " " + elem.attributes[i].nodeName.toLowerCase() + "='" + elem.attributes[i].value .replace(/&/g, "&amp;") .replace(/\'/g, "&apos;") .replace(/>/g, "&gt;") .replace(/</g, "&lt;") + "'"; } } if (elem.childNodes.length > 0) { result += ">"; for (i = 0; i < elem.childNodes.length; i += 1) { child = elem.childNodes[i]; switch(child.nodeType){ case Strophe.ElementType.NORMAL: // normal element, so recurse result += Strophe.serialize(child); break; case Strophe.ElementType.TEXT: // text element to escape values result += Strophe.xmlescape(child.nodeValue); break; case Strophe.ElementType.CDATA: // cdata section so don't escape values result += "<![CDATA[" + child.nodeValue + "]]>"; break; } } result += "</" + nodeName + ">"; } else { result += "/>"; } if (msos.config.query.serialize) { msos.console.debug('Strophe.serialize -> done, output: ' + result); } return result; }, _requestId: 0, _connectionPlugins: {}, addConnectionPlugin: function (name, ptype) { Strophe._connectionPlugins[name] = ptype; } }; Strophe.Builder = function (name, attrs) { // Set correct namespace for jabber:client elements if (name === "presence" || name === "message" || name === "iq") { if (attrs && !attrs.xmlns) { attrs.xmlns = Strophe.NS.CLIENT; } else if (!attrs) { attrs = { xmlns: Strophe.NS.CLIENT }; } } // Holds the tree being built. this.nodeTree = Strophe.xmlElement(name, attrs); // Points to the current operation node. this.node = this.nodeTree; }; Strophe.Builder.prototype = { tree: function () { return this.nodeTree; }, toString: function () { return Strophe.serialize(this.nodeTree); }, up: function () { this.node = this.node.parentNode; return this; }, attrs: function (moreattrs) { var k = ''; for (k in moreattrs) { this.node.setAttribute(k, moreattrs[k]); } return this; }, c: function (name, attrs, text) { var child = Strophe.xmlElement(name, attrs, text); this.node.appendChild(child); if (!text) { this.node = child; } return this; }, cnode: function (elem) { var xmlGen = Strophe.xmlGenerator(), impNode = false, newElem; try { impNode = (xmlGen.importNode !== undefined); } catch (e) { impNode = false; msos.console.warn(stph_bld + 'cnode -> error: ' + e); } newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem); this.node.appendChild(newElem); this.node = newElem; return this; }, t: function (text) { var child = Strophe.xmlTextNode(text); this.node.appendChild(child); return this; }, h: function (html) { var fragment = document.createElement('body'), xhtml; // force the browser to try and fix any invalid HTML tags fragment.innerHTML = html; // copy cleaned html into an xml dom xhtml = Strophe.createHtml(fragment); while (xhtml.childNodes.length > 0) { this.node.appendChild(xhtml.childNodes[0]); } return this; } }; Strophe.Handler = function (handler, ns, name, type, id, from, options) { this.handler = handler; this.ns = ns; this.name = name; this.type = type; this.id = id; this.options = options || { matchBare: false }; // default matchBare to false if undefined if (!this.options.matchBare) { this.options.matchBare = false; } if (this.options.matchBare) { this.from = from ? Strophe.getBareJidFromJid(from) : null; } else { this.from = from; } this.user = true; }; Strophe.Handler.prototype = { isMatch: function (elem) { var nsMatch, from = null, that = this; if (this.options.matchBare) { from = Strophe.getBareJidFromJid(elem.getAttribute('from')); } else { from = elem.getAttribute('from'); } nsMatch = false; if (!this.ns) { nsMatch = true; } else { Strophe.forEachChild( elem, function (elem) { if (elem.getAttribute("xmlns") === that.ns) { nsMatch = true; } } ); nsMatch = nsMatch || elem.getAttribute("xmlns") === this.ns; } if (nsMatch && (!this.name || elem.tagName.toLowerCase() === this.name.toLowerCase()) && (!this.type || elem.getAttribute("type") === this.type) && (!this.id || elem.getAttribute("id") === this.id) && (!this.from || from === this.from)) { return true; } return false; }, run: function (elem) { var result = null; if (msos.config.verbose) { msos.console.debug(stph_hdl + "run -> start, for:", elem); } try { result = this.handler(elem); } catch (e) { if (e.sourceURL) { msos.console.error(stph_hdl + "run -> error w/url: " + e.sourceURL + ":" + e.line + " - " + e.name + ": " + e.message + "\n", this.handler); } else if (e.fileName) { msos.console.error(stph_hdl + "run -> error w/file: " + e.fileName + ":" + e.lineNumber + " - " + e.name + ": " + e.message + "\n", this.handler); } else if (e.stack) { msos.console.error(stph_hdl + "run -> error w/stack: " + e.stack + "\n", this.handler); } else { msos.console.error(stph_hdl + "run -> error plain: " + e.message + "\n", this.handler); } } if (msos.config.verbose) { msos.console.debug(stph_hdl + "run -> done!"); } return result; }, toString: function () { return "{ Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ") }"; } }; Strophe.TimedHandler = function (period, handler) { this.period = period; this.handler = handler; this.lastCalled = new Date().getTime(); this.user = true; }; Strophe.TimedHandler.prototype = { run: function () { this.lastCalled = new Date().getTime(); return this.handler(); }, reset: function () { this.lastCalled = new Date().getTime(); }, toString: function () { return "{ TimedHandler: " + this.handler + "(" + this.period + ") }"; } }; Strophe.Connection = function (service) { /* The path to the httpbind service or websocket url. */ this.service = service; this.jid = ""; this.domain = null; this.features = null; this.rid = Math.floor(Math.random() * 4294967295); this.sid = null; this.streamId = null; this.resource = null; // ws only this.do_session = false; this.do_bind = false; // Handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this._idleTimeout = null; this._disconnectTimeout = null; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this.paused = false; // Default values (BOSH only) this.hold = 1; this.wait = 60; this.window = 5; // Default values (ws only) this.ws = null; this.connect_timeout = 300; this._keep_alive_timer = 20000; this._data = []; this._requests = []; this._uniqueId = Math.round(Math.random() * 10000); this._idleTimeout = setTimeout(_.bind(this._onIdle, this), 100); var k = '', ptype, F; // Initialize plugins for (k in Strophe._connectionPlugins) { ptype = Strophe._connectionPlugins[k]; F = function () {}; F.prototype = ptype; this[k] = new F(); this[k].init(this); } }; Strophe.Connection.prototype = { reset: function () { this.rid = Math.floor(Math.random() * 4294967295); this.sid = null; this.streamId = null; this.do_session = false; this.do_bind = false; // Handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this._requests = []; this._uniqueId = Math.round(Math.random() * 10000); }, pause: function () { this.paused = true; }, resume: function () { this.paused = false; }, getUniqueId: function (suffix) { this._uniqueId += 1; if (typeof suffix === "string" || typeof suffix === "number") { return this._uniqueId + ":" + suffix; } return String(this._uniqueId); }, xmlInput: function (elem) { return; }, xmlOutput: function (elem) { return; }, rawInput: function (data) { return; }, rawOutput: function (data) { return; }, _changeConnectStatus: function (status, condition) { var k = '', plugin, debug = 'failed.'; msos.console.debug(stph_con + "_changeConnectStatus -> start, for: " + Strophe.status_name[status] + ' (' + status + ')'); // Notify all plugins listening for status changes for (k in Strophe._connectionPlugins) { plugin = this[k]; if (plugin.statusChanged) { plugin.statusChanged(status, condition); } } // Notify the user's callback if (typeof this.connect_callback === 'function') { this.connect_callback(status, condition); debug = 'with callback function.'; } else { debug = 'wwithout callback function.'; } msos.console.debug(stph_con + "_changeConnectStatus -> done, " + (condition ? condition + ' ' : '') + debug); }, // ------------------------------------ // Start - WebSocket specific functions // ------------------------------------ connect: function (jid, pass, callback) { msos.console.debug(stph_con + "connect -> start, jid: " + jid); this.jid = jid; this.authzid = Strophe.getBareJidFromJid(this.jid); this.authcid = Strophe.getNodeFromJid(this.jid); this.pass = pass; this.servtype = "xmpp"; this.connect_callback = callback; this.disconnecting = false; this.connected = false; this.authenticated = false; this.errors = 0; // Parse jid for domain and resource this.domain = Strophe.getDomainFromJid(this.jid); this.resource = Strophe.getResourceFromJid(this.jid); this._changeConnectStatus(Strophe.Status.CONNECTING, null); // Start WebSocket specific code if (!this.ws) { this.ws = new WebSocket(this.service, this.servtype); this.ws.onopen = _.bind(this._ws_on_open, this); this.ws.onerror = _.bind(this._ws_on_error, this); this.ws.onclose = _.bind(this._ws_on_close, this); this.ws.onmessage = _.bind(this._ws_on_message, this); } // End WebSocket specific code msos.console.debug(stph_con + "connect -> done, jid: " + jid); }, attach: function () { return; }, flush: function () { return; }, send: function (elem) { var i = 0; msos.console.debug(stph_con + "send -> start."); if (msos.var_is_null(elem)) { msos.console.error(stph_con + "send -> done, missing input!"); return; } if (typeof elem.sort === "function") { for (i = 0; i < elem.length; i += 1) { this._queueData(elem[i]); } } else if (typeof elem.tree === "function") { this._queueData(elem.tree()); } else { this._queueData(elem); } clearTimeout(this._idleTimeout); this._idleTimeout = setTimeout(_.bind(this._onIdle, this), 100); msos.console.debug(stph_con + "send -> done!"); }, _doDisconnect: function () { msos.console.debug(stph_con + "_doDisconnect -> start."); this.authenticated = false; this.disconnecting = false; this.sid = null; this.streamId = null; this.rid = Math.floor(Math.random() * 4294967295); // tell the parent we disconnected if (this.connected) { this._changeConnectStatus(Strophe.Status.DISCONNECTED, null); this.connected = false; } // delete handlers this.handlers = []; this.timedHandlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; if (this.ws.readyState !== this.ws.CLOSED) { this.ws.close(); } this.ws = null; msos.console.debug(stph_con + "_doDisconnect -> done!"); }, _onDisconnectTimeout: function () { msos.console.debug(stph_con + "_onDisconnectTimeout -> start."); this._doDisconnect(); msos.console.debug(stph_con + "_onDisconnectTimeout -> done!"); return false; }, _sendTerminate: function () { var stanza; msos.console.debug(stph_con + "_sendTerminate -> start."); this.disconnecting = true; if (this.authenticated) { stanza = $pres( { xmlns: Strophe.NS.CLIENT, type: 'unavailable' } ); this.ws.send(stanza); } else if (this.ws.readyState !== this.ws.CLOSED) { this.ws.send('</stream:stream>'); } msos.console.debug(stph_con + "_sendTerminate -> done!"); }, _buildBody: function (stanza) { var bodyWrap = $build( 'body', { rid: this.rid, xmlns: Strophe.NS.HTTPBIND } ); if (this.sid !== null) { bodyWrap.attrs({ sid: this.sid }); } return bodyWrap.cnode(stanza); }, _ws_on_open: function () { var elem, resource; msos.console.debug(stph_con + "_ws_on_open -> start."); // Connected, so acknowledge this.connected = true; this._addSysHandler( _.bind(this._session_cb, this), null, null, null, "_session_init" ); this.sid = Math.floor(Math.random() * 4294967295); resource = Strophe.getResourceFromJid(this.jid); if (resource) { this.send( $iq( { type: "set", id: "_session_init" } ).c( 'bind', { xmlns: Strophe.NS.BIND } ).c( 'resource', {} ).t(resource).tree()); } else { this.send( $iq( { type: "set", id: "_session_init" } ).c( 'bind', { xmlns: Strophe.NS.BIND }).tree()); } this._addSysTimedHandler( this._keep_alive_timer, _.bind(this._keep_alive_handler, this) ); msos.console.debug(stph_con + "_ws_on_open -> done!"); }, _ws_on_message: function (message) { var string = message.data, elem, dbug = ''; msos.console.debug(stph_con + "_ws_on_message -> start."); elem = Strophe.xmlHtmlNode(string); if (this.disconnecting && elem.nodeName === "presence" && elem.getAttribute("type") === "unavailable") { dbug = 'disconnecting, nodeName: '+ elem.nodeName; } else { elem = this._buildBody(elem).tree(); dbug = 'success, nodeName: '+ elem.nodeName this._dataRecv(elem); } msos.console.debug(stph_con + "_ws_on_message -> done, success!"); }, _ws_on_error: function (e) { var msg = e.data || 'missing or bad connection.'; msos.console.error(stph_con + "_ws_on_error -> error: " + msg, e); }, _ws_on_close: function (ev) { msos.console.debug(stph_con + "_ws_on_close -> called."); this._doDisconnect(); }, _keep_alive_handler: function () { this.ws.send("\n"); return true; }, _session_cb: function (elem) { var bind, jidNode, jidText; msos.console.debug(stph_con + "_session_cb -> start."); if (elem.getAttribute("type") === "result") { bind = elem.getElementsByTagName("bind"); if (bind.length > 0) { jidNode = bind[0].getElementsByTagName("jid"); if (jidNode.length > 0) { jidText = Strophe.getText(jidNode[0]); this.jid = this.sid + '@' + Strophe.getDomainFromJid(jidText) + '/' + this.resource; } } else { this.jid = this.sid + '@' + this.domain + '/' + this.resource; } msos.console.debug(stph_con + "_session_cb -> authenticated for: " + this.jid); this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } else if (elem.getAttribute("type") === "error") { msos.console.warn(stph_con + "_session_cb -> session creation failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } msos.console.debug(stph_con + "_session_cb -> done!"); return false; }, _processRequest: function (stanza) { var tmp_r = '_processRequest -> ', xmlstring = ''; msos.console.debug(stph_con + tmp_r + "start."); this.rid += 1; // Request ID stanza.setAttribute('rid', this.rid); // Session ID stanza.setAttribute('sid', this.sid); xmlstring = Strophe.serialize(stanza); this.ws.send(xmlstring); if (this.xmlOutput !== Strophe.Connection.prototype.xmlOutput) { this.xmlOutput(stanza); } if (this.rawOutput !== Strophe.Connection.prototype.rawOutput) { this.rawOutput(xmlstring); } msos.console.debug(stph_con + tmp_r + "done!"); }, _onIdle: function () { var data = this._data, i = 0; if (data.length > 0 && !this.paused) { for (i = 0; i < data.length; i += 1) { if (data[i] !== null) { this._processRequest(data[i]); } } this._data = []; } }, // ---------------------------------- // End - WebSocket specific functions // ---------------------------------- _dataRecv: function (stanza) { msos.console.debug(stph_con + "_dataRecv -> start."); var i = 0, hand, typ, cond, conflict, that = this; if (stanza === null) { msos.console.warn(stph_con + "_dataRecv -> done, no stanza"); return; } if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) { this.xmlInput(stanza); } if (this.rawInput !== Strophe.Connection.prototype.rawInput) { this.rawInput(Strophe.serialize(stanza)); } while (this.removeHandlers.length > 0) { hand = this.removeHandlers.pop(); i = _.indexOf(this.handlers, hand); if (i >= 0) { this.handlers.splice(i, 1); } } // add handlers scheduled for addition while (this.addHandlers.length > 0) { this.handlers.push(this.addHandlers.pop()); } // handle graceful disconnect if (this.disconnecting && this._requests.length === 0) { this.deleteTimedHandler(this._disconnectTimeout); this._disconnectTimeout = null; this._doDisconnect(); msos.console.debug(stph_con + "_dataRecv -> done, graceful disconnect."); return; } typ = stanza.getAttribute("type"); if (typ !== null && typ === "terminate") { if (this.disconnecting) { msos.console.debug(stph_con + "_dataRecv -> done, too late to process."); return; } // an error occurred cond = stanza.getAttribute("condition"); conflict = stanza.getElementsByTagName("conflict"); if (cond !== null) { if (cond === "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._changeConnectStatus(Strophe.Status.CONNFAIL, cond); } else { this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown"); } this.disconnect(); msos.console.warn(stph_con + "_dataRecv -> done, something went wrong."); return; } // send each incoming stanza through the handler chain Strophe.forEachChild( stanza, function (child) { var i = 0, newList, hand; newList = that.handlers; that.handlers = []; for (i = 0; i < newList.length; i += 1) { hand = newList[i]; // encapsulate 'handler.run' not to lose the whole handler list if // one of the handlers throws an exception try { if (hand.isMatch(child) && (that.authenticated || !hand.user)) { if (hand.run(child)) { that.handlers.push(hand); } } else { that.handlers.push(hand); } } catch(e) { msos.console.warn(stph_con + "_dataRecv -> handler error: " + e); } } } ); msos.console.debug(stph_con + "_dataRecv -> done!"); }, _queueData: function (element) { if (element === null || !element.tagName || !element.childNodes) { throw { name: stph_con + "_queueData -> ", message: "Cannot queue non-DOMElement." }; } this._data.push(element); if (msos.config.verbose) { msos.console.debug(stph_con + "_queueData -> called, queued requests: " + this._data.length); } }, disconnect: function (reason) { msos.console.debug(stph_con + "disconnect -> start, reason: " + reason); this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason); if (this.connected) { // setup timeout handler this._disconnectTimeout = this._addSysTimedHandler( 3000, _.bind(this._onDisconnectTimeout, this) ); this._sendTerminate(); } msos.console.debug(stph_con + "disconnect -> done!"); }, sendIQ: function (elem, callback, errback, timeout) { var timeoutHandler = null, that = this, id = '', handler; msos.console.debug(stph_con + "sendIQ -> start."); if (typeof elem.tree === "function") { elem = elem.tree(); } id = elem.getAttribute('id') || ''; if (!id) { id = this.getUniqueId("sendIQ"); elem.setAttribute("id", id); } handler = this.addHandler( function (stanza) { // remove timeout handler if there is one if (timeoutHandler) { that.deleteTimedHandler(timeoutHandler); } var iqtype = stanza.getAttribute('type'); if (iqtype === 'result') { if (callback) { callback(stanza); } } else if (iqtype === 'error') { if (errback) { errback(stanza); } } else { throw { name: stph_con + "sendIQ -> ", message: "Got bad IQ type: " + iqtype }; } }, null, 'iq', null, id ); // if timeout specified, setup timeout handler. if (timeout) { timeoutHandler = this.addTimedHandler( timeout, function () { // get rid of normal handler that.deleteHandler(handler); // call errback on timeout with null stanza if (errback) { errback(null); } return false; } ); } this.send(elem); msos.console.debug(stph_con + "sendIQ -> done!"); return id; }, addTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); this.addTimeds.push(thand); return thand; }, deleteTimedHandler: function (handRef) { this.removeTimeds.push(handRef); }, addHandler: function (handler, ns, name, type, id, from, options) { var hand = new Strophe.Handler(handler, ns, name, type, id, from, options); this.addHandlers.push(hand); return hand; }, deleteHandler: function (handRef) { this.removeHandlers.push(handRef); }, _addSysTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); thand.user = false; this.addTimeds.push(thand); return thand; }, _addSysHandler: function (handler, ns, name, type, id) { var hand = new Strophe.Handler(handler, ns, name, type, id); hand.user = false; this.addHandlers.push(hand); return hand; } }; callback(Strophe, $build, $msg, $iq, $pres); }(function () { "use strict"; var args = Array.prototype.slice.call(arguments); window.Strophe = args[0]; window.$build = args[1]; window.$msg = args[2]; window.$iq = args[3]; window.$pres = args[4]; }));
var port = process.env.PORT || 5000; var redirectUrl = process.env.REDIRECT_URL || 'http://example.com'; var redirectStatusCode = process.env.REDIRECT_STATUS_CODE || 301; var keepRequestPath = process.env.REDIRECT_KEEP_REQUEST_PATH || false; var app = require('./server')({ 'redirectUrl' : redirectUrl, 'redirectStatusCode': redirectStatusCode, 'keepRequestPath': keepRequestPath }); app.listen(port); console.log('Server running on port ' + port);
(function(){ 'use strict'; angular.module('cla.controllers') .controller('OutcomesModalCtl', ['$scope', 'case', 'eod_details', 'event_key', 'outcome_codes', 'notes', 'tplVars', '$uibModalInstance', '$timeout', 'flash', 'postal', 'Feedback', 'Complaint', function($scope, _case, eod_details, event_key, outcome_codes, notes, tplVars, $uibModalInstance, $timeout, flash, postal, Feedback, Complaint) { // template vars tplVars = angular.extend({ 'title': 'Outcome code' }, tplVars); tplVars.buttonText = tplVars.buttonText || tplVars.title; $scope.tplVars = tplVars; $scope.outcome_codes = outcome_codes; $scope.selected = {}; $scope.selected.notes = notes || ''; $scope.feedback_allowed = (event_key === 'reject_case'); if(eod_details !== null) { if(_case.complaint_flag) { $scope.ircb_escalates = 'escalated'; } else if(eod_details.isEODSet()) { $scope.ircb_escalates = 'will_escalate'; } else { $scope.ircb_escalates = 'cant_escalate'; } } // focus on search field on open $uibModalInstance.opened.then(function () { $timeout(function () { angular.element('[name="outcome-modal-code-search"]').focus(); }, 50); }); // on save event var onSuccess = function (response) { $scope.$close(response); }; var onFail = function (response) { $scope.errors = {}; angular.forEach(response.data, function (errors, field) { if (Array.isArray(errors)) { $scope.errors[field] = errors.join(', '); } else { $scope.errors[field] = errors; } }); }; var saveEvent = function () { function doSave() { _case['$' + event_key]({ event_code: $scope.selected.outcome_code, notes: $scope.selected.notes }).then(onSuccess, onFail); } if(eod_details !== null && $scope.ircb_escalates === 'will_escalate' && $scope.selected.outcome_code === 'IRCB') { var complaint = new Complaint({ eod: eod_details.reference, // copy IRCB notes into complaint description (EOD notes go into created log event) description: $scope.selected.notes ? 'IRCB notes: ' + $scope.selected.notes : '' }); complaint.$update(function() { _case.complaint_flag = true; // could go _case.$get but that might wipe other changes postal.publish({ channel: 'Complaint', topic: 'save', data: complaint }); flash('success', 'EOD escalated to complaint'); doSave(); }, function() { flash('error', 'EOD not escalated to complaint'); doSave(); }); } else { doSave(); } }; $scope.submit = function(isValid) { if (isValid) { if ($scope.selected.issue) { var feedback_resource = new Feedback({ case: _case.reference, issue: $scope.selected.issue, comment: $scope.selected.notes }); feedback_resource.$save(function () { saveEvent(); }, onFail); } else { saveEvent(); } } }; $scope.cancel = function () { $scope.$dismiss('cancel'); }; } ] ); })();
describe("About Arrays", function() { // We shall contemplate truth by testing reality, via spec expectations. it("should create arrays", function() { var emptyArray = []; expect(typeof(emptyArray)).toBe('object'); // A mistake?-- http:javascript.crockford.com/remedial.html expect(emptyArray.length).toBe(0); var multiTypeArray = [0, 1, "two", function() { return 3; }, {value1: 4, value2: 5}, [6, 7]]; expect(multiTypeArray[0]).toBe(0); expect(multiTypeArray[2]).toBe('two'); expect(multiTypeArray[3]()).toBe(3); expect(multiTypeArray[4].value1).toBe(4); expect(multiTypeArray[4]["value2"]).toBe(5); expect(multiTypeArray[5][0]).toBe(6); }); it("should understand array literals", function() { var array = []; expect(array).toEqual([]); array[0] = 1; expect(array).toEqual([1]); array[1] = 2; expect(array).toEqual([1, 2]); array.push(3); expect(array).toEqual([1,2,3]); }); it("should understand array length", function() { var fourNumberArray = [1, 2, 3, 4]; expect(fourNumberArray.length).toBe(4); fourNumberArray.push(5, 6); expect(fourNumberArray.length).toBe(6); var tenEmptyElementArray = new Array(10); expect(tenEmptyElementArray.length).toBe(10); tenEmptyElementArray.length = 5; expect(tenEmptyElementArray.length).toBe(5); }); it("should slice arrays", function() { var array = ["peanut", "butter", "and", "jelly"]; expect(array.slice(0, 1)).toEqual(['peanut']); expect(array.slice(0, 2)).toEqual(['peanut', 'butter']); expect(array.slice(2, 2)).toEqual([]); expect(array.slice(2, 20)).toEqual(['and', 'jelly']); expect(array.slice(3, 0)).toEqual([]); expect(array.slice(3, 100)).toEqual(['jelly']); expect(array.slice(5, 1)).toEqual([]); }); it("should know array references", function() { var array = [ "zero", "one", "two", "three", "four", "five" ]; function passedByReference(refArray) { refArray[1] = "changed in function"; } passedByReference(array); expect(array[1]).toBe('changed in function'); var assignedArray = array; assignedArray[5] = "changed in assignedArray"; expect(array[5]).toBe('changed in assignedArray'); var copyOfArray = array.slice(); copyOfArray[3] = "changed in copyOfArray"; expect(array[3]).toBe('three'); }); it("should push and pop", function() { var array = [1, 2]; array.push(3); expect(array).toEqual([1,2,3]); var poppedValue = array.pop(); expect(poppedValue).toBe(3); expect(array).toEqual([1,2]); }); it("should know about shifting arrays", function() { var array = [1, 2]; array.unshift(3); expect(array).toEqual([3,1,2]); var shiftedValue = array.shift(); expect(shiftedValue).toEqual(3); expect(array).toEqual([1,2]); }); });
import logger from 'kolibri.lib.logging'; import store from 'kolibri.coreVue.vuex.store'; import Lockr from 'lockr'; import urls from 'kolibri.urls'; import mime from 'rest/interceptor/mime'; import interceptor from 'rest/interceptor'; import baseClient from './core-app/baseClient'; import { SIGNED_OUT_DUE_TO_INACTIVITY } from './constants'; import errorCodes from './disconnectionErrorCodes'; import { createTryingToReconnectSnackbar, createDisconnectedSnackbar, createReconnectedSnackbar, } from './disconnection'; const logging = logger.getLogger(__filename); const reconnectMultiplier = 2; const maxReconnectTime = 600; const timeoutReconnectTime = 60; const minReconnectTime = 5; export class HeartBeat { constructor(delay = 240000) { if (typeof delay !== 'number') { throw new ReferenceError('The delay must be a number in milliseconds'); } this.delay = delay; // Do this to have a consistent callback that has 'this' properly bound // but can be repeatedly referenced to add and remove listeners. this.setActive = this.setActive.bind(this); this.beat = this.beat.bind(this); this.setInactive(); this.enabled = false; } start() { logging.debug('Starting heartbeat'); this.enabled = true; this.setActivityListeners(); // No need to start it straight away, can wait. this.beat(); } stop() { logging.debug('Stopping heartbeat'); this.enabled = false; this.clearActivityListeners(); if (this.timerId) { clearTimeout(this.timerId); } } setActivityListeners() { this.events.forEach(event => { document.addEventListener(event, this.setActive, { capture: true, passive: true }); }); } clearActivityListeners() { this.events.forEach(event => { document.removeEventListener(event, this.setActive, { capture: true, passive: true }); }); } setActive() { if (this.active !== true) { this.active = true; this.clearActivityListeners(); } } setInactive() { this.active = false; } wait() { const { reconnectTime } = store.getters; // If we are currently engaged in exponential backoff in trying to reconnect to the server // use the current reconnect time preferentially instead of the standard delay. // The reconnect time is stored in seconds, so multiply by 1000 to give the milliseconds. this.timerId = setTimeout(this.beat, reconnectTime * 1000 || this.delay); return this.timerId; } /* * Method to check the current session endpoint, and record whether the user was active * in the last interval. Used both for keeping the session alive at regular intervals * and also for checking whether connection has been reestablished when it has previously * been lost. * @return {Promise} promise that resolves when the endpoint check is complete. */ checkSession() { const { currentUserId, connected, reconnectTime } = store.getters; // Record the current user id to check if a different one is returned by the server. // Don't use the regular client, to avoid circular imports, and to use different custom // interceptors on the request specific to the behaviour here. let client = baseClient.wrap(mime, { mime: 'application/json' }); if (!connected) { // If not currently connected to the server, flag that we are currently trying to reconnect. createTryingToReconnectSnackbar(store); client = client.wrap( interceptor({ // Define an interceptor to monitor the response that gets returned. response: function(response) { // If the response does not have one of the disconnect error codes // then we have reconnected. if (!errorCodes.includes(response.status.code)) { // Not one of our 'disconnected' status codes, so we are connected again // Set connected and return the response here to prevent any further processing. heartbeat.setConnected(); return response; } // If we have got here, then the error code meant that the server is still not reachable // set the snackbar to disconnected. // See what the previous reconnect interval was. const reconnect = reconnectTime; // Set a new reconnect interval. store.commit( 'CORE_SET_RECONNECT_TIME', // Multiply the previous interval by our multiplier, but max out at a high interval. Math.min(reconnectMultiplier * reconnect, maxReconnectTime) ); createDisconnectedSnackbar(store, heartbeat.beat); return response; }, }) ); } return client({ params: { // Only send active when both connected and activity has been registered. // Do this to prevent a user logging activity cascade on the server side. active: connected && this.active, }, path: this.sessionUrl('current'), }) .then(response => { // Check the user id in the response if (response.entity.user_id !== currentUserId) { // If it is different, then our user has been signed out. this.signOutDueToInactivity(); } }) .catch(error => { // An error occurred. logging.error('Session polling failed, with error: ', error); if (errorCodes.includes(error.status.code)) { // We had an error that indicates that we are disconnected, so start to monitor // the disconnection. this.monitorDisconnect(error.status.code); } }); } /* * Method to begin monitoring the disconnected state from the server. * This method can be called repeatedly as it will only initiate anything * if the vuex state does not already indicate disconnection. */ monitorDisconnect(code = 0) { if (store.getters.connected) { // We have not already registered that we have been disconnected store.commit('CORE_SET_CONNECTED', false); let reconnectionTime; if (code === 502) { // Do special behaviour in the case that this is a network timeout. reconnectionTime = timeoutReconnectTime; } else { reconnectionTime = minReconnectTime; } store.commit('CORE_SET_RECONNECT_TIME', reconnectionTime); createDisconnectedSnackbar(store, this.beat); this.wait(); } } /* * Method to reset the vuex state to the connected state and restart server polling * on the regular heartbeat delay. */ setConnected() { store.commit('CORE_SET_CONNECTED', true); store.commit('CORE_SET_RECONNECT_TIME', null); createReconnectedSnackbar(store); this.wait(); } /* * Method to signout when automatic signout has been detected. */ signOutDueToInactivity() { // Store that this sign out was for inactivity in local storage. Lockr.set(SIGNED_OUT_DUE_TO_INACTIVITY, true); // Just navigate to the root URL and let the server sort out where // we should be. window.location = window.origin; } sessionUrl(id) { return urls['kolibri:core:session-detail'](id); } beat() { if (this.active) { this.setActivityListeners(); } else { logging.debug('No user activity'); } if (this.timerId) { clearTimeout(this.timerId); } return this.checkSession().finally(() => { if (this.enabled) { this.setInactive(); this.wait(); } }); } get events() { return [ 'mousemove', 'mousedown', 'keypress', 'DOMMouseScroll', 'mousewheel', 'touchmove', 'MSPointerMove', ]; } } const heartbeat = new HeartBeat(); export default heartbeat;
import React from 'react'; import Authenticator from '../Authenticator'; import ShowHidePassword from '../../ShowHidePassword'; import {generateFormChangeHandler} from '../../../utils/form-handler'; import t from '../../../i18n/locale-keys'; class BankIdMethod extends React.PureComponent { constructor(props) { super(props); generateFormChangeHandler(this, { personalId: '' }); } finishEnroll() { const {form} = this.state; if (form.personalId !== '') { return this.props.doEnrollWithBeginProcess(form) .then((response) => { if (response.status !== 'FAILED') { return Promise.resolve(response); } else { throw response.msg; } }); } else { return Promise.reject(t.bankIdNoId()); } }; authenticationInfoChanged() { return this.state.dataDirty; } render() { return ( <Authenticator description={t.bankIdMethodDescription()} {...this.props} > <ShowHidePassword disabled={this.props.readonlyMode} id="PersonalId_Input_Field" name="personalId" onChange={this.handleChange} placeholder={t.bankIdId()} value={this.state.form.personalId} /> </Authenticator> ); } } export default BankIdMethod;
module.exports = { loadingLabel: function () { //Here we add a label to let the user know we are loading everything //This is the "Loading" phrase in pixel art //You can just as easily change it for your own art :) this.loading = game.add.sprite(game.world.centerX, game.world.centerY - 20, 'loading'); this.loading.anchor.setTo(0.5, 0.5); //This is the bright blue bar that is hidden by the dark bar this.barBg = game.add.sprite(game.world.centerX, game.world.centerY + 40, 'load_progress_bar'); this.barBg.anchor.setTo(0.5, 0.5); //This bar will get cropped by the setPreloadSprite function as the game loads! this.bar = game.add.sprite(game.world.centerX - 192, game.world.centerY + 40, 'load_progress_bar_dark'); this.bar.anchor.setTo(0, 0.5); game.load.setPreloadSprite(this.bar); }, preload: function () { this.loadingLabel(); //Add here all the assets that you need to game.load game.load.spritesheet('tiles', 'assets/faux_tiles.png', 16,16); game.load.text('level-1', 'assets/levels/1.txt'); game.load.atlasJSONHash('tiles', 'assets/tiles.png', 'assets/tiles.json'); game.load.image('footman', 'assets/td-footman.png'); game.load.image('turret_base', 'assets/turret_base.png'); game.load.image('turret_top', 'assets/turret_top.png'); game.load.image('clear', 'assets/tracker.png'); game.load.image('shot', 'assets/shot.png'); }, create: function () { game.state.start('menu'); } };
const Color = require('color'); /** * Check param format and throw some errors */ function checkParam(array, n) { // Seriously? Anyone this dumb? if (array.length < 2) { throw new Error('Color array length must > 1'); } // Read the documentation OMG! Of course no frac at the end! if (array[array.length - 1].frac) { throw new Error('The last element in the color array should not have a frac field'); } // You need to see a doctor, like, right now if (n <= array.length) { throw new Error('The number of generated colors should >= the number of color stops'); } // if full option mode, sum should be 1 if (typeof array[0] !== 'string') { const fracSum = array .slice(0, array.length - 1) .reduce((a, b) => a + b.frac, 0); if (fracSum < 0.99) { throw new Error('The sum of the fracs should = 1'); } } return typeof array[0] !== 'string'; } /** * Explainations: * o -> stop color for gradient * * -> generated color * * o * * * | o * * * * | o * * o -> generated color list in char version * 4 5 4 -> assigned number of colors need to be generated * * The last section, the end color should be considered in the generated colors * * @returns {Array} array of colors in Color(pkg) format, need toString() call */ function createGradient(colorList, assignList) { let result = []; assignList.forEach((num, index) => { const isLastElement = index === assignList.length - 1; const list = []; // get end point color const start = colorList[index]; const end = colorList[index + 1]; // if last element, end color should be in the list, // so the num = num - 1 if (isLastElement) { num -= 1; // eslint-disable-line } const deltaR = (end.red() - start.red()) / num; const deltaG = (end.green() - start.green()) / num; const deltaB = (end.blue() - start.blue()) / num; // generate num colors for (let i = 0; i < num; i += 1) { const R = start.red() + (i * deltaR); const G = start.green() + (i * deltaG); const B = start.blue() + (i * deltaB); list.push(Color.rgb(R, G, B)); } // if last element, end this list with the last color if (isLastElement) { list.push(end); } result = result.concat(list); }); return result; } /** * Calculate and optimize the number of each color period * * Sometimes frac * N might be a fraction * So we use this algorithm: * * 1. Split the number into 2 parts, each part fits in an array: * [2, 4, 1, 5] -> int array * [0.2, 0.5, 0.9, 0.3] -> decimal array * * The left number should be: * left = N - sum(intArray) * * 2. Sort the decimal array from large to small, assign left to * the corresponding element in intArray one by one * until left === 0 * * 3. There goes your final array! * * @returns {Array} array of optimized color numbers */ function assignNumbers(fracList, n) { const intArray = []; const decimalArray = []; // assign int part fracList.forEach((frac, index) => { const real = frac * n; const intPart = Math.floor(real); const decimalPart = real - intPart; intArray.push(intPart); decimalArray.push({ value: decimalPart, index, }); }); // how many left ? const left = n - intArray.reduce((a, b) => a + b, 0); // sort O -> o decimalArray.sort((a, b) => b.value - a.value); // assign the left number regard to the decimal part's value // until nothing left for (let i = 0; i < left; i += 1) { const targetIndex = decimalArray[i].index; intArray[targetIndex] += 1; } return intArray; } /** * Generate n colors with given color stops * * @param {Array} colorArray * @param {Number} n number of colors that need to generate * @returns {Array} array of generated colors in rgb mode */ function gradient(colorArray, n) { const isFullOption = checkParam(colorArray, n); // init 2 arrays for algorithm const colorList = []; const fracList = []; // result array for storing data let resultArray = []; // simple array of color string if (!isFullOption) { const frac = 1 / (colorArray.length - 1); colorArray.forEach((colorString, index) => { if (index !== (colorArray.length - 1)) { colorList.push(Color(colorString)); fracList.push(frac); } else { colorList.push(Color(colorString)); } }); } else { colorArray.forEach((obj, index) => { if (index !== (colorArray.length - 1)) { colorList.push(Color(obj.color)); fracList.push(obj.frac); } else if (obj.color) { // the last item could be like { color: #ffffff } colorList.push(Color(obj.color)); } else { // and it could also be like '#ffffff' colorList.push(Color(obj)); } }); } const assignList = assignNumbers(fracList, n); resultArray = createGradient(colorList, assignList); // convert colors to string version resultArray = resultArray.map(c => c.rgb().toString()); return resultArray; } module.exports = gradient;
'use strict'; define(['app'], function(app) { app.register.factory('regionModel', function () { return { region: 'USA' }; }); });
var Stappo = require("../dist/stappo.bundle"); var stappo; describe("Stappo Generic (Bundle)", function () { beforeEach(function(){ stappo = new Stappo(); }); it("should notify only active listeners", function () { const listener1 = stappo.listen( s => { expect(s.a).toBe(1); }); const listener2 = stappo.listen( s => { throw "Shouldn't be called"; }); stappo.unlisten(listener2); stappo.update(() => ({a:1})); stappo.unlisten(listener1); }); it("should merge simple state and notify", function () { const listener = stappo.listen( s => { expect(s.a).toBe(1); }); stappo.update(() => ({a:1})); stappo.unlisten(listener); }); it("should merge modify simple state using previous state and notify", function () { stappo.update(() => ({a:1})); const listener = stappo.listen( s => { expect(s.a).toBe(2); }); stappo.update((s) => ({a:s.a+1})); stappo.unlisten(listener); }); it("should return current state", function () { expect(stappo.get()).toEqual({}) stappo.update(() => ({a:1})) expect(stappo.get().a).toBe(1) }); it("should have deeply immutable state", function () { const listener = stappo.listen( s => { s.a.foo = 2; s.b.bar[0] = 100; expect(s.a.foo).toBe(1); expect(s.b.bar[0]).toBe(0); }); stappo.update( () => ({ a: { foo: 1}, b : {bar: [0,1,2]} })); stappo.unlisten(listener); }); });
import React, { PropTypes } from 'react' import { Modal } from 'react-bootstrap' import { TextInput, NumberInput } from '../forms/controls' class VehicleDialog extends React.Component { constructor(props, context) { super(props, context) this.onChange = this.onChange.bind(this) this.onChangeMileage = this.onChangeMileage.bind(this) this.create = this.create.bind(this) if (props.vehicle) { this.state = { ...props.vehicle } } else { this.state = { year: '', make: '', model: '', color: '', baseMileage: 0, } } } onChange(event) { const field = event.target.name this.setState({ ...this.state, [field]: event.target.value, }) } onChangeMileage(event) { this.setState({ ...this.state, baseMileage: parseInt(event.target.value), }) } create(event) { event.preventDefault() const { onCreate } = this.props onCreate(this.state) } render() { const { show, onClose } = this.props const { year, make, model, color, baseMileage } = this.state return ( <Modal show={show} onHide={onClose}> <form onSubmit={this.create}> <Modal.Header> <Modal.Title>Create Vehicle</Modal.Title> </Modal.Header> <Modal.Body> <TextInput name="year" label="Year" value={year} onChange={this.onChange} /> <TextInput name="make" label="Make" value={make} onChange={this.onChange} /> <TextInput name="model" label="Model" value={model} onChange={this.onChange} /> <TextInput name="color" label="Color" value={color} onChange={this.onChange} /> <NumberInput name="baseMileage" label="Mileage" value={baseMileage} onChange={this.onChangeMileage} /> </Modal.Body> <Modal.Footer> <button type="button" className="btn btn-default" onClick={onClose}> Close </button> <button type="submit" className="btn btn-primary"> Create </button> </Modal.Footer> </form> </Modal> ) } } VehicleDialog.propTypes = { vehicle: PropTypes.object, show: PropTypes.bool, onClose: PropTypes.func, onCreate: PropTypes.func, } export default VehicleDialog
/* jshint globalstrict: true */ "use strict"; function $CompileProvider($provide) { var hasDirectives = {}; var PREFIX_REGEXP = /(x[\:\-_]|data[\:\-_])/i; var BOOLEAN_ATTRS = { multiple: true, selected: true, checked: true, disabled: true, readOnly: true, required: true, open: true }; var BOOLEAN_ELEMENTS = { INPUT: true, SELECT: true, OPTION: true, TEXTAREA: true, BUTTON: true, FORM: true, DETAILS: true }; this.directive = function(name, directiveFactory) { if(_.isString(name)) { // make sure the directive name is valid if(name === "hasOwnProperty") { throw "'hasOwnProperty' is not a valid name for directive"; } if(!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + "Directive", ["$injector", function($injector) { var factories = hasDirectives[name]; return _.map(factories, function(factory) { var directive = $injector.invoke(factory); // give a default restrict if not exit directive.restrict = directive.restrict || "A"; return directive; }); }]); } hasDirectives[name].push(directiveFactory); } else { // passing in an object for multiple directives creating // when iterating on object, the first parameter is value, second: key _.forEach(name, function(directiveFactory, name) { this.directive(name, directiveFactory); }, this); } }; this.$get = ["$injector", "$rootScope", function($injector, $rootScope) { function Attribute(element) { this.$$element = element; // normalized name -> original name this.$attr = {}; } // define the $set on attribute object // the fourth attrName is given for explicitly designate the denormalized attr name Attribute.prototype.$set = function(key, value, writeAttr, attrName) { this[key] = value; // special processing for the boolean attribute // TODO: why only testing on the first child if (isBooleanAttribute(this.$$element[0], key)) { this.$$element.prop(key, value); } if(!attrName) { if(this.$attr[key]) { attrName = this.$attr[key]; } else { attrName = this.$attr[key] = _.snakeCase(key); } } else { // when given the attrName this.$attr[key] = attrName; } // flush the change to the dom element, the key is the normalized name // only when the writeAttr is false, the write will not happen if(writeAttr !== false) { this.$$element.attr(attrName, value); } // invoke the registered observers if(this.$$observers) { _.forEach(this.$$observers[key], function(observer) { try { // call the observer with the latest value observer(value); } catch (e) { console.error(e); } }); } }; // observe related // the observers will only be invoked through $set Attribute.prototype.$observe = function(key, fn) { var self = this; this.$$observers = this.$$observers || {}; this.$$observers[key] = this.$$observers[key] || []; this.$$observers[key].push(fn); // call all the observers once in the next $digest every time the $observe is called $rootScope.$evalAsync(function() { fn(self[key]); }); return fn; }; Attribute.prototype.$addClass = function(classValue) { this.$$element.addClass(classValue); }; Attribute.prototype.$removeClass = function(classValue) { this.$$element.removeClass(classValue); }; Attribute.prototype.$updateClass = function(newClassVal, oldClassVal) { var newClasses = newClassVal.split(/\s+/); var oldClasses = oldClassVal.split(/\s+/); var addedClasses = _.difference(newClasses, oldClasses); var removedClasses = _.difference(oldClasses, newClasses); if (addedClasses.length) { this.$addClass(addedClasses.join(" ")); } if (removedClasses.length) { this.$removeClass(removedClasses.join(" ")); } }; function compile($compileNodes) { return compileNodes($compileNodes); } function compileNodes($compileNodes) { _.forEach($compileNodes, function(node) { // prepare the attrs var attrs = new Attribute($(node)); var directives = collectDirectives(node, attrs); applyDirectivesToNode(directives, node, attrs); // apply to children recursively if(node.childNodes && node.childNodes.length) { compileNodes(node.childNodes); } }); } function applyDirectivesToNode(directives, compileNode, attrs) { var $compileNode = $(compileNode); _.forEach(directives, function(directive) { if(directive.$$start) { $compileNode = groupScan(compileNode, directive.$$start, directive.$$end); } if(directive.compile) { // invoke the defined compile function here directive.compile($compileNode, attrs); } }); } function groupScan(node, startAttr, endAttr) { var nodes = []; if(startAttr && node && node.hasAttribute(startAttr)) { var depth = 0; do { if (node.nodeType === Node.ELEMENT_NODE) { if (node.hasAttribute(startAttr)) { depth++; } else if (node.hasAttribute(endAttr)) { depth--; } } nodes.push(node); node = node.nextSibling; } while (depth > 0); } else { nodes.push(node); } return $(nodes); } function collectDirectives(node, attrs) { var directives = []; var match; if(node.nodeType === Node.ELEMENT_NODE) { // for collecting the node name if any var normalizedNodeName = directiveNormalize(nodeName(node).toLowerCase()); addDirective(directives, normalizedNodeName, "E"); // for collecting the node's attributes if any _.forEach(node.attributes, function(attribute) { var attrStartName, attrEndName; var name = attribute.name; var normalizedAttributeName = directiveNormalize(name.toLowerCase()); // deal with the possible ng-attr prefix if(/^ngAttr[A-Z]/.test(normalizedAttributeName)) { // denormalize it name = _.snakeCase( normalizedAttributeName[6].toLowerCase() + normalizedAttributeName.substring(7), // remove "ng-attr" "-" ); // normalize again normalizedAttributeName = directiveNormalize(name.toLowerCase()); } // save the normalized -> original entry attrs.$attr[normalizedAttributeName] = name; // deal with the start/end suffix if(/Start$/.test(normalizedAttributeName)) { attrStartName = name; attrEndName = name.substring(0, name.length - 5) + "end"; name = name.substring(0, name.length - 6); // remove the trailing "-start" } normalizedAttributeName = directiveNormalize(name.toLowerCase()); addDirective(directives, normalizedAttributeName, "A", attrStartName, attrEndName); // collecting the attrs into object attrs[normalizedAttributeName] = attribute.value.trim(); // process the boolean attribute if(isBooleanAttribute(node, normalizedAttributeName)) { attrs[normalizedAttributeName] = true; } }); // for collecting the node's classes if any var className = node.className; if(_.isString(className) && !_.isEmpty(className)) { while ((match = /([\d\w\-_]+)(?:\:([^;]+))?;?/.exec(className))) { var normalizedClassName = directiveNormalize(match[1]); if (addDirective(directives, normalizedClassName, "C")) { attrs[normalizedClassName] = match[2] ? match[2].trim() : undefined; } className = className.substr(match.index + match[0].length); } } _.forEach(node.classList, function(cls) { var normalizedClassName = directiveNormalize(cls); if(addDirective(directives, normalizedClassName, "C")) { // put the attribute into attrs as placeholder only when matched attrs[normalizedClassName] = undefined; } }); } else if(node.nodeType === Node.COMMENT_NODE) { match = /^\s*directive\:\s*([\d\w\-_]+)\s*(.*)$/.exec(node.nodeValue); if (match) { var normalizedName = directiveNormalize(match[1]); if (addDirective(directives, normalizedName, "M")) { attrs[normalizedName] = match[2] ? match[2].trim() : undefined; } } } return directives; } function isBooleanAttribute(node, attrName) { return BOOLEAN_ATTRS[attrName] && BOOLEAN_ELEMENTS[node.nodeName]; } function directiveNormalize(name) { return _.camelCase(name.replace(PREFIX_REGEXP, "")); } // element: a raw DOM node or a jQuery-wrapped one function nodeName(element) { return element.nodeName ? element.nodeName : element[0].nodeName; } function addDirective(directives, name, mode, attrStartName, attrEndName) { var match; // seek the factory by directive's name if(hasDirectives.hasOwnProperty(name)) { // get the directive declaration for the "restrict" value var foundDirective = $injector.get(name + "Directive"); var applicableDirectives = _.filter(foundDirective, function(dir) { return dir.restrict.indexOf(mode) !== -1; }); _.forEach(applicableDirectives, function(directive) { if(attrStartName) { directive = _.create(directive, { $$start: attrStartName, $$end: attrEndName }); } directives.push(directive); // mark match as matched match = directive; }); // TODO: why using "apply" to concat the returned array to directives // directly modify the passed in directives, no need to return explicitly // not used now, but need to know why ! // directives.push.apply(directives, applicableDirectives); return match; } } // expose the compile function for current provider return compile; }]; $CompileProvider.$inject = ["$provide"]; }
'use strict'; app.controller('PlayerAdminController', ['$scope', '$rootScope', '$location', 'Event', 'Player', 'SYNC_EVENTS', function ($scope, $rootScope, $location, Event, Player, SYNC_EVENTS) { $scope.gridApi = null; $scope.grid_opts = { enableFiltering: false, enableSorting: false, enableGridMenu: false, enableColumnMenus: false, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, rowHeight: 30, columnDefs: [ {name: 'ID', field: 'id', width: 100, enableCellEdit: false}, {name: 'Name', field: 'name'}, {name: 'Token', field: 'token', enableCellEdit: false} ], onRegisterApi: function(gridApi){ $scope.gridApi = gridApi; gridApi.rowEdit.on.saveRow($scope, $scope.save_rows); } }; $scope.getTableHeight = function() { var rowHeight = 30; // your row height var headerHeight = 30; // your header height return { height: ($scope.grid_opts.data.length * rowHeight + headerHeight) + "px" }; }; $scope.save_rows = function(row) { var promise = new Promise(function(resolve, reject) { Player.edit_player(row.id, row.name); resolve(1); }); $scope.gridApi.rowEdit.setSavePromise(row, promise); return promise; }; $scope.add_row = function() { Player.add_player(Event.get_selected_event().id); }; function refresh_grid() { if($scope.gridApi == null) return; $scope.gridApi.core.queueRefresh(); } function refresh_players() { $scope.grid_opts.data = Player.get_players(Event.get_selected_event().id); $scope.grid_opts.minRowsToShow = $scope.grid_opts.data.length; $scope.grid_opts.virtualizationThreshold = $scope.grid_opts.data.length; refresh_grid(); } function init() { refresh_players(); $rootScope.$on(SYNC_EVENTS.playersRefresh, function(event, args) { refresh_players(); }); $rootScope.$on(SYNC_EVENTS.currentEventChange, function(event, args) { refresh_players(); }); } init(); } ]);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _class, _class2, _temp; // Coomponents // Utilities var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _radium = require('radium'); var _radium2 = _interopRequireDefault(_radium); var _Paper = require('../paper/Paper'); var _Paper2 = _interopRequireDefault(_Paper); var _BaseSwitch = require('./BaseSwitch'); var _BaseSwitch2 = _interopRequireDefault(_BaseSwitch); var _TouchRipple = require('../ripple/TouchRipple'); var _TouchRipple2 = _interopRequireDefault(_TouchRipple); var _View = require('../view/View'); var _View2 = _interopRequireDefault(_View); var _ = require('../../'); var _colors = require('../../utils/colors'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Toggle = (0, _radium2.default)(_class = (0, _BaseSwitch2.default)(_class = (_temp = _class2 = function (_Component) { _inherits(Toggle, _Component); function Toggle() { _classCallCheck(this, Toggle); return _possibleConstructorReturn(this, (Toggle.__proto__ || Object.getPrototypeOf(Toggle)).apply(this, arguments)); } _createClass(Toggle, [{ key: 'render', value: function render() { var _props = this.props, size = _props.size, outlineColor = _props.outlineColor, disabledColor = _props.disabledColor, toggleOnColor = _props.toggleOnColor, toggleOffColor = _props.toggleOffColor, getValue = _props.getValue, isDisabled = _props.isDisabled, toggled = _props.toggled, labelPosition = _props.labelPosition; var isToggled = toggled ? toggled : getValue(); // Apply disabled color if neccesary toggleOnColor = isDisabled ? disabledColor : toggleOnColor; toggleOffColor = isDisabled ? disabledColor : toggleOffColor; return _react2.default.createElement( _View2.default, { style: [styles.container, { width: size, height: size, justifyContent: labelPosition === 'left' ? 'flex-end' : 'flex-start' }] }, _react2.default.createElement( 'div', { style: { position: 'relative', width: size } }, _react2.default.createElement(_Paper2.default, { style: styles.track, innerStyle: { borderRadius: 10, backgroundColor: isToggled ? toggleOnColor : toggleOffColor } }), _react2.default.createElement( _Paper2.default, { style: [styles.thumb, isToggled && styles.toggled], innerStyle: { borderRadius: '50%', backgroundColor: isToggled ? toggleOnColor : toggleOffColor } }, _react2.default.createElement(_TouchRipple2.default, { ref: 'ripple', handleMouseDown: function handleMouseDown() {}, overflowHidden: false, rippleColor: toggleOnColor, speed: 150 }) ) ) ); } }]); return Toggle; }(_react.Component), _class2.propTypes = { toggleOnColor: _propTypes2.default.string, toggleOffColor: _propTypes2.default.string, disabledColor: _propTypes2.default.string, size: _propTypes2.default.number.isRequired }, _class2.defaultProps = { disabledColor: _colors.colors.grey400, toggleOnColor: _colors.colors.cyan500, toggleOffColor: _colors.colors.grey50 }, _class2.options = { type: 'toggle' }, _temp)) || _class) || _class; exports.default = Toggle; var styles = { container: { alignItems: 'center', position: 'relative' }, track: { width: '100%', height: 10, borderRadius: 10 }, thumb: { bottom: (18 / 2 - 10 / 2) * -1, // Thumb height / 2 - Track height /2 left: 0, height: 18, width: 18, borderRadius: '50%', position: 'absolute', transformOrigin: '50% 50%', transition: 'left 200ms ease-out, backgroundColor 200ms ease-out' }, toggled: { left: 'calc(100% - 18px)' } };
<div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.7&appId=1128568017194428"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script>
define(function () { 'use strict'; function _isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function _isString(s) { return typeof(s) === 'string'; } function _isArray(arr) { return arr instanceof Array; } function _isObject(arr) { return arr instanceof Object; } function _isArrayOfStrings(arr) { if (! _isArray(arr)) { return false; } if (arr.length === 0) { return false; } for (var i = 0; i < arr.length; i++) { if (! _isString(arr[i])) { return false; } } return true; } var VariantConfigError = function (message) { this.name = 'VariantConfigError'; this.message = message; } VariantConfigError.prototype = new Error(); var Variants = function () { this._conditionTypes = {}; this.registerConditionType(AlwaysCondition); this.registerConditionType(NeverCondition); this.registerConditionType(UsersCondition); this.registerConditionType(GroupsCondition); this.registerConditionType(RandomCondition); this.registerConditionType(RandomModCondition); this.registerConditionType(UsernameModCondition); this.registerConditionType(GoogleExperimentsCondition); } Variants.prototype = { registerConditionType: function (conditionType) { this._conditionTypes[conditionType.prototype.type] = conditionType; }, getMods: function (variantsConfig, context) { context = context || {}; var variantsInUrl = this._getVariantsFromUrl(context); var allMods = {}; if (! _isArray(variantsConfig)) { throw new VariantConfigError('variants should be a list'); } for (var i = 0; i < variantsConfig.length; i++) { var mods = this._getModsForVariant(variantsConfig[i], context, variantsInUrl); if (mods) { for (var key in mods) { allMods[key] = mods[key]; } } } return allMods; }, _getModsForVariant: function (variantConfig, context, variantsInUrl) { // Sanity checking if (! _isString(variantConfig.id)) { throw new VariantConfigError('Every variant must have an string id'); } if (! _isArray(variantConfig.conditions) || variantConfig.conditions.length == 0) { throw new VariantConfigError('A variant must have conditions'); } if (! _isObject(variantConfig.mods)) { throw new VariantConfigError('A variant must have mods'); } var id = variantConfig.id; var allowsUrlOverrides = variantConfig.allowUrlOverrides === true; var urlOverride = allowsUrlOverrides && variantsInUrl.indexOf(id) !== -1; var conditions = this._parseConditions(variantConfig.conditions); var conditionOperatorAll = this._parseConditionalOperator(variantConfig); if (urlOverride || this._testConditions(conditions, conditionOperatorAll, context)) { return variantConfig.mods; } else { return null; } }, _testConditions: function (conditions, conditionOperatorAll, context) { for (var i = 0; i < conditions.length; i++) { var conditionIsTrue = conditions[i].test(context); if (conditionOperatorAll && ! conditionIsTrue) { return false; } if (! conditionOperatorAll && conditionIsTrue) { return true; } } return conditionOperatorAll; }, _getVariantsFromUrl: function(context) { var param = this._getUrlParam(context, 'variants'); if (param) { return param.split(','); } else { return []; } }, _getUrlParam: function(context, name) { var search; if (context.search) { search = context.search; } else if (document.location.search) { search = document.location.search.substring(1); } if (search) { var params = search.split("&"); for (var i = 0; i < params.length; i++) { var parts = params[i].split('='); if (parts[0] == name) { return parts[1]; } } } return null; }, _parseConditionalOperator: function(variantConfig) { if (variantConfig.conditionalOperator) { if (! _isString(variantConfig.conditionalOperator)) { throw new VariantConfigError('conditionalOperator should be AND or OR'); } var conditionalOperator = variantConfig.conditionalOperator.toLowerCase(); if (conditionalOperator === 'and') { return true; } else if (conditionalOperator === 'or') { return false; } else { throw new VariantConfigError('conditionalOperator should be AND or OR'); } } return false; }, _parseConditions: function (conditionConfigs) { var ret = [] for (var i = 0; i < conditionConfigs.length; i++) { ret.push(this._parseCondition(conditionConfigs[i])); } return ret; }, _parseCondition: function (conditionConfig) { if (conditionConfig.type == null) { throw new VariantConfigError('Every condition must have a type'); } else if (! _isString(conditionConfig.type)) { throw new VariantConfigError('Condition type must be a string'); } else if (! this._conditionTypes.hasOwnProperty(conditionConfig.type)) { throw new VariantConfigError('Unknown condition type: ' + conditionConfig.type); } var conditionClass = this._conditionTypes[conditionConfig.type]; return new conditionClass(conditionConfig); }, } var AlwaysCondition = function (config) { } AlwaysCondition.prototype = { type: 'ALWAYS', test: function (context) { return true; } } var NeverCondition = function (config) { } NeverCondition.prototype = { type: 'NEVER', test: function (context) { return false; } } var UsersCondition = function (config) { if (! _isArrayOfStrings(config.values)) { throw new VariantConfigError("USERS requires values to be a list of usernames"); } this.values = config.values; } UsersCondition.prototype = { type: 'USERS', test: function (context) { return context.username && this.values.indexOf(context.username) !== -1; } } var GroupsCondition = function (config) { if (! _isArrayOfStrings(config.values)) { throw new VariantConfigError("GROUPS requires groups to be a list of groups"); } this.values = config.values; } GroupsCondition.prototype = { type: 'GROUPS', test: function (context) { if (context.groups) { for (var i = 0; i < context.groups.length; i++) { if (this.values.indexOf(context.groups[i]) !== -1) { return true; } } } return false; } } var RandomCondition = function (config) { if (! _isNumber(config.value)) { throw new VariantConfigError("RANDOM requires value to be a number"); } if (config.value < 0 || config.value > 1) { throw new VariantConfigError("RANDOM requires value to be a number between 0 and 1"); } this.value = config.value; } RandomCondition.prototype = { type: 'RANDOM', test: function (context) { return Math.random() < this.value; } } var RandomModCondition = function (config) { if (! _isNumber(config.from) || ! _isNumber(config.to)) { throw new VariantConfigError("RANDOM_MOD requires from and to to be numbers"); } if (config.from < 0 || config.to > 100) { throw new VariantConfigError("RANDOM_MOD requires a range between 0 and 100"); } if (config.from >= config.to) { throw new VariantConfigError("RANDOM_MOD cannot have from >= to"); } this.from = config.from; this.to = config.to; } RandomModCondition.prototype = { type: 'RANDOM_MOD', test: function (context) { // We need to use the same random value for all conditions, so store it on the context. if (! context._RandomModCondition_Value) { context._RandomModCondition_Value = Math.floor(Math.random()*100); } return context._RandomModCondition_Value >= this.from && context._RandomModCondition_Value < this.to; } } var UsernameModCondition = function (config) { if (! _isNumber(config.from) || ! _isNumber(config.to)) { throw new VariantConfigError("RANDOM_MOD requires from and to to be numbers"); } if (config.from < 0 || config.to > 100) { throw new VariantConfigError("RANDOM_MOD requires a range between 0 and 100"); } if (config.from >= config.to) { throw new VariantConfigError("RANDOM_MOD cannot have from >= to"); } this.from = config.from; this.to = config.to; } UsernameModCondition.prototype = { type: 'USERNAME_MOD', test: function (context) { if (context.username) { // Hack to inject fake hash function in context for testing var hashFunction = context._hash || this._hash; var value = hashFunction(context.username); return value >= this.from && value < this.to; } else { return false; } }, _hash: function (username) { // Java hash algorithm. var hash, char = 0; for (var i = 0; i < username.length; i++) { char = username.charCodeAt(i); /* jshint -W016 */ hash = ((hash << 5) - hash) + char; hash = hash & hash; /* jshint +W016 */ } return hash%100; }, } var GoogleExperimentsCondition = function (config) { if (! _isNumber(config.variation) || Math.floor(config.variation) !== config.variation || config.variation < 0) { throw new VariantConfigError("GOOGLE_EXPERIMENTS requires integer variation"); } this.variation = config.variation; } GoogleExperimentsCondition.prototype = { type: 'GOOGLE_EXPERIMENTS', test: function (context) { if (window.cxApi) { var variation = window.cxApi.chooseVariation(); return variation === this.variation; } else { return false; } }, } return new Variants(); });
import PropTypes from 'prop-types'; export class Filter { static propTypes = { name: PropTypes.string.isRequired, label: PropTypes.string.isRequired, type: PropTypes.func, options: PropTypes.object, defaultOperator: PropTypes.string, defaultValue: PropTypes.any, }; constructor(props) { PropTypes.checkPropTypes(Filter.propTypes, props, 'property', 'Filter'); for (let key in props) { this[key] = props[key]; } } static create(props) { return new Filter(props); } }
#!/usr/bin/env node var vows = require('vows'), assert = require('assert'), path = require('path'), fs = require('fs'), spawn = require('child_process').spawn, out = '', error = '', basename = path.basename(__filename), input = [ 'test-in/input-dir/*', 'test-in/input-dir/subdir/*', 'test-in/input-dir/subdir/subdir/*', 'test-in/input-dir/subdir/subdir/subdir/*' ], outputDir = 'test-out/' + basename, testOutPath = 'test-in/input-dir/subdir/subdir/subdir/largefile2.txt'; /** * Test suite */ vows.describe(basename).addBatch({ "chdir": { topic: function () { process.chdir(__dirname); return __dirname; }, "cwd is __dirname": function (dir) { assert.strictEqual(process.cwd(), dir); } }, "spawn ../bin.js": { topic: function () { var child = spawn(process.execPath, ['../bin.js'].concat(input).concat(['-o', outputDir])); child.stdout.on('data', function (data) { out += data.toString(); }); child.stderr.on('data', function (data) { error += data.toString(); }); child.on('exit', function (code) { this.callback(null, child, code); }.bind(this)); }, "on exit": { "code is 0": function (child, code) { assert.strictEqual(code, 0); }, "stderr is empty": function (child, code) { assert.isString(error); assert.isEmpty(error); }, "stdout is not empty": function (child, code) { assert.isString(out); assert.isNotEmpty(out); }, "stdout contains 'Completed successfully.'": function (code) { assert.strictEqual(out.indexOf('Completed successfully.') > -1, true); }, "stdout 'files: #' matches": { topic: function () { return out.match(/Completed successfully.[\S\s]+files: ([0-9]+)[\S\s]+elapsed\(ms\)\: [0-9]+[\S\s]+$/); }, "is not null": function (matches) { assert.isNotNull(matches); }, "[1] is not empty": function (matches) { assert.isNotEmpty(matches[1]); }, "[1] is equal to 18": function (matches) { assert.strictEqual(parseInt(matches[1]), 18); } }, "testing output file": { topic: function () { fs.stat(path.join(outputDir, testOutPath), this.callback); }, "after a successful 'fs.stat'": { topic: function (stat) { fs.open(path.join(outputDir, testOutPath), "r", stat.mode, this.callback); }, "after a successful 'fs.open'": { topic: function (fd, stat) { fs.read(fd, stat.size, 0, "utf8", this.callback); }, "we can 'fs.read' to get the file contents": function (data) { assert.isString(data); }, // "'fs.read' contents length is 4901250": function (data) { // assert.strictEqual(data.length, 4901250); // }, "remove outputDir": function (data) { spawn('rm', ['-fR', outputDir]); } } } } } } }).export(module);
import React from 'react'; import renderer from 'react-test-renderer'; import applyMarkdown, {useStyle} from './apply-markdown'; const renderFragments = frags => renderer.create(frags).toJSON(); const coolResult = [ 'be ', { type: 'b', props: { className: 'info' }, children: ['cool'] } ]; describe('applyMarkdown()', () => { it('should return fn that returns whole string', () => { expect(applyMarkdown()('dog')).toBe('dog'); expect(applyMarkdown(null)('cat')).toBe('cat'); }); it('should handle string property', () => { let mark = applyMarkdown({'*': 'info'}), frag = renderFragments(mark('be *cool*')); expect(frag).toEqual([ 'be ', { type: 'span', props: { className: 'info' }, children: ['cool'] } ]); }); it('should handle class component', () => { class Component extends React.Component { render() { return <b className="info">{this.props.children}</b>; } } let mark = applyMarkdown({'*': Component}), frag = renderFragments(mark('be *cool*')); expect(frag).toEqual(coolResult); }); it('should handle functional component', () => { const Component = ({children}) => <b className="info">{children}</b>; let mark = applyMarkdown({'*': Component}), frag = renderFragments(mark('be *cool*')); expect(frag).toEqual(coolResult); }); }); describe('.useStyle', () => { it('should return null', () => { expect(useStyle()).toBe(null); expect(useStyle(null, null)).toBe(null); }); it('should return spec object', () => { const spec = { '*': 'info' }; expect(useStyle(undefined, spec)).toBe(spec); expect(useStyle(null, spec)).toBe(spec); }); it('should transform style into spec', () => { const style = { info: 'gzVnrw', warn: 'jHmeYN' }; const spec = { '*': 'info', '!': 'warn' }; expect(useStyle(style, spec)).toEqual({ '!': 'jHmeYN', '*': 'gzVnrw' }); }); });
import React from 'react'; import {storiesOf} from '@kadira/storybook'; import Markdown from '../utils/Components/Markdown'; import CodeExample from '../utils/Components/CodeExample'; import Readme from '../../src/DatePicker/README.md'; import ExampleControlled from './ExampleControlled'; import ExampleControlledRaw from '!raw!./ExampleControlled'; import ExampleControlledRtl from './ExampleControlledRtl'; import ExampleControlledRawRtl from '!raw!./ExampleControlledRtl'; import ExampleControlledExcludePast from './ExampleControlledExcludePast'; import ExampleControlledRawExcludePast from '!raw!./ExampleControlledExcludePast'; storiesOf('Core', module) .add('DatePicker', () => ( <div> <Markdown source={Readme}/> <h1>Usage examples</h1> <CodeExample title="Controlled input" code={ExampleControlledRaw}> <ExampleControlled/> </CodeExample> <CodeExample title="Controlled input - RTL" code={ExampleControlledRawRtl}> <ExampleControlledRtl/> </CodeExample> <CodeExample title="Controlled input - exclude past dates" code={ExampleControlledRawExcludePast}> <ExampleControlledExcludePast/> </CodeExample> </div> ));
angular.module("ui.rCalendar.tpls", ["templates/rcalendar/calendar.html","templates/rcalendar/day.html","templates/rcalendar/displayEvent.html","templates/rcalendar/month.html","templates/rcalendar/monthviewDisplayEvent.html","templates/rcalendar/monthviewEventDetail.html","templates/rcalendar/week.html"]); angular.module('ui.rCalendar', ['ui.rCalendar.tpls']) .constant('calendarConfig', { formatDay: 'dd', formatDayHeader: 'EEE', formatDayTitle: 'MMMM dd, yyyy', formatWeekTitle: 'MMMM yyyy, Week w', formatMonthTitle: 'MMMM yyyy', formatWeekViewDayHeader: 'EEE d', formatHourColumn: 'ha', calendarMode: 'month', showEventDetail: true, startingDayMonth: 0, startingDayWeek: 0, allDayLabel: 'all day', noEventsLabel: 'No Events', eventSource: null, queryMode: 'local', step: 60, monthviewDisplayEventTemplateUrl: 'templates/rcalendar/monthviewDisplayEvent.html', monthviewEventDetailTemplateUrl: 'templates/rcalendar/monthviewEventDetail.html', weekviewAllDayEventTemplateUrl: 'templates/rcalendar/displayEvent.html', weekviewNormalEventTemplateUrl: 'templates/rcalendar/displayEvent.html', dayviewAllDayEventTemplateUrl: 'templates/rcalendar/displayEvent.html', dayviewNormalEventTemplateUrl: 'templates/rcalendar/displayEvent.html' }) .controller('ui.rCalendar.CalendarController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'calendarConfig', '$timeout', '$ionicSlideBoxDelegate', function ($scope, $attrs, $parse, $interpolate, $log, dateFilter, calendarConfig, $timeout, $ionicSlideBoxDelegate) { 'use strict'; var self = this, ngModelCtrl = {$setViewValue: angular.noop}; // nullModelCtrl; // Configuration attributes angular.forEach(['formatDay', 'formatDayHeader', 'formatDayTitle', 'formatWeekTitle', 'formatMonthTitle', 'formatWeekViewDayHeader', 'formatHourColumn', 'allDayLabel', 'noEventsLabel', 'showEventDetail'], function (key, index) { self[key] = angular.isDefined($attrs[key]) ? $interpolate($attrs[key])($scope.$parent) : calendarConfig[key]; }); angular.forEach(['monthviewDisplayEventTemplateUrl', 'monthviewEventDetailTemplateUrl', 'weekviewAllDayEventTemplateUrl', 'weekviewNormalEventTemplateUrl', 'dayviewAllDayEventTemplateUrl', 'dayviewNormalEventTemplateUrl', 'eventSource', 'queryMode', 'step', 'startingDayMonth', 'startingDayWeek'], function (key, index) { self[key] = angular.isDefined($attrs[key]) ? ($scope.$parent.$eval($attrs[key])) : calendarConfig[key]; }); self.hourParts = 1; if (self.step === 60 || self.step === 30 || self.step === 15) { self.hourParts = Math.floor(60 / self.step); } else { throw new Error('Invalid step parameter: ' + self.step); } $scope.$parent.$watch($attrs.eventSource, function (value) { self.onEventSourceChanged(value); }); $scope.calendarMode = $scope.calendarMode || calendarConfig.calendarMode; if (angular.isDefined($attrs.initDate)) { self.currentCalendarDate = $scope.$parent.$eval($attrs.initDate); } if (!self.currentCalendarDate) { self.currentCalendarDate = new Date(); if ($attrs.ngModel && !$scope.$parent.$eval($attrs.ngModel)) { $parse($attrs.ngModel).assign($scope.$parent, self.currentCalendarDate); } } function overlap(event1, event2) { var earlyEvent = event1, lateEvent = event2; if (event1.startIndex > event2.startIndex || (event1.startIndex === event2.startIndex && event1.startOffset > event2.startOffset)) { earlyEvent = event2; lateEvent = event1; } if (earlyEvent.endIndex <= lateEvent.startIndex) { return false; } else { return !(earlyEvent.endIndex - lateEvent.startIndex === 1 && earlyEvent.endOffset + lateEvent.startOffset > self.hourParts); } } function calculatePosition(events) { var i, j, len = events.length, maxColumn = 0, col, isForbidden = new Array(len); for (i = 0; i < len; i += 1) { for (col = 0; col < maxColumn; col += 1) { isForbidden[col] = false; } for (j = 0; j < i; j += 1) { if (overlap(events[i], events[j])) { isForbidden[events[j].position] = true; } } for (col = 0; col < maxColumn; col += 1) { if (!isForbidden[col]) { break; } } if (col < maxColumn) { events[i].position = col; } else { events[i].position = maxColumn++; } } } function calculateWidth(orderedEvents) { var cells = new Array(24), event, index, i, j, len, eventCountInCell, currentEventInCell; //sort by position in descending order, the right most columns should be calculated first orderedEvents.sort(function (eventA, eventB) { return eventB.position - eventA.position; }); for (i = 0; i < 24; i += 1) { cells[i] = { calculated: false, events: [] }; } len = orderedEvents.length; for (i = 0; i < len; i += 1) { event = orderedEvents[i]; index = event.startIndex; while (index < event.endIndex) { cells[index].events.push(event); index += 1; } } i = 0; while (i < len) { event = orderedEvents[i]; if (!event.overlapNumber) { var overlapNumber = event.position + 1; event.overlapNumber = overlapNumber; var eventQueue = [event]; while ((event = eventQueue.shift())) { index = event.startIndex; while (index < event.endIndex) { if (!cells[index].calculated) { cells[index].calculated = true; if (cells[index].events) { eventCountInCell = cells[index].events.length; for (j = 0; j < eventCountInCell; j += 1) { currentEventInCell = cells[index].events[j]; if (!currentEventInCell.overlapNumber) { currentEventInCell.overlapNumber = overlapNumber; eventQueue.push(currentEventInCell); } } } } index += 1; } } } i += 1; } } function getAdjacentCalendarDate(currentCalendarDate, direction) { var step = self.mode.step, calculateCalendarDate = new Date(currentCalendarDate), year = calculateCalendarDate.getFullYear() + direction * (step.years || 0), month = calculateCalendarDate.getMonth() + direction * (step.months || 0), date = calculateCalendarDate.getDate() + direction * (step.days || 0), firstDayInNextMonth; calculateCalendarDate.setFullYear(year, month, date); if ($scope.calendarMode === 'month') { firstDayInNextMonth = new Date(year, month + 1, 1); if (firstDayInNextMonth.getTime() <= calculateCalendarDate.getTime()) { calculateCalendarDate = new Date(firstDayInNextMonth - 24 * 60 * 60 * 1000); } } return calculateCalendarDate; } self.init = function (ngModelCtrl_) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = function () { self.render(); }; }; self.render = function () { if (ngModelCtrl.$modelValue) { var date = new Date(ngModelCtrl.$modelValue), isValid = !isNaN(date); if (isValid) { this.currentCalendarDate = date; } else { $log.error('"ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); } ngModelCtrl.$setValidity('date', isValid); } this.refreshView(); }; self.refreshView = function () { if (this.mode) { this.range = this._getRange(this.currentCalendarDate); if ($scope.titleChanged) { $scope.titleChanged({title: self._getTitle()}); } this._refreshView(); this.rangeChanged(); } }; // Split array into smaller arrays self.split = function (arr, size) { var arrays = []; while (arr.length > 0) { arrays.push(arr.splice(0, size)); } return arrays; }; self.onEventSourceChanged = function (value) { self.eventSource = value; if (self._onDataLoaded) { self._onDataLoaded(); } }; self.getAdjacentViewStartTime = function (direction) { var adjacentCalendarDate = getAdjacentCalendarDate(self.currentCalendarDate, direction); return self._getRange(adjacentCalendarDate).startTime; }; self.move = function (direction) { self.direction = direction; if (self.moveOnSelected) { self.moveOnSelected = false; } else { self.currentCalendarDate = getAdjacentCalendarDate(self.currentCalendarDate, direction); } ngModelCtrl.$setViewValue(self.currentCalendarDate); self.refreshView(); self.direction = 0; }; self.rangeChanged = function () { if (self.queryMode === 'local') { if (self.eventSource && self._onDataLoaded) { self._onDataLoaded(); } } else if (self.queryMode === 'remote') { if ($scope.rangeChanged) { $scope.rangeChanged({ startTime: this.range.startTime, endTime: this.range.endTime }); } } }; self.registerSlideChanged = function (scope) { scope.currentViewIndex = 0; scope.slideChanged = function ($index) { $timeout(function () { var currentViewIndex = scope.currentViewIndex, direction = 0; if ($index - currentViewIndex === 1 || ($index === 0 && currentViewIndex === 2)) { direction = 1; } else if (currentViewIndex - $index === 1 || ($index === 2 && currentViewIndex === 0)) { direction = -1; } currentViewIndex = $index; scope.currentViewIndex = currentViewIndex; self.move(direction); scope.$digest(); }, 200); }; }; self.populateAdjacentViews = function (scope) { var currentViewStartDate, currentViewData, toUpdateViewIndex, currentViewIndex = scope.currentViewIndex, getViewData = this._getViewData; if (self.direction === 1) { currentViewStartDate = self.getAdjacentViewStartTime(1); toUpdateViewIndex = (currentViewIndex + 1) % 3; angular.copy(getViewData(currentViewStartDate), scope.views[toUpdateViewIndex]); } else if (self.direction === -1) { currentViewStartDate = self.getAdjacentViewStartTime(-1); toUpdateViewIndex = (currentViewIndex + 2) % 3; angular.copy(getViewData(currentViewStartDate), scope.views[toUpdateViewIndex]); } else { if (!scope.views) { currentViewData = []; currentViewStartDate = self.range.startTime; currentViewData.push(getViewData(currentViewStartDate)); currentViewStartDate = self.getAdjacentViewStartTime(1); currentViewData.push(getViewData(currentViewStartDate)); currentViewStartDate = self.getAdjacentViewStartTime(-1); currentViewData.push(getViewData(currentViewStartDate)); scope.views = currentViewData; } else { currentViewStartDate = self.range.startTime; angular.copy(getViewData(currentViewStartDate), scope.views[currentViewIndex]); currentViewStartDate = self.getAdjacentViewStartTime(-1); toUpdateViewIndex = (currentViewIndex + 2) % 3; angular.copy(getViewData(currentViewStartDate), scope.views[toUpdateViewIndex]); currentViewStartDate = self.getAdjacentViewStartTime(1); toUpdateViewIndex = (currentViewIndex + 1) % 3; angular.copy(getViewData(currentViewStartDate), scope.views[toUpdateViewIndex]); } } }; self.placeEvents = function (orderedEvents) { calculatePosition(orderedEvents); calculateWidth(orderedEvents); }; self.placeAllDayEvents = function (orderedEvents) { calculatePosition(orderedEvents); }; self.slideView = function (direction) { var slideHandle = $ionicSlideBoxDelegate.$getByHandle($scope.calendarMode + 'view-slide'); if (slideHandle) { if (direction === 1) { slideHandle.next(); } else if (direction === -1) { slideHandle.previous(); } } }; }]) .directive('calendar', function () { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/calendar.html', scope: { calendarMode: '=', rangeChanged: '&', eventSelected: '&', timeSelected: '&', titleChanged: '&' }, require: ['calendar', '?^ngModel'], controller: 'ui.rCalendar.CalendarController', link: function (scope, element, attrs, ctrls) { var calendarCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (ngModelCtrl) { calendarCtrl.init(ngModelCtrl); } scope.$on('changeDate', function (event, direction) { calendarCtrl.slideView(direction); }); scope.$on('eventSourceChanged', function (event, value) { calendarCtrl.onEventSourceChanged(value); }); } }; }) .directive('monthview', ['dateFilter', function (dateFilter) { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/month.html', require: ['^calendar', '?^ngModel'], link: function (scope, element, attrs, ctrls) { var ctrl = ctrls[0], ngModelCtrl = ctrls[1]; scope.showEventDetail = ctrl.showEventDetail; scope.formatDayHeader = ctrl.formatDayHeader; ctrl.mode = { step: {months: 1} }; scope.noEventsLabel = ctrl.noEventsLabel; scope.displayEventTemplateUrl = ctrl.monthviewDisplayEventTemplateUrl; scope.eventDetailTemplateUrl = ctrl.monthviewEventDetailTemplateUrl; function getDates(startDate, n) { var dates = new Array(n), current = new Date(startDate), i = 0; current.setHours(12); // Prevent repeated dates because of timezone bug while (i < n) { dates[i++] = new Date(current); current.setDate(current.getDate() + 1); } return dates; } function createDateObject(date, format) { return { date: date, label: dateFilter(date, format) }; } function updateCurrentView(currentViewStartDate, view) { var currentCalendarDate = ctrl.currentCalendarDate, today = new Date(), oneDay = 86400000, r, selectedDayDifference = Math.floor((currentCalendarDate.getTime() - currentViewStartDate.getTime()) / oneDay), currentDayDifference = Math.floor((today.getTime() - currentViewStartDate.getTime()) / oneDay); for (r = 0; r < 42; r += 1) { view.dates[r].selected = false; } if (selectedDayDifference >= 0 && selectedDayDifference < 42) { view.dates[selectedDayDifference].selected = true; scope.selectedDate = view.dates[selectedDayDifference]; } else { scope.selectedDate = { events: [] }; } if (currentDayDifference >= 0 && currentDayDifference < 42) { view.dates[currentDayDifference].current = true; } } function compareEvent(event1, event2) { if (event1.allDay) { return 1; } else if (event2.allDay) { return -1; } else { return (event1.startTime.getTime() - event2.startTime.getTime()); } } scope.select = function (selectedDate, events) { var views = scope.views, dates, r; if (views) { dates = views[scope.currentViewIndex].dates; var currentCalendarDate = ctrl.currentCalendarDate; var currentMonth = currentCalendarDate.getMonth(); var currentYear = currentCalendarDate.getFullYear(); var selectedMonth = selectedDate.getMonth(); var selectedYear = selectedDate.getFullYear(); var direction = 0; if (currentYear === selectedYear) { if (currentMonth !== selectedMonth) { direction = currentMonth < selectedMonth ? 1 : -1; } } else { direction = currentYear < selectedYear ? 1 : -1; } ctrl.currentCalendarDate = selectedDate; if (direction === 0) { ctrl.currentCalendarDate = selectedDate; if (ngModelCtrl) { ngModelCtrl.$setViewValue(selectedDate); } var currentViewStartDate = ctrl.range.startTime, oneDay = 86400000, selectedDayDifference = Math.floor((selectedDate.getTime() - currentViewStartDate.getTime()) / oneDay); for (r = 0; r < 42; r += 1) { dates[r].selected = false; } if (selectedDayDifference >= 0 && selectedDayDifference < 42) { dates[selectedDayDifference].selected = true; scope.selectedDate = dates[selectedDayDifference]; } } else { ctrl.moveOnSelected = true; ctrl.slideView(direction); } if (scope.timeSelected) { scope.timeSelected({selectedTime: selectedDate, events: events}); } } }; scope.getHighlightClass = function (date) { var className = ''; if (date.hasEvent) { if (date.secondary) { className = 'monthview-secondary-with-event'; } else { className = 'monthview-primary-with-event'; } for(var i=0; i<date.events.length; i++) { if(className) { className += ' '; } if(date.events[i].className) { className += date.events[i].className; } } } if (date.selected) { if (className) { className += ' '; } className += 'monthview-selected'; } if (date.current) { if (className) { className += ' '; } className += 'monthview-current'; } if (date.secondary) { if (className) { className += ' '; } className += 'text-muted'; } return className; }; ctrl._getTitle = function () { var currentViewStartDate = ctrl.range.startTime, date = currentViewStartDate.getDate(), month = (currentViewStartDate.getMonth() + (date !== 1 ? 1 : 0)) % 12, year = currentViewStartDate.getFullYear() + (date !== 1 && month === 0 ? 1 : 0), headerDate = new Date(year, month, 1); return dateFilter(headerDate, ctrl.formatMonthTitle); }; ctrl._getViewData = function (startTime) { var startDate = startTime, date = startDate.getDate(), month = (startDate.getMonth() + (date !== 1 ? 1 : 0)) % 12; var days = getDates(startDate, 42); for (var i = 0; i < 42; i++) { days[i] = angular.extend(createDateObject(days[i], ctrl.formatDay), { secondary: days[i].getMonth() !== month }); } return { dates: days }; }; ctrl._refreshView = function () { ctrl.populateAdjacentViews(scope); updateCurrentView(ctrl.range.startTime, scope.views[scope.currentViewIndex]); }; ctrl._onDataLoaded = function () { var eventSource = ctrl.eventSource, len = eventSource ? eventSource.length : 0, startTime = ctrl.range.startTime, endTime = ctrl.range.endTime, timeZoneOffset = -new Date().getTimezoneOffset(), utcStartTime = new Date(startTime.getTime() + timeZoneOffset * 60 * 1000), utcEndTime = new Date(endTime.getTime() + timeZoneOffset * 60 * 1000), currentViewIndex = scope.currentViewIndex, dates = scope.views[currentViewIndex].dates, oneDay = 86400000, eps = 0.001; for (var r = 0; r < 42; r += 1) { if (dates[r].hasEvent) { dates[r].hasEvent = false; dates[r].events = []; } } for (var i = 0; i < len; i += 1) { var event = eventSource[i]; var eventStartTime = new Date(event.startTime); var eventEndTime = new Date(event.endTime); var st; var et; if (event.allDay) { if (eventEndTime <= utcStartTime || eventStartTime >= utcEndTime) { continue; } else { st = utcStartTime; et = utcEndTime; } } else { if (eventEndTime <= startTime || eventStartTime >= endTime) { continue; } else { st = startTime; et = endTime; } } var timeDifferenceStart; if (eventStartTime <= st) { timeDifferenceStart = 0; } else { timeDifferenceStart = (eventStartTime - st) / oneDay; } var timeDifferenceEnd; if (eventEndTime >= et) { timeDifferenceEnd = (et - st) / oneDay; } else { timeDifferenceEnd = (eventEndTime - st) / oneDay; } var index = Math.floor(timeDifferenceStart); var eventSet; while (index < timeDifferenceEnd - eps) { dates[index].hasEvent = true; eventSet = dates[index].events; if (eventSet) { eventSet.push(event); } else { eventSet = []; eventSet.push(event); dates[index].events = eventSet; } index += 1; } } for (r = 0; r < 42; r += 1) { if (dates[r].hasEvent) { dates[r].events.sort(compareEvent); } } var findSelected = false; for (r = 0; r < 42; r += 1) { if (dates[r].selected) { scope.selectedDate = dates[r]; findSelected = true; break; } if (findSelected) { break; } } }; ctrl._getRange = function getRange(currentDate) { var year = currentDate.getFullYear(), month = currentDate.getMonth(), firstDayOfMonth = new Date(year, month, 1), difference = ctrl.startingDayMonth - firstDayOfMonth.getDay(), numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : -difference, startDate = new Date(firstDayOfMonth), endDate; if (numDisplayedFromPreviousMonth > 0) { startDate.setDate(-numDisplayedFromPreviousMonth + 1); } endDate = new Date(startDate); endDate.setDate(endDate.getDate() + 42); return { startTime: startDate, endTime: endDate }; }; ctrl.registerSlideChanged(scope); ctrl.refreshView(); } }; }]) .directive('weekview', ['dateFilter', function (dateFilter) { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/week.html', require: '^calendar', link: function (scope, element, attrs, ctrl) { scope.formatWeekViewDayHeader = ctrl.formatWeekViewDayHeader; scope.formatHourColumn = ctrl.formatHourColumn; ctrl.mode = { step: {days: 7} }; scope.allDayLabel = ctrl.allDayLabel; scope.hourParts = ctrl.hourParts; scope.allDayEventTemplateUrl = ctrl.weekviewAllDayEventTemplateUrl; scope.normalEventTemplateUrl = ctrl.weekviewNormalEventTemplateUrl; scope.fetchWeekEventClass = function(event) { return event.event.className ? event.event.className : ''; }; function getDates(startTime, n) { var dates = new Array(n), current = new Date(startTime), i = 0; current.setHours(12); // Prevent repeated dates because of timezone bug while (i < n) { dates[i++] = { date: new Date(current) }; current.setDate(current.getDate() + 1); } return dates; } function createDateObjects(startTime) { var times = [], row, time, currentHour = startTime.getHours(), currentDate = startTime.getDate(); for (var hour = 0; hour < 24; hour += 1) { row = []; for (var day = 0; day < 7; day += 1) { time = new Date(startTime.getTime()); time.setHours(currentHour + hour); time.setDate(currentDate + day); row.push({ time: time }); } times.push(row); } return times; } function compareEventByStartOffset(eventA, eventB) { return eventA.startOffset - eventB.startOffset; } //This can be decomissioned when upgrade to Angular 1.3 function getISO8601WeekNumber(date) { var checkDate = new Date(date); checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; } ctrl._getTitle = function () { var firstDayOfWeek = ctrl.range.startTime, weekNumberIndex, weekFormatPattern = 'w', title; weekNumberIndex = ctrl.formatWeekTitle.indexOf(weekFormatPattern); title = dateFilter(firstDayOfWeek, ctrl.formatWeekTitle); if (weekNumberIndex !== -1) { title = title.replace(weekFormatPattern, getISO8601WeekNumber(firstDayOfWeek)); } return title; }; scope.select = function (selectedTime, events) { if (scope.timeSelected) { scope.timeSelected({selectedTime: selectedTime, events: events}); } }; ctrl._getViewData = function (startTime) { return { rows: createDateObjects(startTime), dates: getDates(startTime, 7) }; }; ctrl._refreshView = function () { ctrl.populateAdjacentViews(scope); }; ctrl._onDataLoaded = function () { var eventSource = ctrl.eventSource, i, day, hour, len = eventSource ? eventSource.length : 0, startTime = ctrl.range.startTime, endTime = ctrl.range.endTime, timeZoneOffset = -new Date().getTimezoneOffset(), utcStartTime = new Date(startTime.getTime() + timeZoneOffset * 60000), utcEndTime = new Date(endTime.getTime() + timeZoneOffset * 60000), currentViewIndex = scope.currentViewIndex, rows = scope.views[currentViewIndex].rows, dates = scope.views[currentViewIndex].dates, oneHour = 3600000, oneDay = 86400000, //add allday eps eps = 0.016, eventSet, allDayEventInRange = false, normalEventInRange = false; for (i = 0; i < 7; i += 1) { dates[i].events = []; } for (day = 0; day < 7; day += 1) { for (hour = 0; hour < 24; hour += 1) { rows[hour][day].events = []; } } for (i = 0; i < len; i += 1) { var event = eventSource[i]; var eventStartTime = new Date(event.startTime); var eventEndTime = new Date(event.endTime); if (event.allDay) { if (eventEndTime <= utcStartTime || eventStartTime >= utcEndTime) { continue; } else { allDayEventInRange = true; var allDayStartIndex; if (eventStartTime <= utcStartTime) { allDayStartIndex = 0; } else { allDayStartIndex = Math.floor((eventStartTime - utcStartTime) / oneDay); } var allDayEndIndex; if (eventEndTime >= utcEndTime) { allDayEndIndex = Math.ceil((utcEndTime - utcStartTime) / oneDay); } else { allDayEndIndex = Math.ceil((eventEndTime - utcStartTime) / oneDay); } var displayAllDayEvent = { event: event, startIndex: allDayStartIndex, endIndex: allDayEndIndex }; eventSet = dates[allDayStartIndex].events; if (eventSet) { eventSet.push(displayAllDayEvent); } else { eventSet = []; eventSet.push(displayAllDayEvent); dates[allDayStartIndex].events = eventSet; } } } else { if (eventEndTime <= startTime || eventStartTime >= endTime) { continue; } else { normalEventInRange = true; var timeDifferenceStart; if (eventStartTime <= startTime) { timeDifferenceStart = 0; } else { timeDifferenceStart = (eventStartTime - startTime) / oneHour; } var timeDifferenceEnd; if (eventEndTime >= endTime) { timeDifferenceEnd = (endTime - startTime) / oneHour; } else { timeDifferenceEnd = (eventEndTime - startTime) / oneHour; } var startIndex = Math.floor(timeDifferenceStart); var endIndex = Math.ceil(timeDifferenceEnd - eps); var startRowIndex = startIndex % 24; var dayIndex = Math.floor(startIndex / 24); var endOfDay = dayIndex * 24; var endRowIndex; var startOffset = 0; var endOffset = 0; if (ctrl.hourParts !== 1) { startOffset = Math.floor((timeDifferenceStart - startIndex) * ctrl.hourParts); } do { endOfDay += 24; if (endOfDay <= endIndex) { endRowIndex = 24; } else { endRowIndex = endIndex % 24; if (ctrl.hourParts !== 1) { endOffset = Math.floor((endIndex - timeDifferenceEnd) * ctrl.hourParts); } } var displayEvent = { event: event, startIndex: startRowIndex, endIndex: endRowIndex, startOffset: startOffset, endOffset: endOffset }; eventSet = rows[startRowIndex][dayIndex].events; if (eventSet) { eventSet.push(displayEvent); } else { eventSet = []; eventSet.push(displayEvent); rows[startRowIndex][dayIndex].events = eventSet; } startRowIndex = 0; startOffset = 0; dayIndex += 1; } while (endOfDay < endIndex); } } } if (normalEventInRange) { for (day = 0; day < 7; day += 1) { var orderedEvents = []; for (hour = 0; hour < 24; hour += 1) { if (rows[hour][day].events) { rows[hour][day].events.sort(compareEventByStartOffset); orderedEvents = orderedEvents.concat(rows[hour][day].events); } } if (orderedEvents.length > 0) { ctrl.placeEvents(orderedEvents); } } } if (allDayEventInRange) { var orderedAllDayEvents = []; for (day = 0; day < 7; day += 1) { if (dates[day].events) { orderedAllDayEvents = orderedAllDayEvents.concat(dates[day].events); } } if (orderedAllDayEvents.length > 0) { ctrl.placeAllDayEvents(orderedAllDayEvents); } } }; ctrl._getRange = function getRange(currentDate) { var year = currentDate.getFullYear(), month = currentDate.getMonth(), date = currentDate.getDate(), day = currentDate.getDay(), difference = day - ctrl.startingDayWeek, firstDayOfWeek, endTime; if (difference < 0) { difference += 7; } firstDayOfWeek = new Date(year, month, date - difference); endTime = new Date(year, month, date - difference + 7); return { startTime: firstDayOfWeek, endTime: endTime }; }; ctrl.registerSlideChanged(scope); ctrl.refreshView(); } }; }]) .directive('dayview', ['dateFilter', function (dateFilter) { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/day.html', require: '^calendar', link: function (scope, element, attrs, ctrl) { scope.formatHourColumn = ctrl.formatHourColumn; ctrl.mode = { step: {days: 1} }; scope.allDayLabel = ctrl.allDayLabel; scope.hourParts = ctrl.hourParts; scope.allDayEventTemplateUrl = ctrl.dayviewAllDayEventTemplateUrl; scope.normalEventTemplateUrl = ctrl.dayviewNormalEventTemplateUrl; scope.fetchDayEventClass = function(event) { return event.event.className ? event.event.className : ''; }; function createDateObjects(startTime) { var rows = [], time, currentHour = startTime.getHours(), currentDate = startTime.getDate(); for (var hour = 0; hour < 24; hour += 1) { time = new Date(startTime.getTime()); time.setHours(currentHour + hour); time.setDate(currentDate); rows.push({ time: time }); } return rows; } function compareEventByStartOffset(eventA, eventB) { return eventA.startOffset - eventB.startOffset; } scope.select = function (selectedTime, events) { if (scope.timeSelected) { scope.timeSelected({selectedTime: selectedTime, events: events}); } }; ctrl._onDataLoaded = function () { var eventSource = ctrl.eventSource, hour, len = eventSource ? eventSource.length : 0, startTime = ctrl.range.startTime, endTime = ctrl.range.endTime, timeZoneOffset = -new Date().getTimezoneOffset(), utcStartTime = new Date(startTime.getTime() + timeZoneOffset * 60 * 1000), utcEndTime = new Date(endTime.getTime() + timeZoneOffset * 60 * 1000), currentViewIndex = scope.currentViewIndex, rows = scope.views[currentViewIndex].rows, allDayEvents = scope.views[currentViewIndex].allDayEvents = [], oneHour = 3600000, eps = 0.016, eventSet, normalEventInRange = false; for (hour = 0; hour < 24; hour += 1) { rows[hour].events = []; } for (var i = 0; i < len; i += 1) { var event = eventSource[i]; var eventStartTime = new Date(event.startTime); var eventEndTime = new Date(event.endTime); if (event.allDay) { if (eventEndTime <= utcStartTime || eventStartTime >= utcEndTime) { continue; } else { allDayEvents.push({ event: event }); } } else { if (eventEndTime <= startTime || eventStartTime >= endTime) { continue; } else { normalEventInRange = true; } var timeDifferenceStart; if (eventStartTime <= startTime) { timeDifferenceStart = 0; } else { timeDifferenceStart = (eventStartTime - startTime) / oneHour; } var timeDifferenceEnd; if (eventEndTime >= endTime) { timeDifferenceEnd = (endTime - startTime) / oneHour; } else { timeDifferenceEnd = (eventEndTime - startTime) / oneHour; } var startIndex = Math.floor(timeDifferenceStart); var endIndex = Math.ceil(timeDifferenceEnd - eps); var startOffset = 0; var endOffset = 0; if (ctrl.hourParts !== 1) { startOffset = Math.floor((timeDifferenceStart - startIndex) * ctrl.hourParts); endOffset = Math.floor((endIndex - timeDifferenceEnd) * ctrl.hourParts); } var displayEvent = { event: event, startIndex: startIndex, endIndex: endIndex, startOffset: startOffset, endOffset: endOffset }; eventSet = rows[startIndex].events; if (eventSet) { eventSet.push(displayEvent); } else { eventSet = []; eventSet.push(displayEvent); rows[startIndex].events = eventSet; } } } if (normalEventInRange) { var orderedEvents = []; for (hour = 0; hour < 24; hour += 1) { if (rows[hour].events) { rows[hour].events.sort(compareEventByStartOffset); orderedEvents = orderedEvents.concat(rows[hour].events); } } if (orderedEvents.length > 0) { ctrl.placeEvents(orderedEvents); } } }; ctrl._refreshView = function () { ctrl.populateAdjacentViews(scope); }; ctrl._getTitle = function () { var startingDate = ctrl.range.startTime; return dateFilter(startingDate, ctrl.formatDayTitle); }; ctrl._getViewData = function (startTime) { return { rows: createDateObjects(startTime), allDayEvents: [] }; }; ctrl._getRange = function getRange(currentDate) { var year = currentDate.getFullYear(), month = currentDate.getMonth(), date = currentDate.getDate(), startTime = new Date(year, month, date), endTime = new Date(year, month, date + 1); return { startTime: startTime, endTime: endTime }; }; ctrl.registerSlideChanged(scope); ctrl.refreshView(); } }; }]); angular.module("templates/rcalendar/calendar.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/calendar.html", "<div class=\"calendar-container\" ng-switch=\"calendarMode\">\n" + " <dayview ng-switch-when=\"day\"></dayview>\n" + " <monthview ng-switch-when=\"month\"></monthview>\n" + " <weekview ng-switch-when=\"week\"></weekview>\n" + "</div>"); }]); angular.module("templates/rcalendar/day.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/day.html", "<div class=\"dayview\">\n" + " <ion-slide-box class=\"dayview-slide\" on-slide-changed=\"slideChanged($index)\" does-continue=\"true\"\n" + " show-pager=\"false\" delegate-handle=\"dayview-slide\">\n" + " <ion-slide ng-repeat=\"view in views track by $index\">\n" + " <div class=\"dayview-allday-table\">\n" + " <div class=\"dayview-allday-label\" ng-bind=\"::allDayLabel\"></div>\n" + " <ion-content class=\"dayview-allday-content-wrapper\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered dayview-allday-content-table\">\n" + " <tbody>\n" + " <tr>\n" + " <td class=\"calendar-cell\" ng-class=\"{'calendar-event-wrap':view.allDayEvents.length>0}\"\n" + " ng-if=\"$index===currentViewIndex\" ng-style=\"{height: 25*view.allDayEvents.length+'px'}\">\n" + " <div ng-repeat=\"displayEvent in view.allDayEvents\"\n" + " class=\"calendar-event\"\n" + " ng-class=\"fetchDayEventClass(displayEvent)\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: 25*$index+'px',width: '100%',height:'25px'}\"\n" + " ng-include=\"::allDayEventTemplateUrl\">\n" + " </div>\n" + " </td>\n" + " <td class=\"calendar-cell\" ng-if=\"$index!==currentViewIndex\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <ion-content class=\"dayview-normal-event-container\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-fixed dayview-normal-event-table\"\n" + " ng-if=\"$index===currentViewIndex\">\n" + " <tbody>\n" + " <tr ng-repeat=\"tm in view.rows track by $index\">\n" + " <td class=\"calendar-hour-column text-center\">\n" + " {{::tm.time | date: formatHourColumn}}\n" + " </td>\n" + " <td class=\"calendar-cell\" ng-click=\"select(tm.time, tm.events)\">\n" + " <div ng-class=\"{'calendar-event-wrap': tm.events}\" ng-if=\"tm.events\">\n" + " <div ng-repeat=\"displayEvent in tm.events\"\n" + " class=\"calendar-event\"\n" + " ng-class=\"fetchDayEventClass(displayEvent)\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: (37*displayEvent.startOffset/hourParts)+'px', left: 100/displayEvent.overlapNumber*displayEvent.position+'%', width: 100/displayEvent.overlapNumber+'%', height: 37*(displayEvent.endIndex -displayEvent.startIndex - (displayEvent.endOffset + displayEvent.startOffset)/hourParts)+'px'}\"\n" + " ng-include=\"::normalEventTemplateUrl\">\n" + " </div>\n" + " </div>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table class=\"table table-bordered table-fixed dayview-normal-event-table\"\n" + " ng-if=\"$index!==currentViewIndex\">\n" + " <tbody>\n" + " <tr ng-repeat=\"tm in view.rows track by $index\">\n" + " <td class=\"calendar-hour-column text-center\">\n" + " {{::tm.time | date: formatHourColumn}}\n" + " </td>\n" + " <td class=\"calendar-cell\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </ion-slide>\n" + " </ion-slide-box>\n" + "</div>\n" + ""); }]); angular.module("templates/rcalendar/displayEvent.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/displayEvent.html", "<div class=\"calendar-event-inner\">{{displayEvent.event.title}}</div>"); }]); angular.module("templates/rcalendar/month.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/month.html", "<div>\n" + " <ion-slide-box class=\"monthview-slide\" on-slide-changed=\"slideChanged($index)\" does-continue=\"true\"\n" + " show-pager=\"false\" delegate-handle=\"monthview-slide\">\n" + " <ion-slide ng-repeat=\"view in views track by $index\">\n" + " <table ng-if=\"$index===currentViewIndex\" class=\"table table-bordered table-fixed monthview-datetable\">\n" + " <thead>\n" + " <tr>\n" + " <th ng-repeat=\"day in view.dates.slice(0,7) track by day.date\">\n" + " <small>{{::day.date | date: formatDayHeader}}</small>\n" + " </th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr ng-repeat=\"row in [0,1,2,3,4,5]\">\n" + " <td ng-repeat=\"col in [0,1,2,3,4,5,6]\" ng-click=\"select(view.dates[row*7+col].date, view.dates[row*7+col].events)\"\n" + " ng-class=\"getHighlightClass(view.dates[row*7+col])\" ng-include=\"::displayEventTemplateUrl\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table ng-if=\"$index!==currentViewIndex\" class=\"table table-bordered table-fixed monthview-datetable\">\n" + " <thead>\n" + " <tr class=\"text-center\">\n" + " <th ng-repeat=\"day in view.dates.slice(0,7) track by day.date\">\n" + " <small>{{::day.date | date: formatDayHeader}}</small>\n" + " </th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr ng-repeat=\"row in [0,1,2,3,4,5]\">\n" + " <td ng-repeat=\"col in [0,1,2,3,4,5,6]\">{{view.dates[row*7+col].label}}\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-slide>\n" + " </ion-slide-box>\n" + " <div ng-include=\"::eventDetailTemplateUrl\"></div>\n" + "</div>\n" + ""); }]); angular.module("templates/rcalendar/monthviewDisplayEvent.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/monthviewDisplayEvent.html", "{{view.dates[row*7+col].label}}"); }]); angular.module("templates/rcalendar/monthviewEventDetail.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/monthviewEventDetail.html", "<ion-content class=\"event-detail-container\" has-bouncing=\"false\" ng-show=\"showEventDetail\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-striped table-fixed event-detail-table\">\n" + " <tr ng-repeat=\"event in selectedDate.events\" ng-click=\"eventSelected({event:event})\">\n" + " <td ng-if=\"!event.allDay\" class=\"monthview-eventdetail-timecolumn\">{{::event.startTime|date: 'HH:mm'}}\n" + " -\n" + " {{::event.endTime|date: 'HH:mm'}}\n" + " </td>\n" + " <td ng-if=\"event.allDay\" class=\"monthview-eventdetail-timecolumn\">All day</td>\n" + " <td class=\"event-detail\">{{::event.title}}</td>\n" + " </tr>\n" + " <tr ng-if=\"!selectedDate.events\">\n" + " <td class=\"no-event-label\" ng-bind=\"::noEventsLabel\"></td>\n" + " </tr>\n" + " </table>\n" + "</ion-content>"); }]); angular.module("templates/rcalendar/week.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/week.html", "<div class=\"weekview\">\n" + " <ion-slide-box class=\"weekview-slide\" on-slide-changed=\"slideChanged($index)\" does-continue=\"true\"\n" + " show-pager=\"false\" delegate-handle=\"weekview-slide\">\n" + " <ion-slide ng-repeat=\"view in views track by $index\">\n" + " <table class=\"table table-bordered table-fixed weekview-header\">\n" + " <thead>\n" + " <tr>\n" + " <th class=\"calendar-hour-column\"></th>\n" + " <th class=\"weekview-header text-center\" ng-repeat=\"dt in view.dates\">{{::dt.date| date:\n" + " formatWeekViewDayHeader}}\n" + " </th>\n" + " </tr>\n" + " </thead>\n" + " </table>\n" + " <div ng-if=\"$index===currentViewIndex\">\n" + " <div class=\"weekview-allday-table\">\n" + " <div class=\"weekview-allday-label\" ng-bind=\"::allDayLabel\">\n" + " </div>\n" + " <ion-content class=\"weekview-allday-content-wrapper\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-fixed weekview-allday-content-table\">\n" + " <tbody>\n" + " <tr>\n" + " <td ng-repeat=\"day in view.dates track by day.date\" class=\"calendar-cell\">\n" + " <div ng-class=\"{'calendar-event-wrap': day.events}\" ng-if=\"day.events\"\n" + " ng-style=\"{height: 25*day.events.length+'px'}\">\n" + " <div ng-repeat=\"displayEvent in day.events\"\n" + " class=\"calendar-event\"\n" + " ng-class=\"fetchWeekEventClass(displayEvent)\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: 25*displayEvent.position+'px', width: 100*(displayEvent.endIndex-displayEvent.startIndex)+'%', height: '25px'}\"\n" + " ng-include=\"::allDayEventTemplateUrl\">\n" + " </div>\n" + " </div>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <ion-content class=\"weekview-normal-event-container\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-fixed weekview-normal-event-table\">\n" + " <tbody>\n" + " <tr ng-repeat=\"row in view.rows track by $index\">\n" + " <td class=\"calendar-hour-column text-center\">\n" + " {{::row[0].time | date: formatHourColumn}}\n" + " </td>\n" + " <td ng-repeat=\"tm in row track by tm.time\" class=\"calendar-cell\" ng-click=\"select(tm.time, tm.events)\">\n" + " <div ng-class=\"{'calendar-event-wrap': tm.events}\" ng-if=\"tm.events\">\n" + " <div ng-repeat=\"displayEvent in tm.events\"\n" + " class=\"calendar-event\"\n" + " ng-class=\"fetchWeekEventClass(displayEvent)\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: (37*displayEvent.startOffset/hourParts)+'px',left: 100/displayEvent.overlapNumber*displayEvent.position+'%', width: 100/displayEvent.overlapNumber+'%', height: 37*(displayEvent.endIndex -displayEvent.startIndex - (displayEvent.endOffset + displayEvent.startOffset)/hourParts)+'px'}\"\n" + " ng-include=\"::normalEventTemplateUrl\">\n" + " </div>\n" + " </div>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <div ng-if=\"$index!==currentViewIndex\">\n" + " <div class=\"weekview-allday-table\">\n" + " <div class=\"weekview-allday-label\" ng-bind=\"::allDayLabel\"></div>\n" + " <ion-content class=\"weekview-allday-content-wrapper\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-fixed weekview-allday-content-table\">\n" + " <tbody>\n" + " <tr>\n" + " <td ng-repeat=\"day in view.dates track by day.date\" class=\"calendar-cell\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <ion-content class=\"weekview-normal-event-container\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-fixed weekview-normal-event-table\">\n" + " <tbody>\n" + " <tr ng-repeat=\"row in view.rows track by $index\">\n" + " <td class=\"calendar-hour-column text-center\">\n" + " {{::row[0].time | date: formatHourColumn}}\n" + " </td>\n" + " <td ng-repeat=\"tm in row track by tm.time\" class=\"calendar-cell\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " </ion-slide>\n" + " </ion-slide-box>\n" + "</div>\n" + ""); }]);
import React, { Component, useState } from 'react'; import { shallow, mount } from 'enzyme'; import nj, { html } from 'nornj'; import '../../src/base'; function putStateValue(value, ret) { return value.prop == 'state' ? ret : putStateValue(value.parent, { [value.prop]: ret }); } nj.registerExtension( 'stateBind', options => { const { tagProps, value, context: { $this } } = options; const _value = value(); tagProps.value = _value.value; const _onChange = tagProps.onChange; tagProps.onChange = function(e) { $this.setState(putStateValue(_value, e.target.value), () => _onChange.apply($this, arguments)); }; }, { isDirective: true, isBindable: true, useExpressionInProps: true } ); class TestStateBind extends Component { state = { count: 100, foo: { count: 100 }, bar: { baz: { count: 100 } } }; render() { return ( <div> <input ref="input" n-stateBind={this.state.foo.count} onChange={this.props.handleChange} /> </div> ); } } const testStateBindTemplate = html` <div> <input ref="input" n-stateBind="{this.state.foo.count}" onChange="{this.props.handleChange}" /> </div> `; class TestStateBindTemplate extends Component { state = { count: 100, foo: { count: 100 }, bar: { baz: { count: 100 } } }; render() { return testStateBindTemplate(this); } } describe('n-stateBind directive', function() { it('should render n-stateBind', () => { const app = mount(<TestStateBind />); expect(app.find('input').props().value).toEqual(100); }); it('should render n-stateBind by NornJ template', () => { const app = mount(<TestStateBindTemplate />); expect(app.find('input').props().value).toEqual(100); }); it('responds to value change', () => { const spyHandleChange = jest.fn(e => console.log(e.target.value)); const wrap = mount(<TestStateBind handleChange={spyHandleChange} />); const event = { target: { value: 200 } }; wrap.find('input').simulate('change', event); wrap.update(); expect(wrap.ref('input').value).toEqual('200'); expect(spyHandleChange).toHaveBeenCalled(); }); });
var Meetup;
//Modificadores jQuery para el CSS var ht = $(window).height(); var ma = (($(window).height())/5); $(document).ready(function(){ $("#inicioHeader").css("height",ht); $(".vcenter").css("margin-top",ma) }); var app = angular.module('appNav', [ ]); //Botones para el nav /*Se inicia el controller*/ /* keyword nombre inicia Controler*/ app.controller('navController', function(){ /*Asignamos un método a las variables que tienen el contenido*/ /* metodo variable que tiene el contenido*/ this.navs = botones; }) /*Declaramos las variables y sus contenidos para usar el controller*/ var botones = [ { "name":"Inicio", "link":"index.html" },{ "name":"Cómo Funciona", "link":"comoFunciona.html" /*},{ "name":"Costos", "link":"costos.html"*/ },{ "name":"Graduaciones USDE", "link":"graduacionesUSDE.html" },{ "name":"Plan de Estudios", "link":"planDeEstudios.html" /*},{ "name":"Escuela de Idiomas", "link":"escuelaDeIdiomas.html" },{ "name":"Otras Tutorías", "link":"otrasTutorias.html"*/ },{ "name":"Contácto", "link":"contacto.html" } ] //Contenido de Inicio.html app.controller('contentInicio', function(){ this.primero = sec1; this.segundo = sec2; this.tercero = sec3; this.cuarto = sec4; this.quinto = sec5; }) var sec1 = { "titulo":"Su mejor elección para la educación de sus hijos.", "image":"Niña escribiendo en el suelo. Fondo" }; var sec2 = { "titulo":"Educación en Casa", "contenido":[ "Somos la más reciente y moderna opción en el área pedagógica y tecnológica que nos permite desarrollar programas de home schooling adaptados a las necesidades y exigencias de la actualidad.", "La mayoría de los colegios Guatemaltecos solo ofrecen educación aprobada por el Ministerio de Educación, pero el diploma que se obtiene no les permite a los estudiantes entradas a Universidades de USA.", "Los programas de WELDS ofrecen estudios desde primer grado hasta doce grado, de acuerdo a estándares de USA., lo cual le otorga al alumno egresado reconocimientos educativos o diplomas de graduación, de un colegio americano aprobado por US Department of Education, lo que les da acceso muchas universidades americanas." ], "image":"Adolescente mujer sentada en el suelo. Fondo" }; var sec3 = { "contenido": [ { "texto":"Graduación en reconocida por el US Departmet of Education", "icon":"fa-graduation-cap" },{ "texto":"Entrar a Universidades Americanas", "icon":"fa-lightbulb-o" },{ "texto":"Cursos en Ingles", "icon":"fa-book" },{ "texto":"Plataforma educativa online", "icon":"fa-pencil" } ]}; var sec4 = { "titulo": "La llave para el futuro de sus hijos", "articulos": [{ "titulo": "E-Books y Lecciones", "image": "Grupo de adolescentes estudiando en grupo.", "contenido": [ "Cada curso cuenta con un grupo de libros digitales y lecciones para que los alumnos puedan estudiar, estos mismos están diseñados para que los alumnos puedan ir aprendiendo a su paso." ] }, { "titulo": "Reporte de Avances", "image": "Adolescente mujer estudiando en la biblioteca.", "contenido": [ "Podrá observar en tiempo real los avances del alumno, lecciones aprendidas, punteos y cursos superados." ] }, { "titulo": "Evaluaciones Periódicas", "image": "Mujer adulta maestra.", "contenido": [ "Contamos con evaluaciones para medir el desempeño y lo aprendido para los alumnos." ] } ] }; var sec5 = { "titulo": "Enseñanza con Valores", "contenido": [ "Nuestros planes educativos contienes dolidos valores para que los alumnos puedan desempeñarse en un mundo laboral activo." ] } //Contenido de comoFunciona.html app.controller('contentComoFunciona', function(){ this.primero = fucniona1; this.segundo = funciona2; this.tercero = funciona3; this.cuarto = funciona4; this.quinto = funciona5; }) var fucniona1 = { "titulo": "Como Funciona?", "sub":"¿Como Me Inscribo?", "contenido":"Los Pasos que debes seguir son los siguientes: ", "lista":[ "Ponte en contacto a través de nuestra página y se solicitara algunos documentos necesarios para la inscripción.", "Debes realizar un examen de ubicación, el cual podrá ser en línea, cualquier día y cualquier hora o en nuestras instalaciones, previa cita de día y horario disponible.", "El examen de ubicación tiene un costo de $75.00.", "Luego se te enviará vía correo electrónico todos los pasos para necesarios para la inscripción, pago de cuotas, entrega de materiales y la adjudicación de usuario dentro de la plataforma educativa.", "Listo, puedes empezar a estudiar a tu ritmo, con tu horario y con disponibilidad de tutorías." ]}; var funciona2 = { "titulo":"¿Cómo funciona la plataforma educativa?", "lista":[ "El alumno recibe con la inscripción todo el material que va a utilizar.", "Si tiene dudas puede, por medio de la plataforma solicitar tutorías, de lunes a viernes, en horario de 8 am a 5 pm un máximo de 1 hora diaria, con tutor en forma personal.", "Por medio de la plataforma recibirás las tutorías y más material para desarrollar tus conocimientos, podrás también participar el foros y trabajo en grupo para interactuar, desde casa, con la comunidad educativa.", "Recibirás informes y evaluaciones para conocer avances de lo aprendido.", "Tienes acceso desde cualquier dispositivo con acceso a internet, 24/7 (no aplica a tutorías)." ], }; var funciona3 = { "titulo":"¿Cómo obtengo mis documentos de grados aprobados?", "contnido":"Por medio de nuestra plataforma se mantendrá la información permanente de los avances del estudiante y cuando este complete un grado en particular, será notificado y se le entregará sus respectivas constancias de aprobación." }; var funciona4 = { "titulo":"¿En qué momento me puedo integrar al programa de estudio?", "contenido":"En cualquier momento, dada su naturaleza de principio, un alumno puede integrarse en el momento que lo desee y comenzar sus estudios." }; var funciona5 = { "titulo":"¿Hay algún costo adicional?", "contenido":"Únicamente en el momento que el alumno se gradúa tiene un costo adicional de $60.00 por los trámites de acreditación consular del título. </br> Queda también pendientes, los costos del acto de graduación a llevarse a cabo en el país." }; //Contenido de planDeEstudios.html app.controller('contentGrado', function(){ this.titulo = "Plan de Estudios"; this.contentGrado = gradoApp; }) var gradoApp = [ { "name": "Grade 1", "number":1, "math" : { "name": "Math", "themes": [ "Focusing on math review including basic addition and subtraction problems with 2- and 3-digit numbers ", "Multiplication problems as repeated addition problems", "Multiplication tables", "Understanding numbers to 1,000 by various ways of counting, adding and subtracting horizontally and vertically", "Telling time", "Measuring", "Regrouping", "Beginning geometry", "Fractions", "Multiplication" ] }, "language": { "name": "Language Arts", "themes" : [ "Listening skills and beginning reading", "Fairy tales", "Nursery rhymes", "Myths", "Riddles", "Aesop’s Fables", "Simple sentence writing", "Introduction to punctuation signs" ] }, "science": { "name": "Science", "themes": [ "General Science", "Living Things and Their Habitats: Deserts &oceans", "The Food Chain", "Dinosaurs", "Introduction to the body", "Matter", "Units of Measurement", "The Environment", "Plants", "Animals,", "The solar system", "Measuring the seasons" ] }, "social": { "name": "Social Science", "themes": [ "An introduction to the Ice Age,", "Egypt", "Mesopotamia", "Hammurabi", "Crossing the Land Bridge", "Early American history", "World religions" ] }, "arts": { "name":"Fine Arts", "themes": [ "Visual art history", "Color, Drawing", "Shapes, Texture", "Portraits, Murals", "Orchestra instruments", "The Orchestra", "Great Composers", "Dance ", "Music" ] } }, { "name": "Grade 2", "number":2, "math": { "name":"Math", "themes": [ "Focusing on math review including basic addition and subtraction problems with 2- and 3-digit numbers", "Multiplication problems as repeated addition problems", "Multiplication tables", "Understanding numbers to 1,000 by various ways of counting, adding and subtracting horizontally and vertically", "Telling time", "Measuring", "Regrouping", "Beginning geometry", "Fractions", "Multiplication" ] }, "language": { "name": "Language Arts", "themes": [ "Learning to develop basic reading skills", "Vocabulary", "Reading for information using classic children stories including: Cinderella, A Christmas Carol, Hansel and Gretel, Peter Pan, and Greek and Roman myth", "Enjoying poetry", "Sayings and phrases", "Beginning to understand parts of speech", "Sentences", "Using proper punctuation" ] }, "science": { "name": "Science", "themes": [ "Introducing the cycles of life from birth to death", "Zoology", "Botany", "Beginning with the seasons.", "Presenting experiments to see the world", "Understanding health and human growth", "Introduction to chemistry", "Physics", "Astronomy", "Earth science", "Meteorology" ] }, "social":{ "name": "Social Science", "themes": [ "Beginning to use maps to find oceans, continents, and the four cardinal directions ", "Looking at geography ", "Early history of Mexico, Central America, South America, the Mediterranean countries, Africa, India, China. ", "Beginning American history to 1776 " ] }, "arts":{ "name": "Fine Arts", "themes": [ "Introducing music and the instruments in the orchestra", "Kinds of music", "Chopin", "Architecture of the Greeks", "Painters including: El Greco, Miro, Charles Demuth, Pieter Bruegel and Jan Vermeer", "Observing and appreciating sculpture and color.", "Acting in a play" ] } }, { "name": "Grade 3", "number":3, "math": { "name":"Math", "themes": [ "Telling time", "Numbers and money into the 100,000's", "Multiplying and dividing numbers from six to nine", "Introduction to geometry, algebra and adding and subtracting number in the thousands", "Practicing mental addition", "Word problems", "Fractions", "Estimation" ] }, "language": { "name": "Language Arts", "themes": [ "Developing and extending basic writing skills spelling rules, word derivations, word roots, parts of a sentence and parts of speech", "Reading biographies of famous people", "Alice's Adventures in Wonderland", "Pollyanna", "Sayings and phrases", "Myths and legends from all lands" ] }, "science": { "name": "Science", "themes": [ "Studying seeds and plants", "The balance of nature", "Pollution", "The brain", "Matter", "Earth's rocks", "Discussion of forces", "Atoms", "Machines", "Metals and electricity in the physical sciences", "Introducing chemistry and astronomy", "Gravity", "The solar system", "Comparing the earth and the moon", "Reading biographies of scientists: John Muir, Jane Goodall, Edward Jenner, and Elijah McCoy" ] }, "social":{ "name": "Social Science", "themes": [ "Reading and using maps", "Globes and graphs", "The history of world civilizations including Ancient Rome, the Byzantine Empire, and Islam", "American Indian civilizations through early English settlements,", "History of the high civilizations of Africa to slavery", "Growth of the American colonies through The Declaration of Independence." ] }, "arts":{ "name": "Fine Arts", "themes": [ "Beginning study of music with instruments", "Percussion, tempo and rhythm", "Developing imagination", "Basic art techniques and art elements including design, mosaic, murals, patterns, lines, colors, quilt making, architecture and puppetry", "Meeting artists including Grandma Moses, George Gershwin, Aaron Copland, Duke Ellington, Diana Ross, Joan Baez, and Georgia O’Keeffe" ] } }, { "name": "Grade 4", "number":4, "math": { "name":"Math", "themes": [ "Studying how to multiply and divide by two-digit numbers", "Three-digit numbers", "Practicing mental arithmetic with emphasis on place value, estimations, and checking of work", "Introducing basic geometry", "Working with decimals", "Roman numerals", "Probability, word problems", "Knowing how to convert units of measurement", "Working with fractions and money" ] }, "language": { "name": "Language Arts", "themes": [ "Developing basic skills in reading", "vocabulary building", "recognizing parts of speech", "usage of subjects and predicate", "correct grammar", "Reading classics by Homer, Shakespeare, Cervantes, Robert Lewis Stevenson, Washington Irving, and Mark Twain", "Legends, speeches, and poetry" ] }, "science": { "name": "Science", "themes": [ "Discussing the history of the earth, rocks, and fossils", "Sources of energy; weather; electricity and magnets", "Fossil fuels", "Hydroelectricity", "Electric power from nuclear fission", "Solar energy", "Geothermal energy", "Health", "Respiratory and circulatory systems", "Personal hygiene", "Introduction to noted scientists." ] }, "social":{ "name": "Social Science", "themes": [ "Focusing on world geography", "Map reading", "Prominent physical features", "Historical events from the Stone Age, through the Middle Ages to the Renaissance", "American history from the Revolution to the Civil War" ] }, "arts":{ "name": "Fine Arts", "themes": [ "Studying music including basic keyboard, chords, and chord progressions", "Famous paintings, artists and cartoonists", "Introduction to architecture and cathedrals", "Masters of art including Brunelleschi, Michelangelo, Raphael, Leonardo da Vinci, Van Eyck, Rembrandt, Jacques-Louis David, and cartoonists including Shultz, Davis and Nash" ] } }, { "name": "Grade 5", "number":5, "math": { "name":"Math", "themes": [ "Reviewing math skills including:", "addition", "multiplication", "division", "mixed numbers", "numbers to billions", "decimals", "tables and graphing", "geometric figures", "multiplying and dividing fractions", "areas", "word problems", "functions", "equations", "ratios" ] }, "language": { "name": "Language Arts", "themes": [ "Comprehension and interpretation in reading fables, myths, non-fiction writing and classics including Tom Sawyer, Julius Caesar, Don Quixote, and Homer's Iliad and Odyssey", "Vocabulary", "Syllables", "Word division", "Capitalization", "Abbreviations", "Parts of speech", "Verb tenses", "Writing poetry", "Original stories" ] }, "science": { "name": "Science", "themes": [ "Studying animal, matter and plant classification", "Reproduction in plants and animals", "Weather and climate patterns", "Photosynthesis", "Physics", "Energy", "Engines", "Electricity", "Power", "Stars", "Earth's structure", "Health and personal hygiene." ] }, "social":{ "name": "Social Science", "themes": [ "Clarifying map skills", "Early American histor including the first explorers, colonization, independence, the Civil War, Reconstruction, expansion into the wild west, immigration", "History of early twentieth century of the United States", "Introducing European history including: the Renaissance, the Reformation, the growth of English power, the Enlightenment, revolutions of France", "Discussing Japan, Russia" ] }, "arts":{ "name": "Fine Arts", "themes": [ "Exploring music", "Harmony", "Melody", "The keyboards", "The orchestra", "Musicians including Mozart, Rossini and Sousa", "The history of painting and biographies of great artists including Ingres, Delacroix, El Greco, Michelangelo, Raphael, and Leonardo de Vinci", "Reviewing architecture including the study of buildings such as The Palace of Versailles, Saint Paul’s Cathedral, Moorish style, and buildings by Inigo Jones, John Soane, Mies van der Rohe, Louis Sullivan, Frank Lloyd Wright, and Walter Gropius", ] } }, { "name": "Grade 6", "number":6, "math": { "name":"Math", "themes": [ "Place value", "Estimation", "Properties", "Division", "Decimals", "Fractions", "Reciprocals", "Expressions", "Exponents", "Exponent notation", "Order of operations", "Frequency tables", "Adding and subtracting units of time", "Percents", "Introduction to geometry", "Integers", "Coordinate graphing" ] }, "language": { "name": "Language Arts", "themes": [ "Improving comprehension and reading using Romeo and Juliet, Oliver Twist, The Secret Garden, Animal Farm, and The Diary of Anne Frank", "Poetry, myths, phrases, sayings and other adventure and mystery classics", "Studying daily vocabulary", "Commonly misspelled words", "How to write original compositions, reports, poetry, friendly and business letters including sentence structure, parts of speech, and research skills" ] }, "science": { "name": "Science", "themes": [ "Examining the classifying of life forms", "Reproduction", "Heredity", "Genetics", "Matter", "Space", "Light", "Sound", "Energy sources", "Body systems", "Crust history", "Electricity", "Chemistry", "Plant reproduction", "Health and personal hygiene", "Introducing scientists" ] }, "social":{ "name": "Social Science", "themes": [ "Studying maps with focus on vegetation, minerals, demographics, weather and economy of Asia, Africa, Australia, New Zealand, and the Pacific Islands", "Examining ancient history including the civilizations of Egypt, Greece, Southwest Asia, Rome, and Europe", "The Middle Ages", "The revolutions of Latin America", "The discovery of Americ", "The industrial revolution", "The British Empire", "Missionaries", "Explorers", "World War I", "The depression", "World War II", "The twentieth century" ] }, "arts":{ "name": "Fine Arts", "themes": [ "Studying the musical keyboard", "Chords", "Patterns in music", "Musicians including Aaron Copland, Mozart, Gershwin, Joplin, Berlin, and Chopin.", "Looking at the visual arts and the artists including Tanner, Homer, van Gogh, Monet, Rodin, Kandinsky, Munch, Picasso, Mondrian, Hopper, Wyeth, and Frank Lloyd Wright", "Examining dance with Stravinsky's Rite of Spring" ] } }, { "name": "Grade 7", "number":7, "math": { "name":"Math", "themes": [ "Math skill review with standard form, exponential form, factors, equalities and inequalities, variables and formulas, prime factorization, square roots, estimating, order of operations, decimals, geometry, the metric system and percents." ] }, "language": { "name": "Language Arts", "themes": [ "Guided reading of children's classics including The Red Pony, biographies, short stories, non-fiction, myths, comprehension and interpretation with daily spelling and vocabulary", "Discussion of descriptive, narrative writing and poetry writing, focusing on the planning and outlining of an essay", "Discussion of diagramming simple, compound and complex sentences with emphasis on punctuation and a review of the parts of speech." ] }, "science": { "name": "Science", "themes": [ "Focus on the scientific method", "Elementary physics", "Solids", "Liquids", "Gases", "Heat", "Magnetism", "Atoms", "Electricity", "Engines", "Inertia", "Fire", "Weather", "Photosynthesis", "Composting", "Friction", "Sound", "Environmental issues", "Health and personal hygiene", ] }, "social":{ "name": "Social Science", "themes": [ "The study of maps", "Climate", "Landforms", "Vegetation", "Minerals", "Rivers", "Economies of Europe, the former Soviet Union, Oceania, Antarctica, Australia, New Zealand, North America, South America, India and Asia." ] }, "arts":{ "name": "Fine Arts", "themes": [ "The art of the theatre", "Music appreciation with a look at great musicians including Haydn, Bach, Rimsky-Korsakov, Mozart, Gershwin, Rachmaninoff, Chopin, Beethoven, and Tchaikovsky", "Appreciation of great visual artists, including Michelangelo, Monet, O'Keeffe, Rembrandt, Cassatt , John Singer Sargent, and Leonardo da Vinci", ] } }, { "name": "Grade 8", "number":8, "math": { "name":"Math", "themes": [ "Problem solving", "Introduction to algebra, exponents and power", "Review of variables, expressions, and equations", "Explore solving division and multiplication equations and two step equations", "Geometry", "Graphs and statistics", "Symmetry", "Prime factorization", "Rational numbers and decimals", "Discussion of square roots, scientific notation, ratio, proportion and percent, and probability." ] }, "language": { "name": "Language Arts", "themes": [ "Guided reading of literary classics of Shakespeare and Arthur Conan Doyle", "improving comprehension and reading of authors: Hemingway, Frost, Isaac Bashevis Singer, Richard Wilbur, Saki, Plath, Keats, and Tennyson", "Introduction to writing the five paragraph essay", "Building spoken, reading and written vocabulary", "Narrative, descriptive and explanatory writing", "Proofreading", "Story writing", "Review of parts of speech" ] }, "science": { "name": "Science", "themes": [ "Review of the scientific method", "Design experiments", "Physics", "States of matter", "The heat and motion connection", "The study of the atom", "The periodic table", "Rational numbers and decimals", "Discussion of organic and inorganic material", "Solutions", "Concentration", "Acids and bases", "Waves", "Frequency and pitch", "The optics of lenses", "Electricity", "Matter", "Energy", "Electricit", "Nuclear sources of energy", ] }, "social":{ "name": "Social Science", "themes": [ "The responsibilities and privileges of citizenship", "The history of America's government", "National, state and local government's responsibilities to citizens", "The political party system", "Voting", "Nominating candidates", "Elections", "How a bill becomes a law", "How the Congress, courts and executive branch of the government work", "How our economic system operates", ] }, "arts":{ "name": "Fine Arts", "themes": [ "History of American home entertainment from the games and songs of the colonists to the computers and iPods of the twenty-first century", "Frescos", "The marches of John Phillip Sousa", "The photography of Brady, Jackson, and Hine." ] } }, { "name": "Grade 9", "number":9, "math": { "name":"Math", "themes": [ "Algebra I: ", "Evaluating Expressions", "Writing Equations and Inequalities", "Math Properties", "History of Algebra", "Equations & Inequalities", "Graphing", "Systems of Equations", "Polynomials", "Radicals" ] }, "language": { "name": "Language Arts", "themes": [ "Grade appropriate vocabulary, reading, writing, and grammar studies, including stories, essays, poems and prose by: ", "O. Henry", "Walt Whitman", "Langston Hughes", "Edgar Allan Poe", "Jack London", "Anton Chekhov", "Shirley Jackson", "Dorothy Canfield Fisher", "William Shakespeare", "Carl Sandburg", "E. E. Cummings", "David Wagoner", "Robert Herrick", "Homer", ] }, "science": { "name": "Science", "themes": [ "Physical & Earth Science: ", "Measurement", "Scientific Methods", "Variables and Control in Experiments", "Atoms and Matter", "Minerals / Crystals", "Technology", "Intro to The Rock Cycle", "Maps / Map Projections", "Landforms", "Soil", "Weathering", "Erosion", "Glaciers", "Wind", "Water Erosion", "Groundwater", "Continental Drift", "Seafloor Spreading", "Plate Tectonics", "Earthquakes", "Volcanoes", "Relative and Absolute Ages of Rocks", "Evolution and Geologic Time", "Early Earth History", "Fossils", "Extinction of Dinosaurs", "Earth's Atmosphere", "The Ozone Layer", "The Water Cycle", "Weather Patterns", "Severe Weather", "Climate & Climate Changes", "Pollution", "Population Impact on the Environment", "Using the Land", "Oceans", "The Moon", "The Solar System", "Radiation from Space", "Electromagnetic Radiation", "Telescopes, Satellites", "Contemporary Issues in Physical & Earth Science" ] }, "social":{ "name": "Social Science", "themes": [ "World History I", "What is History and How is it Understood", "Earliest Civilizations", "Greek Civilization", "Roman Civilization", "Indian Civilization", "Chinese Civilization", "Byzantine Empire", "Islamic Civilization", "African Civilizations", "Pre-Columbian Civilizations of the Americas", "The Fall of Rome and its Effects", "The Late Middle Ages and The Renaissance", "Reformation and The Age of Absolutism", "European Exploration and the Beginnings of Global Trade", "The Effects of European Exploration", "European Colonialism After the Age of Exploration and its Effects", "Revolution in Europe, Russia, Africa, Asia, and Latin America", "World War I and WWII", "The Holocaust", "The Rise of Fascism", "Joseph Stalin", "The Aftermath of World War II and Beyond" ] }, "arts":{ "name": "Fine Arts", "themes": [ "Lascaux Caves", "The Mythical Story of Romulus and Remus and the Naming of Rome", "The Terracotta Army", "The Hagia Sophia", "Tuvan Throat Singing", "West Africa (Benin) in the 16th Century", "Mayan Writing and Hieroglyphics", "Iroquois and the Longhouse", "Byzantine Art", "Giotto and The Gates of Paradise", "Perspective and Perspective Machines", "Inca Architecture", "The Art of Azulejo", "Classical Gardens of Versailles", "Faberge Easter Eggs and the Russian Revolution", "Diego Rivera and Mexican Nationalism", "Art During World War I: A Portrait", "Creating Music During War: Claude Debussy", "Symbolism", "Naum Gabo", "Alberto Giacometti", "Degenerate Art ", "Holocaust Films", "Futurism", "Intonarumori", "Socialist Realism" ] } }, { "name": "Grade 10", "number":10, "math": { "name":"Math", "themes": [ "Geometry: ", "Lines, Line Segments, Rays and Angles", "Angle Measures", "Classifying Angles", "Angle Relationships", "Parallel Lines", "Triangles", "SSS, SAS, ASA, AAS and HL Congruence", "Angle Bisectors", "Medians and Centroids", "Quadrilaterals", "Polygons", "The Pythagorean Theorem", "Solids", "Volume and Surface Area: Prisms", "Spheres", "Circles", "Arcs and Central Angles", "Transformations", "Constructions", "History of Geometry" ] }, "language": { "name": "Language Arts", "themes": [ "Grade appropriate vocabulary, reading, writing, and grammar studies, including:", "Twelve Angry Men", "Animal Farm", "To Kill and Mockingbird", "Cold Equations", "Mr. Parker", "Julius Caesar", "The Pedestrian", "With All Flags Flying", "Of Mice and Men", "Antigone" ] }, "science": { "name": "Science", "themes": [ "Biology: ", "Introduction to Biology", "Branches of Biology", "The Scientific Method", "Matter", "Chemical Reactions", "Water, Mixtures, Solutions, Suspensions", "The Cell Theory", "Cells and their Parts", "DNA", "RNA", "Cell Growth", "Genetics", "Heredity", "The Human Organism", "Food and Nutrition", "Organs", "Development" ] }, "social":{ "name": "Social Science", "themes": [ "American History I:", "The history of the United States from its founding to The Civil War ", "Themes of American democracy, civil rights, liberties, economic development, technology, cultural diversity and family life. " ] }, "arts":{ "name": "Fine Arts", "themes": [ "Global Art Connections I:", "An eclectic look at the history of art including: Islamic art, the architecture of Frank Lloyd Wright, the Baroque, the Impressionists, early Renaissance artists to the greats of the Renaissance. ", "Seventeenth, eighteenth and nineteenth century artists including Rembrandt, Gainsborough, Ingress, Delacroix, Goya, Blake, David, Turner, Constable, Manet, Degas, and Renoir." ] } }, { "name": "Grade 11", "number":11, "math": { "name":"Math", "themes": [ "Algebra II / Statistics:", "Intermediate to advanced algebra skills including expressions, equations, functions, rational numbers, linear equations, proportional reasoning, graphing, polynomials, quadratic and exponential functions." ] }, "language": { "name": "Language Arts", "themes": [ "Guided reading of American literature, including Our Town and Glass Menagerie, with poets, novelists and short story writers' techniques examined ", "Daily spelling and vocabulary", "Persuasive and expository writing and outlining", "Writing grammatically correct essays" ] }, "science": { "name": "Science", "themes": [ "Chemistry / Social Health and Hygiene:", "Chemistry and atoms", "Electrons", "Compounds", "Molecular substances", "The periodic table", "Equations", "Reactions", "Elements", "Gases", "Acids, bases, and pH", "Nuclear and organic chemistry", "Personal and social health and hygiene" ] }, "social":{ "name": "Social Science", "themes": [ "American History II:", "The history of the United States since 1865 ", "Themes of American democracy, civil rights, liberties, economic development, technology, cultural diversity, family life and the United States' role in world affairs" ] }, "arts":{ "name": "Fine Arts", "themes": [ "The History of Painting & The History of Sculpture:", "The history of painting and sculpture during historical moments including: the Parthenon, The Baroque Style of Bernini, The Hudson River School, George Catlin, and Gustave Caillebotte", "The greats of Medieval art including: Fra Filippo Lippi, Francois Duquesnoy, Gregorio Fernandez, Andrea Pisano, and Fra Angelico", "American artists from the nineteenth century", "American artists from the twentieth century" ] } }, { "name": "Grade 12", "number":12, "math": { "name":"Math", "themes": [ "Pre-calculus", "Trigonometric functions", "Graphs", "Equations", "Parametric equations", "Conics", "Exponential and logarithmic functions", "Calculus" ] }, "language": { "name": "Language Arts", "themes": [ "Guided reading of British literature including Macbeth", "World masterpieces including Dante's writing.", "Daily spelling, vocabulary, research and personal writing", "Review of parts of speech", "Online and library research techniques." ] }, "science": { "name": "Science", "themes": [ "Physics:", "Physics", "Vectors", "Motion", "Momentum", "Thermal energy", "Waves", "Sound", "Light electromagnetic induction ", "Quantum theory", "Solid state electronics", "Community health" ] }, "social":{ "name": "Social Science", "themes": [ "Economics:", "Fundamental economic concepts", "Microeconomics", "Macroeconomics", "Economic institutions and policies", "International and global economics" ] }, "arts":{ "name": "Fine Arts", "themes": [ "History of Design: ", "Elements of design including repetition, variety, rhythm, balance, emphasis, economy, controlling attention, viewing angle, viewing distance, conveying an idea, and understanding and valuing what others have created", "Distinguishing between the fine arts and the applied arts", "Designed experiments for line, implied lines, positive and negative areas, descriptive line, shape and form" ] } } ] /* <<<<<<< HEAD ======= >>>>>>> 281450ec975c5af0edd42dbb3b0a6a79d3b73c07 */ //Contenido de graduacionesUSDE.htl app.controller('contentUSDE', function(){ this.content = USDE; }) var USDE = { "titulo":"Graduaciones USDE", "contenido":[ "Todos nuestros estudiantes obtienen certificaciones de estudio o títulos de graduación avalados por el sistema de Educación Americano, lo cual les facilita el ingreso a universidades en USA.", "Además los títulos son validados para el ingreso en cualquier universidad privada dentro del territorio centroamericano.", ], "articulo":{ "titulo": "Entrar a Universidades Americanas", "parrafo":"Contamos con todo el soporte y seguimiento para que nuestros egresados puedan ingresar a la universidad poniendo su disposición programas de refuerzo como TOEFL y SATs." }, "universidades":{ "titulo":"Listado de Universidades", "lista":[ "Adelphi U. NY", "Agnes Scott C. GA", "Albertson C. ID", "Albion C. MI", "Alfred U. NY", "Allegheny C. PA", "Alverno C. WI", "American U. DC", "Amherst C. MA", "Antioch C. OH", "Arizona State U. AZ", "Asbury C. KY", "Assumption C. MA", "Auburn U. AL", "Augustana C. IL", "Austin C. TX", "Baylor U. TX", "Beloit C. WI", "Bemidji State U. MN", "Bennington C. VT", "Berea C. KY", "Berklee C. of Music MA", "Berry C. GA", "Bethany C. WV", "Bethel C. MN", "Biola U. CA", "Birmingham-Southern C. AL", "Boston C. MA", "Boston Conservatory MA", "Boston U. MA", "Bowdoin C. ME", "Bradley U. IL", "Brandeis U. MA", "Brigham Young U. UT", "Brown U. RI", "Bryn Mawr C. PA", "Bucknell U. PA", "Buena Vista U. IA", "Butler U. IN", "California Institute of Technology CA", "California Polytechnic State U. CA", "California State U. Los Angeles CA", "Calvin C. MI", "Capital U. OH", "Carleton C. MN", "Carnegie Mellon U. PA", "Carroll C. MT", "Case Western Reserve U. OH", "Catholic U. of America DC", "Cedarville C. OH", "Central C. IA", "Christian Brothers U. TN", "Claremont McKenna C. CA", "Clemson U. SC", "Coe C. IA", "Colby C. ME", "C. of St. Benedict MN", "C. of St. Scholastica MN", "C. of the Atlantic ME", "C. of William and Mary VA", "C. of Wooster OH", "Colorado C. CO", "Colorado School of Mines CO", "Colorado State U. CO", "Concordia C. Moorhead, MN", "Cornell C. IA", "Cornell U. NY", "Creighton U. NE", "Dartmouth C. NH", "David Lipscomb U. TN", "Davidson C. NC", "Delaware Valley C. PA", "Denison U. OH", "DePaul U. IL", "DePauw U. IN", "Dickinson C. PA", "Drake U. IA", "Drew U. NJ", "Drexel U. PA", "Duke U. NC", "Duquesne U. PA", "Earlham C. IN", "Eckerd C. FL", "Edinboro U. of Pennsylvania PA", "Elizabethtown C. PA", "Emory U. GA", "Evergreen State C. WA", "Fashion Institute of Technology NY", "Florida Institute of Technology FL", "Franciscan U. of Steubenville OH", "Franklin and Marshall C. PA", "George Fox U. OR", "George Mason U. VA", "George Washington U. DC", "Georgetown U. DC", "Georgia Institute of Technology GA", "Gettysburg C. PA", "Goddard C. VT", "Gordon C. MA", "Goshen C. IN", "Goucher C. MD", "Grinnell C. IA", "Grove City C. PA", "Guilford C. NC", "Gustavus Adolphus C. MN", "Hampshire C. MA", "Hanover C. IN", "Harvey Mudd C. CA", "Hastings C. NE", "Haverford C. PA", "Hillsdale C. MI", "Hobart and William Smith Colleges NY", "Hood C. MD", "Hope C. MI", "Houghton C. NY", "Humboldt State U. CA", "Illinois Institute of Technology IL", "Illinois Wesleyan U. IL", "Indiana U., Bloomington IN", "Iowa State U. IA", "Ithaca C. NY", "James Madison U. VA", "John Brown U. AR", "Johns Hopkins U. MD", "Juniata C. PA", "Kalamazoo C. MI", "Kansas State U. KS", "Kenyon C. OH", "Kettering U. MI", "King C. TN", "Knox C. IL", "Lafayette C. PA", "Lake Forest C. IL", "Lawrence U. WI", "LeTourneau U. TX", "Lewis &amp; Clark C. OR", "Linfield C. OR", "Louisiana State U. and Agricultural and Mechanical C. LA", "Loyola C. MD", "Loyola U. Chicago IL", "Luther C. IA", "Macalester C. MN", "Marietta C. OH", "Marlboro C. VT", "Marquette U. WI", "Maryland Institute C. of Art MD", "Maryville C. TN", "Massachusetts Institute of Technology MA", "Messiah C. PA", "Miami U. OH", "Michigan Technological U. MI", "Middlebury C. VT", "Mills C. CA", "Montana State U.--Billings MT", "Montana State U.--Bozeman MT", "Montana Tech of the U. of Montana MT", "Mount Holyoke C. MA", "Muhlenberg C. PA", "Muskingtum C. OH", "New C. of the U. of South Florida FL", "New Mexico Institute of Mining and Technology (New Mexico Tech) NM", "New York U. NY", "North Carolina State U.", "North Central C. IL", "Northwestern C. IA", "Northwestern U. IL", "Oberlin C. OH", "Occidental C. CA", "Oglethorpe U. GA", "Ohio Northern U. OH ", "Ohio State U.: Columbus Campus OH", "Ohio U. OH", "Ohio Wesleyan U. OH", "Oklahoma City U. OK", "Oklahoma State U. OK", "Oregon State U. OR", "Ouachita Baptist U. AR", "Pacific Lutheran U. WA", "Pennsylvania State U. University Park Campus PA", "Pepperdine U. CA", "Philadelphia C. of Pharmacy and Science PA", "Polytechnic U. [yes] NY", "Pomona C. CA", "Princeton U. NJ", "Providence C. RI", "Purdue U. IN", "Radford U. VA", "Reed C. OR", "Regis U. CO", "Rensselaer Polytechnic Institute NY", "Rhode Island School of Design RI", "Rhodes C. TN", "Rice U. TX", "Ripon C. WI", "Rose-Hulman Institute of Technology IN", "Rutgers, State U. of New Jersey, Rutgers C. NJ", "Samford U. AL", "Sarah Lawrence C. NY", "Seattle U. WA", "Seton Hall U. NJ", "Shepherd C. [yes] WV", "Simmons C. MA", "Simon's Rock C. of Bard MA", "Smith C. MA", "Southern Methodist U. TX", "St. Andrews Presbyterian C. NC", "St. John's C. MD &amp; NM", "St. John's U. MN", "St. Joseph's C. ME", "St. Joseph's U. PA", "Saint Mary's C. IN", "St. Mary's C. of Maryland MD", "St. Norbert C. WI", "St. Olaf C. MN", "St. Vincent C. PA", "Stanford U. CA", "State U. of New York at Binghamton NY", "State U. of New York C. at Geneseo NY", "Stephens C. MO", "Stetson U. FL", "Swarthmore C. PA", "Sweet Briar C. VA", "Syracuse U. NY", "Taylor U. IN", "Temple U. PA", "Texas A &amp; M U., College Station TX", "Texas Christian U. TX", "Thomas Aquinas C. CA", "Trinity U. TX", "Tulane U. LA", "Union U. TN", "United States Air Force Academy Colorado Springs, CO", "United States Coast Guard Academy CT", "United States Military Academy West Point, NY", "United States Naval Academy Annapolis, MD", "U. of California: Riverside CA", "U. of California: Santa Cruz CA", "U. of Chicago IL", "U. of Cincinnati OH", "U. of Colorado at Boulder CO", "U. of Connecticut CT", "U. of Dallas TX", "U. of Dayton OH", "U. of Delaware DE", "U. of Denver CO", "U. of Evansville IN", "U. of Florida FL", "U. of Georgia GA", "U. of Idaho ID", "U. of Illinois IL", "U. of Iowa IA", "U. of Kansas KS", "U. of Kentucky KY", "U. of Maine, Farmington ME", "U. of Maine ME", "U. of Maryland MD", "U. of Massachusetts Amherst MA", "U. of Miami FL ", "U. of Michigan MI", "U. of Minnesota, Morris MN", "U. of Minnesota, Twin Cities MN", "U. of Missouri-Columbia MO", "U. of Missouri-Kansas City MO", "U. of Missouri-Rolla MO", "U. of Montana MT", "U. of Nebraska-Lincoln NE", "U. of New Hampshire NH", "U. of North Carolina at Asheville NC", "U. of North Carolina NC", "U. of North Dakota ND", "U. of Notre Dame IN", "U. of Oklahoma OK", "U. of Oregon OR", "U. of Pennsylvania PA", "U. of Pittsburgh PA ", "U. of Puget Sound WA", "U. of Redlands CA", "U. of Rhode Island RI", "U. of Rochester NY", "U. of St. Thomas MN", "U. of San Francisco CA", "U. of Southern California CA", "U. of Tennessee TN", "U. of Texas at Austin TX", "U. of the South", "U. of Utah UT", "U. of Vermont VT", "U. of Virginia VA", "U. of Washington WA", "U. of Wisconsin--Madison WI", "U. of Wyoming WY", "Ursinus C. PA", "Valparaiso U. IN", "Vanderbilt U. TN", "Vassar C. NY", "Villanova U. PA", "Virginia Polytechnic Institute and State U. VA", "Wabash C. IN", "Warren Wilson C. NC", "Wartburg C. IA", "Washington C. MD", "Washington U. MO", "Wellesley C. MA", "Wells C. NY", "Wesleyan U. CT", "West Virginia Wesleyan C. WV", "Westminster Choir C. of Rider U. NJ", "Westminster C. MO", "Wheaton C. IL", "Wheaton C. MA", "Whitman C. WA", "Whittier C. CA", "Willamette U. OR", "William Jewell C. MO", "Williams C. MA", "Wingate U. NC", "Winona State U. MN", "Wittenberg U. OH", "Wofford C. S ", "Yale U. CT" ] } };
'use strict'; // Base error class for further extending class ExtendableError extends Error { constructor(message) { super(message); this.name = this.constructor.name; Error.captureStackTrace(this, this.constructor.name); } } module.exports = ExtendableError;
/* Version: 16.0.6216.3006 */ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* Your use of this file is governed by the Microsoft Services Agreement http://go.microsoft.com/fwlink/?LinkId=266419. */ /// <reference path="outlook-win32.debug.js" /> Office._ExcelMask = 0x1; Office._WordMask = 0x2; Office._ProjectMask = 0x4; Office._OutlookMask = 0x8; Office._PowerPointMask = 0x10; Office._OutlookComposeMask = 0x20; Office._AccessWebAppMask = 0x40; { Office._extractedCallback = function (originalArgs, totalArgsCount, optionalArgsCount) { var optionalArgs = Array.prototype.slice.call(originalArgs, totalArgsCount - optionalArgsCount); var callback = function(){}; for (var i = Math.min(optionalArgs.length, optionalArgsCount) - 1; i >= 0; i--) { if (typeof optionalArgs[i] == "function") { callback = optionalArgs[i]; break; } } return callback; } Office._BindingDataChangedEvents = function (eventType) { this.binding = new Office._Binding(bindingType); this.type = eventType; this.startColumn = {}; this.startRow = {}; } Office._DocumentEventArgs = function (eventType) { Office._processContents(this, { type: { annotate: { /// <field type="Office.EventType"></field> type: undefined }, value: eventType } }); if (eventType == "activeViewChanged") { Office._processItem( this, { annotate: { /// <field type="Office.ActiveView"></field> activeView: undefined } }, "activeView" ); } } Office._CustomXmlNodeEvents = function (eventType) { this.type = eventType; this.inUndoRedo = {}; if (eventType == 'nodeDeleted') { this.oldNode = new Office._CustomXmlNode(); this.oldNextSibling = new Office._CustomXmlNode(); } if (eventType == 'nodeInserted') { this.newNode = new Office._CustomXmlNode(); } if (eventType == 'nodeReplaced') { this.oldNode = new Office._CustomXmlNode(); this.newNode = new Office._CustomXmlNode(); } } Office._Error = function () { this.id = {}; this.message = {}; this.name = {}; } Office._CustomXmlNode = function () { this.baseName = {}; this.namespaceUri = {}; this.nodeType = {}; this.getNodesAsync = function (xPath, callback) { ///<summary> Gets the nodes associated with the xPath expression. </summary> ///<param name="xPath" type="string">The xPath expression</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getNodesAsync"); callback(result); }; this.getNodeValueAsync = function (callback) { ///<summary> Gets the node value. </summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getNodeValueAsync"); callback(result); }; this.getXmlAsync = function (callback) { ///<summary> Gets the node's XML. </summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getXmlAsync"); callback(result); }; this.setNodeValueAsync = function (value, callback) { ///<summary> Sets the node value. </summary> ///<param name="value" type="string">The value to be set on the node</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("setNodeValueAsync"); callback(result); }; this.setXmlAsync = function (xml, callback) { ///<summary> Sets the node XML. </summary> ///<param name="xml" type="string">The XML to be set on the node</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("setXmlAsync"); callback(result); }; } Office._context_document_customXmlParts_customXmlPrefixMappings = function () { this.addNamespaceAsync = function (prefix, nsUri, callback) { ///<summary>Adds a namespace. </summary> //////<param name="prefix" type="string">The namespace prefix</param> //////<param name="nsUri" type="string">The namespace URI</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("addNamespaceAsync"); callback(result); }; this.getNamespaceAsync = function (prefix, callback) { ///<summary> Gets a namespace with the specified prefix </summary> ///<param name="prefix" type="string">The namespace prefix</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getNamespaceAsync"); callback(result); }; this.getPrefixAsync = function (nsUri, callback) { ///<summary> Gets a prefix for the specified URI </summary> ///<param name="nsUri" type="string">The namespace URI</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getPrefixAsync"); callback(result); }; } Office._CustomXmlPart = function () { this.builtIn = {}; this.id = {}; this.namespaceManager = new Office._context_document_customXmlParts_customXmlPrefixMappings(); this.deleteAsync = function (callback) { ///<summary> Deletes the Custom XML Part. </summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("deleteAsync"); callback(result); }; this.getNodesAsync = function (xPath, callback) { ///<summary> Gets the nodes associated with the xPath expression. </summary> ///<param name="xPath" type="string">The xPath expression</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getNodesAsync"); callback(result); }; this.getXmlAsync = function (callback) { ///<summary> Gets the XML for the Custom XML Part. </summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getXmlAsync"); callback(result); }; this.addHandlerAsync = function (eventType, handler, callback) { ///<summary> Adds an event handler to the object using the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For CustomXmlPartNode it can be 'nodeDeleted', 'nodeInserted' or 'nodeReplaced' </param> ///<param name="handler" type="function">The name of the handler </param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var events = new Office._CustomXmlNodeEvents(eventType); handler(events); var result = new Office._AsyncResult("addHandlerAsync"); callback(result); }; this.removeHandlerAsync = function (eventType, options, callback) { ///<summary> Removes an event handler from the object using the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For CustomXmlPartNode it can be 'nodeDeleted', 'nodeInserted' or 'nodeReplaced' </param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {handler:eventHandler} /// &#10; handler: Indicates a specific handler to be removed, if not specified all handlers are removed /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> /// Office._extractedCallback(arguments, 3, 2)(new Office._AsyncResult("removeHandlerAsync")); } } Office._Binding = function (bindingType) { ///<field type="String" name="id">Id of the Binding</field>}; this.id = {}; this.type = {}; this.document = {}; this.setDataAsync = function (data, options, callback) { ///<summary> Writes the specified data into the current selection.</summary> ///<param name="data" type="Object">The data to be set. Either a string or value, 2d array or TableData object</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {coercionType:Office.CoercionType.Matrix} or {coercionType: 'matrix'} /// &#10; coercionType: Explicitly sets the shape of the data object. Use Office.CoercionType or text value. If not supplied is inferred from the data type. /// &#10; startRow: Used in partial set for table/matrix. Indicates the start row. /// &#10; startColumn: Used in partial set for table/matrix. Indicates the start column. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 3, 2)(new Office._AsyncResult("setDataAsync")); }; this.getDataAsync = function (options, callback) { ///<summary> Returns the current selection.</summary> ///<param name="options" type="Object" optional="true"> /// Syntax example: {coercionType: 'matrix,'valueFormat: 'formatted', filterType:'all'} /// &#10; coercionType: The expected shape of the selection. If not specified returns the bindingType shape. Use Office.CoercionType or text value. /// &#10; valueFormat: Get data with or without format. Use Office.ValueFormat or text value. /// &#10; startRow: Used in partial get for table/matrix. Indicates the start row. /// &#10; startColumn: Used in partial get for table/matrix. Indicates the start column. /// &#10; rowCount: Used in partial get for table/matrix. Indicates the number of rows from the start row. /// &#10; columnCount: Used in partial get for table/matrix. Indicates the number of columns from the start column. /// &#10; filterType: Get the visible or all the data. Useful when filtering data. Use Office.FilterType or text value. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 1) { callback = options; } var result = new Office._AsyncResult("getDataAsync", options.coercionType); callback(result); }; this.addHandlerAsync = function (eventType, handler, callback) { ///<summary> Adds an event handler to the object using the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For binding it can be 'bindingDataChanged' and 'bindingSelectionChanged' </param> ///<param name="handler" type="function">The name of the handler </param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var events = new Office._BindingDataChangedEvents(eventType); handler(events); var result = new Office._AsyncResult("addHandlerAsync"); callback(result); }; this.removeHandlerAsync = function (eventType, options, callback) { ///<summary> Removes an event handler from the object using the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For binding can be 'bindingDataChanged' and 'bindingSelectionChanged' </param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {handler:eventHandler} /// &#10; handler: Indicates a specific handler to be removed, if not specified all handlers are removed /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var events = new Office._BindingDataChangedEvents(eventType); handler(events); Office._extractedCallback(arguments, 3, 2)(new Office._AsyncResult("removeHandlerAsync")); }; if ((bindingType == undefined) || (bindingType == Office.BindingType.Matrix) || (bindingType == Office.BindingType.Table)) { this.columnCount = {}; this.rowCount = {}; } if ((bindingType == undefined) || (bindingType == Office.BindingType.Table)) { Office._processContents(this, { hasHeaders: { value: {} }, addRowsAsync: { value: function (data, callback) { ///<summary> Adds the specified rows to the table </summary> ///<param name="data" type="Object"> A 2D array with the rows to add </param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, addColumnsAsync: { value: function (tableData, callback) { ///<summary> Adds the specified columns to the table </summary> ///<param name="tableData" type="Object"> A TableData object with the headers and rows </param> ///<param name="callback" type="function" optional="true">The optional callback method</param>}; } }, deleteAllDataValuesAsync: { value: function (callback) { ///<summary> Clears the table</summary> ///<param name="callback" type="function" optional="true">The optional callback method</param>}; } }, formattingSpecific: { metaOnly: true, conditions: { hosts: ["excel"], }, contents: { clearFormatsAsync: { conditions: { reqs: ["method TableBinding.clearFormatsAsync"] }, value: function (options, callback) { ///<summary> Clears formatting on the bound table. </summary> ///<param name="options" type="Object" optional="true"> /// Syntax example: {asyncContext:context} /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 2, 2)(new Office._AsyncResult("clearFormatsAsync")); } }, getFormatsAsync: { conditions: { reqs: ["method TableBinding.getFormatsAsync"] }, value: function (cellReference, formats, options, callback) { ///<summary> Gets the formatting on specified items in the table. </summary> ///<param name="cellReference" type="Object" optional="true">An object literal containing name-value pairs that specify the range of cells to get formatting from.</param> ///<param name="formats" type="Array" optional="true">An array specifying the format properties to get.</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {asyncContext:context} /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 4, 4)(new Office._AsyncResult("getFormatsAsync")); } }, setFormatsAsync: { conditions: { reqs: ["method TableBinding.setFormatsAsync"] }, value: function (formatsInfo, options, callback) { ///<summary> Sets formatting on specified items and data in the table. </summary> ///<param name="formatsInfo" type="Array" elementType="Array" optional="true"> /// Array elements are themselves three-element arrays: /// [target, type, formats] /// &#10; target: The identifier of the item to format. String. /// &#10; type: The kind of item to format. String. /// &#10; formats: An object literal containing a list of property name-value pairs that define the formatting to apply. ///</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {asyncContext:context} /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 3, 3)(new Office._AsyncResult("setFormatsAsync")); } }, setTableOptionsAsync: { conditions: { reqs: ["method TableBinding.setTableOptionsAsync"] }, value: function (tableOptions, options, callback) { ///<summary> Updates table formatting options on the bound table. </summary> ///<param name="tableOptions" type="Object">An object literal containing a list of property name-value pairs that define the table options to apply.</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {asyncContext:context} /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 3, 2)(new Office._AsyncResult("setTableOptionsAsync")); } } } } }); } } Office._TableData = function () { this.headers = new Array(new Array()); this.rows = new Array(new Array()); } Office._File = function () { this.size = {}; this.sliceCount = {}; this.getSliceAsync = function (sliceIndex, callback) { ///<summary> Gets the specified slice. </summary> ///<param name="sliceIndex" type="Integer">The index of the slice to be retrieved </param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getSliceAsync"); callback(result); }; this.closeAsync = function (callback) { ///<summary> Closes the File. </summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> }; } Office._Slice = function () { this.data = {}; this.index = {}; this.size = {}; } Office._AsyncResult = function (method, bindingType) { this.asyncContext = {}; this.error = new Office._Error(); this.status = {}; if ((method == "addfromSelectionAsync") || (method == "addFromNamedItemAsync") || (method == "getByIdAsync") || (method == "addFromPromptAsync")) { this.value = new Office._Binding(bindingType); } else if ((method == "getDataAsync") || (method == "getSelectedDataAsync")) { if (bindingType == "table") this.value = new Office._TableData(); else if (bindingType == "matrix") this.value = new Array(new Array); else this.value = {}; } else if (method == "getAllAsync") { this.value = new Array(new Office._Binding(bindingType)); } else if (method == "getByNamespaceAsync") { this.value = new Array(new Office._CustomXmlPart()); } else if (method == "getNodesAsync") { this.value = new Array(new Office._CustomXmlNode()); } else if ((method == "XMLgetByIdAsync") || (method == "addAsync")) { this.value = new Office._CustomXmlPart(); } else if (method == "refreshAsync") { this.value = new Office._context_document_settings(); } else if (method == "getFileAsync") { this.value = new Office._File(); } else if (method == "getSliceAsync") { this.value = new Office._Slice(); } else if (method == "getActiveViewAsync") { Office._processItem(this, { annotate: { ///<field type="String">The presentation's current view.</field> value: undefined } }, "value" ); } else if (method == "getFilePropertiesAsync") { this.value = new Office._FileProperties(); } else { this.value = {}; } } Office._FileProperties = function () { ///<field type="String" name="url">File's URL</field> this.url = ""; } Office._context_document_settings = function () { this.get = function (settingName) { ///<summary>Retrieves the setting with the specified name.</summary> ///<param name="settingName" type="string">The name of the setting </param> }; this.remove = function (settingName) { ///<summary>Removes the setting with the specified name.</summary> ///<param name="settingName" type="string">The name of the setting </param> /// }; this.saveAsync = function (options, callback) { ///<summary>Saves all settings.</summary> ///<param name="options" type="Object" optional="true"> /// Syntax example: {overwriteIfStale:false} /// &#10; overwriteIfStale: Indicates whether the setting will be replaced if stale. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> /// Office._extractedCallback(arguments, 2, 2)(new Office._AsyncResult("saveAsync", coercionType)); }; this.set = function (settingName, value) { ///<summary>Sets a value for the setting with the specified name.</summary> ///<param name="settingName" type="string">The name of the setting</param> ///<param name="value" type="object">The value for the setting</param> }; }; Office._context_document_bindings = function () { this.document = {}; if (Office._AccessWebAppMask & Office._appContext) { this.addFromSelectionAsync = function (bindingType, options, callback) { ///<summary>Create a binding based on what the user's current selection.</summary> ///<param name="bindingType" type="Office.BindingType">The Office BindingType for the data</param> ///<param name="options" type="Object" optional="true"> /// addFromSelectionAsyncOptions- e.g. {id: "BindingID"} /// &#10; id: Identifier. /// &#10; asyncContext: Object keeping state for the callback /// &#10; columns: The string[] of the columns involved in the binding /// &#10; sampleData: A TableData that gives sample table in the Dialog.TableData.Headers is [][] of string. ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 2) { callback = options; }; var result = new Office._AsyncResult("addfromSelectionAsync", bindingType); callback(result); } } else { this.addFromSelectionAsync = function (bindingType, options, callback) { ///<summary>Create a binding based on what the user's current selection.</summary> ///<param name="bindingType" type="Office.BindingType">The Office BindingType for the data</param> ///<param name="options" type="Object" optional="true"> /// addFromSelectionAsyncOptions- e.g. {id: "BindingID"} /// &#10; id: Identifier. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 2) { callback = options; }; var result = new Office._AsyncResult("addfromSelectionAsync", bindingType); callback(result); } } if (Office._AccessWebAppMask & Office._appContext) { this.addFromNamedItemAsync = function (itemName, bindingType, options, callback) { ///<summary>Creates a binding against a named object in the document</summary> ///<param name="itemName" type="String">Name of the bindable object in the document. For Example 'MyExpenses' table in Excel." </param> ///<param name="bindingType" type="Office.BindingType">The Office BindingType for the data</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {id: "BindingID"} /// &#10; id: Name of the binding, autogenerated if not supplied. /// &#10; asyncContext: Object keeping state for the callback /// &#10; columns: The string[] of the columns involved in the binding ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 3) { callback = options; }; var result = new Office._AsyncResult("addFromNamedItemAsync", bindingType); callback(result); } } else { this.addFromNamedItemAsync = function (itemName, bindingType, options, callback) { ///<summary>Creates a binding against a named object in the document</summary> ///<param name="itemName" type="String">Name of the bindable object in the document. For Example 'MyExpenses' table in Excel." </param> ///<param name="bindingType" type="Office.BindingType">The Office BindingType for the data</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {id: "BindingID"} /// &#10; id: Name of the binding, autogenerated if not supplied. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 3) { callback = options; }; var result = new Office._AsyncResult("addFromNamedItemAsync", bindingType); callback(result); } } this.getByIdAsync = function (id, callback) { ///<summary>Retrieves a binding based on its Name</summary> ///<param name="id" type="String">The binding id</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getByIdAsync") callback(result); } this.getAllAsync = function (callback) { ///<summary>Gets an array with all the binding objects in the document.</summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("getAllAsync") callback(result); }; this.releaseByIdAsync = function (id, callback) { ///<summary>Removes the binding from the document</summary> ///<param name="id" type="String">The binding id</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("releaseByIdAsync") callback(result); }; if (Office._AccessWebAppMask & Office._appContext) { this.addFromPromptAsync = function (bindingType, options, callback) { ///<summary>(Access only with sample data) Create a binding by prompting the user to make a selection on the document.</summary> ///<param name="bindingType" type="Office.BindingType">The Office BindingType for the data</param> ///<param name="options" type="Object" optional="true"> /// addFromPromptAsyncOptions- e.g. {promptText: "Please select data", id: "mySales"} /// &#10; promptText: Greet your users with a friendly word. /// &#10; asyncContext: Object keeping state for the callback /// &#10; id: Identifier. /// &#10; sampleData: A TableData that gives sample table in the Dialog.TableData.Headers is [][] of string. ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 2) { callback = options; }; var result = new Office._AsyncResult("addFromPromptAsync", bindingType) callback(result); } } else if (Office._ExcelMask & Office._appContext) { this.addFromPromptAsync = function (bindingType, options, callback) { ///<summary>(Excel only) Create a binding by prompting the user to make a selection on the document.</summary> ///<param name="bindingType" type="Office.BindingType">The Office BindingType for the data</param> ///<param name="options" type="Object" optional="true"> /// addFromPromptAsyncOptions- e.g. {promptText: "Please select data", id: "mySales"} /// &#10; promptText: Greet your users with a friendly word. /// &#10; asyncContext: Object keeping state for the callback /// &#10; id: Identifier. ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 2) { callback = options; }; var result = new Office._AsyncResult("addFromPromptAsync", bindingType) callback(result); } } }; Office._context_document = { mode: { annotate: { //Gets the document mode mode: undefined } }, url: { annotate: { //Gets the document URL url: undefined } }, addHandlerAsync: { value: function (eventType, handler, callback) { ///<summary> Adds an event handler for the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For document can be 'DocumentSelectionChanged' </param> ///<param name="handler" type="function">The name of the handler </param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("addHandlerAsync"); callback(result); handler(new Office._DocumentEventArgs(eventType)); } }, removeHandlerAsync: { value: function (eventType, handler, callback) { ///<summary> Removes an event handler for the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For document can be 'DocumentSelectionChanged' </param> ///<param name="handler" type="function" optional="true">The name of the handler. If not specified all handlers are removed </param> ///<param name="callback" type="function" optional="true">The optional callback method</param> /// var result = new Office._AsyncResult("removeHandlerAsync", coercionType); callback(result); } }, settings: { conditions: { hosts: ["word", "excel", "ppt", "accesswebapp"], reqs: [ "set Settings GE 1.1", "method Settings.get", "method Settings.remove", "method Settings.saveAsync", "method Settings.set" ] }, value: new Office._context_document_settings() }, refreshableSettings: { name: "settings", conditions: { hosts: ["excel", "ppt", "accesswebapp"], reqs: [] }, partialConditions: true, contents: { addHandlerAsync: { conditions: { reqs: ["method Settings.addHandlerAsync"] }, value: function (eventType, handler, callback) { ///<summary> Adds an event handler for the object using the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For settings can be 'settingsChanged' </param> ///<param name="handler" type="function">The name of the handler </param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("addHandlerAsync", coercionType); callback(result); } }, refreshAsync: { conditions: { reqs: ["method Settings.refreshAsync"] }, value: function (callback) { ///<summary>Gets the latest version of the settings object.</summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("refreshAsync", coercionType); callback(result); } }, removeHandlerAsync: { conditions: { reqs: ["method Settings.removeHandlerAsync"] }, value: function (eventType, handler, callback) { ///<summary> Removes an event handler for the specified event type. </summary> ///<param name="eventType" type="Office.EventType">The event type. For settings can be 'settingsChanged' </param> ///<param name="handler" type="Object" optional="true"> /// Syntax example: {handler:eventHandler} /// &#10; handler: Indicates a specific handler to be removed, if not specified all handlers are removed /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> var result = new Office._AsyncResult("removeHandlerAsync", coercionType); callback(result); } } } }, setSelectedDataAsync: { conditions: { hosts: ["word", "excel", "ppt"], reqs: ["set Selection GE 1.1", "method Document.setSelectedDataAsync"] }, value: function (data, options, callback) { ///<summary> Writes the specified data into the current selection.</summary> ///<param name="data" type="Object">The data to be set. Either a string or value, 2d array or TableData object</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {coercionType:Office.CoercionType.Matrix} or {coercionType: 'matrix'} /// &#10; coercionType: Explicitly sets the shape of the data object. Use Office.CoercionType or text value. If not supplied is inferred from the data type. /// &#10; imageLeft: Used for image. Sets the left position of the image. /// &#10; imageTop: Used for image. Sets the top position of the image. /// &#10; imageWidth: Used for image. Sets the width of the image. /// &#10; imageHeight: Used for image. Sets the height of the image. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> /// if (arguments.length == 2) { callback = options; }; var result = new Office._AsyncResult("setSelectedDataAsync"); callback(result); } }, bindings: { conditions: { hosts: ["word", "excel", "accesswebapp"], reqs: [ "set TextBindings GE 1.1", "set TableBindings GE 1.1", "set MatrixBindings GE 1.1", "method Bindings.addFromPromptAsync", "method Bindings.addFromNamedItemAsync", "method Bindings.addFromSelectionAsync", "method Bindings.getAllAsync", "method Bindings.getByIdAsync", "method Bindings.releaseByIdAsync", "method MatrixBinding.getDataAsync", "method MatrixBinding.setDataAsync", "method TableBinding.clearFormatsAsync", "method TableBinding.setFormatsAsync", "method TableBinding.setTableOptionsAsync", "method TableBinding.addColumnsAsync", "method TableBinding.addRowsAsync", "method TableBinding.deleteAllDataValuesAsync", "method TableBinding.getDataAsync", "method TableBinding.setDataAsync", "method TextBinding.getDataAsync", "method TextBinding.setDataAsync" ] }, value: new Office._context_document_bindings() }, getFileAsync: { conditions: { hosts: ["word", "ppt","excel"], reqs: ["set File GE 1.1", "method Document.getFileAsync", "method File.closeAsync", "method File.getSliceAsync"] }, value: function (fileType, options, callback) { ///<summary>(Word and PowerPoint only) Gets the entire file in slices of up to 4MB.</summary> ///<param name="fileType" type="Office.FileType">The format in which the file will be returned</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {sliceSize:1024} /// &#10; sliceSize: Specifies the desired slice size (in bytes) up to 4MB. If not specified a default slice size of 4MB will be used. ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> if (arguments.length == 2) { callback = options; }; var result = new Office._AsyncResult("getFileAsync"); callback(result); } }, getSelectedDataAsync: { conditions: { hosts: ["excel", "word", "project", "ppt"], reqs: ["set Selection GE 1.1", "method Document.getSelectedDataAsync"] }, value: function (coercionType, options, callback) { ///<summary> Returns the current selection.</summary> ///<param name="coercionType" type="Office.CoercionType">The expected shape of the selection.</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {valueFormat: 'formatted', filterType:'all'} /// &#10; valueFormat: Get data with or without format. Use Office.ValueFormat or text value. /// &#10; filterType: Get the visible or all the data. Useful when filtering data. Use Office.FilterType or text value. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> /// if (arguments.length == 2) { callback = options; }; var result = new Office._AsyncResult("getSelectedDataAsync", coercionType); callback(result); } }, customXmlParts: { conditions: { hosts: ["word"], reqs: [ "set CustomXmlParts GE 1.1", "method CustomXmlNode.getNodesAsync", "method CustomXmlNode.getNodeValueAsync", "method CustomXmlNode.getXmlAsync", "method CustomXmlNode.setNodeValueAsync", "method CustomXmlNode.setXmlAsync", "method CustomXmlPart.addHandlerAsync", "method CustomXmlPart.deleteAsync", "method CustomXmlPart.getNodesAsync", "method CustomXmlPart.getXmlAsync", "method CustomXmlPart.removeHandlerAsync", "method CustomXmlPrefixMappings.addNamespaceAsync", "method CustomXmlPrefixMappings.getNamespaceAsync", "method CustomXmlPrefixMappings.getPrefixAsync" ] }, partialConditions: true, contents: { addAsync: { conditions: { reqs: ["method CustomXmlParts.addAsync"] }, value: function (xml, callback) { ///<summary>(Word Only) Asynchronously adds a new custom XML part to a file.</summary> ///<param name="xml" type="String">The XML to add to the newly created custom XML part.</param> ///<param name="callback" type="function" optional="true">A function that is invoked when the callback returns, whose only parameter is of type AsyncResult.</param> var result = new Office._AsyncResult("addAsync"); callback(result); } }, getByIdAsync: { conditions: { reqs: ["method CustomXmlParts.getByIdAsync"] }, value: function (id, callback) { ///<summary>(Word Only) Asynchronously gets the specified custom XML part by its id.</summary> ///<param name="id" type="String">The id of the custom XML part.</param> ///<param name="callback" type="function" optional="true">A function that is invoked when the callback returns, whose only parameter is of type AsyncResult.</param> var result = new Office._AsyncResult("XMLgetByIdAsync"); callback(result); } }, getByNamespaceAsync: { conditions: { reqs: ["method CustomXmlParts.getByNamespaceAsync"] }, value: function (ns, callback) { ///<summary>(Word Only) Asynchronously gets the specified custom XML part(s) by its namespace. </summary> ///<param name="ns" type="String"> The namespace to search.</param> ///<param name="callback" type="function" optional="true">A function that is invoked when the callback returns, whose only parameter is of type AsyncResult.</param> var result = new Office._AsyncResult("getByNamespaceAsync"); callback(result); } } } }, getActiveViewAsync: { conditions: { hosts: ["ppt"], reqs: ["set ActiveView GE 1.1", "method Document.getActiveViewAsync"] }, value: function(options, callback) { ///<summary>(PowerPoint only) Returns the current view of the presentation.</summary> ///<param name="options" type="Object" optional="true"> /// Syntax example: {asyncContext:context} /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 2, 2)(new Office._AsyncResult("getActiveViewAsync")); } }, getFilePropertiesAsync: { conditions: { hosts: ["word", "ppt", "excel"], reqs: ["method Document.getFilePropertiesAsync"] }, value: function(options, callback) { ///<summary>Gets file properties of the current document.</summary> ///<param name="options" type="Object" optional="true"> /// Syntax example: {asyncContext:context} /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 2, 2)(new Office._AsyncResult("getFilePropertiesAsync")); } }, goToByIdAsync: { conditions: { hosts: ["excel", "ppt", "word"], reqs: ["method Document.goToByIdAsync"] }, value: function(id, goToType, options, callback) { ///<summary>Goes to the specified object or location in the document.</summary> ///<param name="id" type="String or Number">The identifier of the object or location to go to.</param> ///<param name="goToType" type="Office.GoToType">The type of the location to go to.</param> ///<param name="options" type="Object" optional="true"> /// Syntax example: {asyncContext:context} /// &#10; selectionMode: (Word only) Use Office.SelectionMode or text value. /// &#10; asyncContext: Object keeping state for the callback ///</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> Office._extractedCallback(arguments, 4, 2)(new Office._AsyncResult("goToByIdAsync")); } } } } Office._items = { context: { contents: { contentLanguage: {}, displayLanguage: {}, license: { contents: { value: { annotate: { //License summary. value: undefined } } } }, document: { conditions: { hosts: ["not outlook; not outlookcompose"] }, annotate: { // Office Document document: undefined }, contents: Office._context_document }, officeTheme: { conditions: { hosts: ["excel", "outlook", "powerpoint", "project", "word"] }, annotate: { officeTheme: undefined }, contents: { "bodyBackgroundColor": {}, "bodyForegroundColor": {}, "controlBackgroundColor": {}, "controlForegroundColor": {} } }, touchEnabled: {}, commerceAllowed : {}, requirements: { annotate: { // Checks whether a given requirement set is supported by the current host. requirements: undefined }, contents: { isSetSupported: { value: function (name, minVersion) { ///<summary> Check if the specified requirement set is supported by the host Office application </summary> ///<param name="name" type="String"> Set name. e.g.: "MatrixBindings" </param> ///<param name="minVersion" type="Number"> The minimum required version </param> } }, } } } }, initialize: { value: function (reason) { ///<summary> This method is called after the Office API was loaded.</summary> ///<param name="reason" type="Office.InitializationReason" optional="true"> Indicates how the app was initialized</param> } }, useShortNamespace: { value: function (useShortNamespace) { ///<summary> Indicates if the large namespace for objects will be used or not.</summary> ///<param name="useShortNamespace" type="boolean"> Indicates if 'true' that the short namespace will be used</param> } }, select: { conditions: { hosts: ["not outlook; not outlookcompose"] }, value: function (expression, callback) { ///<summary> Returns a promise of an object described in the expression. Callback is invoked only if method fails.</summary> ///<param name="expression" type="string">The object to be retrieved. Example "bindings#BindingName", retrieves a binding promise for a binding named 'BindingName'</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> /// var result = new Office._AsyncResult("select"); callback(result); return (new Office._Binding()); } }, TableData: { conditions: { hosts: ["word", "excel", "accesswebapp"], reqs: ["set TableBindings GE 1.1"] }, value: new Office._TableData() } }; /*Infrastructure***************************************************************/ Office._processItem = function (target, item, key, suppressConditionCheck) { var conditionsFulfilled = suppressConditionCheck || Office._filterManager._checkCondition(item.conditions); if (!(conditionsFulfilled || item.partialConditions)) { return false; } suppressConditionCheck = suppressConditionCheck || conditionsFulfilled && item.partialConditions; if (item.setup) { item.setup(); } if (item.metaOnly) { return Office._processContents(target, item.contents, suppressConditionCheck); } key = item.name || key; var areItemsAdded = false; if (item.hasOwnProperty("value")) { target[key] = item.value; areItemsAdded = true; } else if (typeof item.contents == "function") { target[key] = item.contents(); areItemsAdded = true; } else { target[key] = target[key] || {}; if (Office._processContents(target[key], item.contents, suppressConditionCheck) || conditionsFulfilled) { areItemsAdded = true; } else { delete target[key]; } } if (item.annotate) { intellisense.annotate(target, item.annotate); areItemsAdded = true; } return areItemsAdded; } Office._processContents = function (target, contents, suppressConditionCheck) { if (typeof contents !== "object") { return false; } var areItemsAdded = false; for (var item in contents) { areItemsAdded = Office._processItem(target, contents[item], item, suppressConditionCheck) || areItemsAdded; } return areItemsAdded; } Office._filterManager = (function () { var filters = []; return { _checkCondition: function (condition) { if (!condition) return true; var answer = true; for (var i = 0; i < filters.length; i++) { var filter = filters[i]; var conditionForThisFilter = condition[filter.identifier]; if (conditionForThisFilter && filter.isEnabled()) { var thisFiltersAnswer = false; for (var j = 0; j < conditionForThisFilter.length; j++) { var productTerm = conditionForThisFilter[j].split(';'); var thisTermsAnswer = true; for (var k = 0; k < productTerm.length; k++) { var singleCondition = productTerm[k].toUpperCase().trim(); var invert = false; if (singleCondition.indexOf("NOT") != -1) { invert = true; singleCondition = singleCondition.slice(singleCondition.indexOf(" ")).trim(); } var result = filter.isConditionTrue(singleCondition, invert); thisTermsAnswer = thisTermsAnswer && result; } thisFiltersAnswer = thisFiltersAnswer || thisTermsAnswer; } answer = answer && thisFiltersAnswer; } if (!answer) break; } return answer; }, _pushFilter: function (identifier, filteringDelegate, isEnabledDelegate) { filters.push({ identifier: identifier, isConditionTrue: filteringDelegate, isEnabled: isEnabledDelegate }); } } })(); Office._filterManager._pushFilter( "hosts", (function () { var nameToMaskMapping = { EXCEL: Office._ExcelMask, WORD: Office._WordMask, PROJECT: Office._ProjectMask, OUTLOOK: Office._OutlookMask, PPT: Office._PowerPointMask, OUTLOOKCOMPOSE: Office._OutlookComposeMask, ACCESSWEBAPP: Office._AccessWebAppMask } return function (condition, invert) { var result = false; if (nameToMaskMapping[condition] & Office._appContext) { result = true; } return invert ? !result : result; } })(), function () { return typeof Office._appContext === "number"; } ); Office._filterManager._pushFilter( "reqs", (function () { function checkForMethod(methodName) { return Office._methodContext && Office._methodContext[methodName]; } function checkForSet(setDescriptor) { setDescriptor = setDescriptor.split(" "); var setName = setDescriptor[0].trim(), setEntry = Office._setContext && setName in Office._setContext && (Office._setContext[setName] || "1.1"); if (!setEntry) { return false; } if (setDescriptor.length === 1) { return true; } else { var comparisonOperator = setDescriptor[1].trim(), setVersion = setDescriptor[2].split("."), setEntryVersion = setEntry.split("."), difference = 0, maxComponentCount = Math.max(setEntryVersion.length, setVersion.length); for (var i = 0; i < maxComponentCount; i++) { var leftInt = parseInt(setEntryVersion[i], 10) || 0, rightInt = parseInt(setVersion[i], 10) || 0; if (leftInt === rightInt) { continue; } difference = leftInt - rightInt; break; } switch (comparisonOperator) { case "EQ": return difference === 0; case "GT": return difference > 0; case "LT": return difference < 0; case "GE": return difference >= 0; case "LE": return difference <= 0; default: return false; } } return false; } return function (condition, invert) { var result = true; var typeAgnosticCond = condition.slice(condition.indexOf(" ")).trim(); if (condition.indexOf("SET") === 0) { result = checkForSet(typeAgnosticCond); } else if (condition.indexOf("METHOD") === 0) { result = checkForMethod(typeAgnosticCond); } return invert ? !result : result; } })(), function () { if (Office._showAll === false) { return true; } return false; } ) Office._addEnumOnObject = function (enumName, enumObj, targetObj, conditions) { Office._processItem( targetObj, { conditions: conditions, value: enumObj }, enumName ); } /******************************************************************************/ // Setup Project Office._processItem(Office, { metaOnly: true, conditions: { hosts: ["project"] }, contents: { ProjectProjectFields: { value: { ///<field type="Number">CurrencySymbol</field> CurrencySymbol: 1, ///<field type="Number">CurrencySymbolPosition</field> CurrencySymbolPosition: 2, ///<field type="Number">DurationUnits</field> DurationUnits: 3, ///<field type="Number">GUID</field> GUID: 4, ///<field type="Number">Finish</field> Finish: 5, ///<field type="Number">Start</field> Start: 6, ///<field type="Number">ReadOnly</field> ReadOnly: 7, ///<field type="Number">VERSION</field> VERSION: 8, ///<field type="Number">WorkUnits</field> WorkUnits: 9, ///<field type="Number">ProjectServerUrl</field> ProjectServerUrl: 10, ///<field type="Number">WSSUrl</field> WSSUrl: 11, ///<field type="Number">WSSList</field> WSSList: 12 } }, ProjectViewTypes: { value: { ///<field type="Number">Gantt</field> Gantt: 1, ///<field type="Number">NetworkDiagram</field> NetworkDiagram: 2, ///<field type="Number">TaskDiagram</field> TaskDiagram: 3, ///<field type="Number">TaskForm</field> TaskForm: 4, ///<field type="Number">TaskSheet</field> TaskSheet: 5, ///<field type="Number">ResourceForm</field> ResourceForm: 6, ///<field type="Number">ResourceSheet</field> ResourceSheet: 7, ///<field type="Number">ResourceGraph</field> ResourceGraph: 8, ///<field type="Number">TeamPlanner</field> TeamPlanner: 9, ///<field type="Number">TaskDetails</field> TaskDetails: 10, ///<field type="Number">TaskNameForm</field> TaskNameForm: 11, ///<field type="Number">ResourceNames</field> ResourceNames: 12, ///<field type="Number">Calendar</field> Calendar: 13, ///<field type="Number">TaskUsage</field> TaskUsage: 14, ///<field type="Number">ResourceUsage</field> ResourceUsage: 15, ///<field type="Number">Timeline</field> Timeline: 16, ///<field type="Number">Drawing</field> Drawing: 18, ///<field type="Number">Resource Plan</field> ResourcePlan: 19 } }, ProjectTaskFields: { value: { ///<field type="Number">ActualCost</field> ActualCost: 0, ///<field type="Number">ActualDuration</field> ActualDuration: 1, ///<field type="Number">ActualFinish</field> ActualFinish: 2, ///<field type="Number">ActualOvertimeCost</field> ActualOvertimeCost: 3, ///<field type="Number">ActualOvertimeWork</field> ActualOvertimeWork: 4, ///<field type="Number">ActualStart</field> ActualStart: 5, ///<field type="Number">ActualWork</field> ActualWork: 6, ///<field type="Number">Text1</field> Text1: 7, ///<field type="Number">Text10</field> Text10: 8, ///<field type="Number">Finish10</field> Finish10: 9, ///<field type="Number">Start10</field> Start10: 10, ///<field type="Number">Text11</field> Text11: 11, ///<field type="Number">Text12</field> Text12: 12, ///<field type="Number">Text13</field> Text13: 13, ///<field type="Number">Text14</field> Text14: 14, ///<field type="Number">Text15</field> Text15: 15, ///<field type="Number">Text16</field> Text16: 16, ///<field type="Number">Text17</field> Text17: 17, ///<field type="Number">Text18</field> Text18: 18, ///<field type="Number">Text19</field> Text19: 19, ///<field type="Number">Finish1</field> Finish1: 20, ///<field type="Number">Start1</field> Start1: 21, ///<field type="Number">Text2</field> Text2: 22, ///<field type="Number">Text20</field> Text20: 23, ///<field type="Number">Text21</field> Text21: 24, ///<field type="Number">Text22</field> Text22: 25, ///<field type="Number">Text23</field> Text23: 26, ///<field type="Number">Text24</field> Text24: 27, ///<field type="Number">Text25</field> Text25: 28, ///<field type="Number">Text26</field> Text26: 29, ///<field type="Number">Text27</field> Text27: 30, ///<field type="Number">Text28</field> Text28: 31, ///<field type="Number">Text29</field> Text29: 32, ///<field type="Number">Finish2</field> Finish2: 33, ///<field type="Number">Start2</field> Start2: 34, ///<field type="Number">Text3</field> Text3: 35, ///<field type="Number">Text30</field> Text30: 36, ///<field type="Number">Finish3</field> Finish3: 37, ///<field type="Number">Start3</field> Start3: 38, ///<field type="Number">Text4</field> Text4: 39, ///<field type="Number">Finish4</field> Finish4: 40, ///<field type="Number">Start4</field> Start4: 41, ///<field type="Number">Text5</field> Text5: 42, ///<field type="Number">Finish5</field> Finish5: 43, ///<field type="Number">Start5</field> Start5: 44, ///<field type="Number">Text6</field> Text6: 45, ///<field type="Number">Finish6</field> Finish6: 46, ///<field type="Number">Start6</field> Start6: 47, ///<field type="Number">Text7</field> Text7: 48, ///<field type="Number">Finish7</field> Finish7: 49, ///<field type="Number">Start7</field> Start7: 50, ///<field type="Number">Text8</field> Text8: 51, ///<field type="Number">Finish8</field> Finish8: 52, ///<field type="Number">Start8</field> Start8: 53, ///<field type="Number">Text9</field> Text9: 54, ///<field type="Number">Finish9</field> Finish9: 55, ///<field type="Number">Start9</field> Start9: 56, ///<field type="Number">Baseline10BudgetCost</field> Baseline10BudgetCost: 57, ///<field type="Number">Baseline10BudgetWork</field> Baseline10BudgetWork: 58, ///<field type="Number">Baseline10Cost</field> Baseline10Cost: 59, ///<field type="Number">Baseline10Duration</field> Baseline10Duration: 60, ///<field type="Number">Baseline10Finish</field> Baseline10Finish: 61, ///<field type="Number">Baseline10FixedCost</field> Baseline10FixedCost: 62, ///<field type="Number">Baseline10FixedCostAccrual</field> Baseline10FixedCostAccrual: 63, ///<field type="Number">Baseline10Start</field> Baseline10Start: 64, ///<field type="Number">Baseline10Work</field> Baseline10Work: 65, ///<field type="Number">Baseline1BudgetCost</field> Baseline1BudgetCost: 66, ///<field type="Number">Baseline1BudgetWork</field> Baseline1BudgetWork: 67, ///<field type="Number">Baseline1Cost</field> Baseline1Cost: 68, ///<field type="Number">Baseline1Duration</field> Baseline1Duration: 69, ///<field type="Number">Baseline1Finish</field> Baseline1Finish: 70, ///<field type="Number">Baseline1FixedCost</field> Baseline1FixedCost: 71, ///<field type="Number">Baseline1FixedCostAccrual</field> Baseline1FixedCostAccrual: 72, ///<field type="Number">Baseline1Start</field> Baseline1Start: 73, ///<field type="Number">Baseline1Work</field> Baseline1Work: 74, ///<field type="Number">Baseline2BudgetCost</field> Baseline2BudgetCost: 75, ///<field type="Number">Baseline2BudgetWork</field> Baseline2BudgetWork: 76, ///<field type="Number">Baseline2Cost</field> Baseline2Cost: 77, ///<field type="Number">Baseline2Duration</field> Baseline2Duration: 78, ///<field type="Number">Baseline2Finish</field> Baseline2Finish: 79, ///<field type="Number">Baseline2FixedCost</field> Baseline2FixedCost: 80, ///<field type="Number">Baseline2FixedCostAccrual</field> Baseline2FixedCostAccrual: 81, ///<field type="Number">Baseline2Start</field> Baseline2Start: 82, ///<field type="Number">Baseline2Work</field> Baseline2Work: 83, ///<field type="Number">Baseline3BudgetCost</field> Baseline3BudgetCost: 84, ///<field type="Number">Baseline3BudgetWork</field> Baseline3BudgetWork: 85, ///<field type="Number">Baseline3Cost</field> Baseline3Cost: 86, ///<field type="Number">Baseline3Duration</field> Baseline3Duration: 87, ///<field type="Number">Baseline3Finish</field> Baseline3Finish: 88, ///<field type="Number">Baseline3FixedCost</field> Baseline3FixedCost: 89, ///<field type="Number">Baseline3FixedCostAccrual</field> Baseline3FixedCostAccrual: 90, ///<field type="Number">Basline3Start</field> Basline3Start: 91, ///<field type="Number">Baseline3Work</field> Baseline3Work: 92, ///<field type="Number">Baseline4BudgetCost</field> Baseline4BudgetCost: 93, ///<field type="Number">Baseline4BudgetWork</field> Baseline4BudgetWork: 94, ///<field type="Number">Baseline4Cost</field> Baseline4Cost: 95, ///<field type="Number">Baseline4Duration</field> Baseline4Duration: 96, ///<field type="Number">Baseline4Finish</field> Baseline4Finish: 97, ///<field type="Number">Baseline4FixedCost</field> Baseline4FixedCost: 98, ///<field type="Number">Baseline4FixedCostAccrual</field> Baseline4FixedCostAccrual: 99, ///<field type="Number">Baseline4Start</field> Baseline4Start: 100, ///<field type="Number">Baseline4Work</field> Baseline4Work: 101, ///<field type="Number">Baseline5BudgetCost</field> Baseline5BudgetCost: 102, ///<field type="Number">Baseline5BudgetWork</field> Baseline5BudgetWork: 103, ///<field type="Number">Baseline5Cost</field> Baseline5Cost: 104, ///<field type="Number">Baseline5Duration</field> Baseline5Duration: 105, ///<field type="Number">Baseline5Finish</field> Baseline5Finish: 106, ///<field type="Number">Baseline5FixedCost</field> Baseline5FixedCost: 107, ///<field type="Number">Baseline5FixedCostAccrual</field> Baseline5FixedCostAccrual: 108, ///<field type="Number">Baseline5Start</field> Baseline5Start: 109, ///<field type="Number">Baseline5Work</field> Baseline5Work: 110, ///<field type="Number">Baseline6BudgetCost</field> Baseline6BudgetCost: 111, ///<field type="Number">Baseline6BudgetWork</field> Baseline6BudgetWork: 112, ///<field type="Number">Baseline6Cost</field> Baseline6Cost: 113, ///<field type="Number">Baseline6Duration</field> Baseline6Duration: 114, ///<field type="Number">Baseline6Finish</field> Baseline6Finish: 115, ///<field type="Number">Baseline6FixedCost</field> Baseline6FixedCost: 116, ///<field type="Number">Baseline6FixedCostAccrual</field> Baseline6FixedCostAccrual: 117, ///<field type="Number">Baseline6Start</field> Baseline6Start: 118, ///<field type="Number">Baseline6Work</field> Baseline6Work: 119, ///<field type="Number">Baseline7BudgetCost</field> Baseline7BudgetCost: 120, ///<field type="Number">Baseline7BudgetWork</field> Baseline7BudgetWork: 121, ///<field type="Number">Baseline7Cost</field> Baseline7Cost: 122, ///<field type="Number">Baseline7Duration</field> Baseline7Duration: 123, ///<field type="Number">Baseline7Finish</field> Baseline7Finish: 124, ///<field type="Number">Baseline7FixedCost</field> Baseline7FixedCost: 125, ///<field type="Number">Baseline7FixedCostAccrual</field> Baseline7FixedCostAccrual: 126, ///<field type="Number">Baseline7Start</field> Baseline7Start: 127, ///<field type="Number">Baseline7Work</field> Baseline7Work: 128, ///<field type="Number">Baseline8BudgetCost</field> Baseline8BudgetCost: 129, ///<field type="Number">Baseline8BudgetWork</field> Baseline8BudgetWork: 130, ///<field type="Number">Baseline8Cost</field> Baseline8Cost: 131, ///<field type="Number">Baseline8Duration</field> Baseline8Duration: 132, ///<field type="Number">Baseline8Finish</field> Baseline8Finish: 133, ///<field type="Number">Baseline8FixedCost</field> Baseline8FixedCost: 134, ///<field type="Number">Baseline8FixedCostAccrual</field> Baseline8FixedCostAccrual: 135, ///<field type="Number">Baseline8Start</field> Baseline8Start: 136, ///<field type="Number">Baseline8Work</field> Baseline8Work: 137, ///<field type="Number">Baseline9BudgetCost</field> Baseline9BudgetCost: 138, ///<field type="Number">Baseline9BudgetWork</field> Baseline9BudgetWork: 139, ///<field type="Number">Baseline9Cost</field> Baseline9Cost: 140, ///<field type="Number">Baseline9Duration</field> Baseline9Duration: 141, ///<field type="Number">Baseline9Finish</field> Baseline9Finish: 142, ///<field type="Number">Baseline9FixedCost</field> Baseline9FixedCost: 143, ///<field type="Number">Baseline9FixedCostAccrual</field> Baseline9FixedCostAccrual: 144, ///<field type="Number">Baseline9Start</field> Baseline9Start: 145, ///<field type="Number">Baseline9Work</field> Baseline9Work: 146, ///<field type="Number">BaselineBudgetCost</field> BaselineBudgetCost: 147, ///<field type="Number">BaselineBudgetWork</field> BaselineBudgetWork: 148, ///<field type="Number">BaselineCost</field> BaselineCost: 149, ///<field type="Number">BaselineDuration</field> BaselineDuration: 150, ///<field type="Number">BaselineFinish</field> BaselineFinish: 151, ///<field type="Number">BaselineFixedCost</field> BaselineFixedCost: 152, ///<field type="Number">BaselineFixedCostAccrual</field> BaselineFixedCostAccrual: 153, ///<field type="Number">BaselineStart</field> BaselineStart: 154, ///<field type="Number">BaselineWork</field> BaselineWork: 155, ///<field type="Number">BudgetCost</field> BudgetCost: 156, ///<field type="Number">BudgetFixedCost</field> BudgetFixedCost: 157, ///<field type="Number">BudgetFixedWork</field> BudgetFixedWork: 158, ///<field type="Number">BudgetWork</field> BudgetWork: 159, ///<field type="Number">TaskCalendarGUID</field> TaskCalendarGUID: 160, ///<field type="Number">ConstraintDate</field> ConstraintDate: 161, ///<field type="Number">ConstraintType</field> ConstraintType: 162, ///<field type="Number">Cost1</field> Cost1: 163, ///<field type="Number">Cost10</field> Cost10: 164, ///<field type="Number">Cost2</field> Cost2: 165, ///<field type="Number">Cost3</field> Cost3: 166, ///<field type="Number">Cost4</field> Cost4: 167, ///<field type="Number">Cost5</field> Cost5: 168, ///<field type="Number">Cost6</field> Cost6: 169, ///<field type="Number">Cost7</field> Cost7: 170, ///<field type="Number">Cost8</field> Cost8: 171, ///<field type="Number">Cost9</field> Cost9: 172, ///<field type="Number">Date1</field> Date1: 173, ///<field type="Number">Date10</field> Date10: 174, ///<field type="Number">Date2</field> Date2: 175, ///<field type="Number">Date3</field> Date3: 176, ///<field type="Number">Date4</field> Date4: 177, ///<field type="Number">Date5</field> Date5: 178, ///<field type="Number">Date6</field> Date6: 179, ///<field type="Number">Date7</field> Date7: 180, ///<field type="Number">Date8</field> Date8: 181, ///<field type="Number">Date9</field> Date9: 182, ///<field type="Number">Deadline</field> Deadline: 183, ///<field type="Number">Duration1</field> Duration1: 184, ///<field type="Number">Duration10</field> Duration10: 185, ///<field type="Number">Duration2</field> Duration2: 186, ///<field type="Number">Duration3</field> Duration3: 187, ///<field type="Number">Duration4</field> Duration4: 188, ///<field type="Number">Duration5</field> Duration5: 189, ///<field type="Number">Duration6</field> Duration6: 190, ///<field type="Number">Duration7</field> Duration7: 191, ///<field type="Number">Duration8</field> Duration8: 192, ///<field type="Number">Duration9</field> Duration9: 193, ///<field type="Number">Duration</field> Duration: 194, ///<field type="Number">EarnedValueMethod</field> EarnedValueMethod: 195, ///<field type="Number">FinishSlack</field> FinishSlack: 196, ///<field type="Number">FixedCost</field> FixedCost: 197, ///<field type="Number">FixedCostAccrual</field> FixedCostAccrual: 198, ///<field type="Number">Flag10</field> Flag10: 199, ///<field type="Number">Flag1</field> Flag1: 200, ///<field type="Number">Flag11</field> Flag11: 201, ///<field type="Number">Flag12</field> Flag12: 202, ///<field type="Number">Flag13</field> Flag13: 203, ///<field type="Number">Flag14</field> Flag14: 204, ///<field type="Number">Flag15</field> Flag15: 205, ///<field type="Number">Flag16</field> Flag16: 206, ///<field type="Number">Flag17</field> Flag17: 207, ///<field type="Number">Flag18</field> Flag18: 208, ///<field type="Number">Flag19</field> Flag19: 209, ///<field type="Number">Flag2</field> Flag2: 210, ///<field type="Number">Flag20</field> Flag20: 211, ///<field type="Number">Flag3</field> Flag3: 212, ///<field type="Number">Flag4</field> Flag4: 213, ///<field type="Number">Flag5</field> Flag5: 214, ///<field type="Number">Flag6</field> Flag6: 215, ///<field type="Number">Flag7</field> Flag7: 216, ///<field type="Number">Flag8</field> Flag8: 217, ///<field type="Number">Flag9</field> Flag9: 218, ///<field type="Number">FreeSlack</field> FreeSlack: 219, ///<field type="Number">HasRollupSubTasks</field> HasRollupSubTasks: 220, ///<field type="Number">ID</field> ID: 221, ///<field type="Number">Name</field> Name: 222, ///<field type="Number">Notes</field> Notes: 223, ///<field type="Number">Number1</field> Number1: 224, ///<field type="Number">Number10</field> Number10: 225, ///<field type="Number">Number11</field> Number11: 226, ///<field type="Number">Number12</field> Number12: 227, ///<field type="Number">Number13</field> Number13: 228, ///<field type="Number">Number14</field> Number14: 229, ///<field type="Number">Number15</field> Number15: 230, ///<field type="Number">Number16</field> Number16: 231, ///<field type="Number">Number17</field> Number17: 232, ///<field type="Number">Number18</field> Number18: 233, ///<field type="Number">Number19</field> Number19: 234, ///<field type="Number">Number2</field> Number2: 235, ///<field type="Number">Number20</field> Number20: 236, ///<field type="Number">Number3</field> Number3: 237, ///<field type="Number">Number4</field> Number4: 238, ///<field type="Number">Number5</field> Number5: 239, ///<field type="Number">Number6</field> Number6: 240, ///<field type="Number">Number7</field> Number7: 241, ///<field type="Number">Number8</field> Number8: 242, ///<field type="Number">Number9</field> Number9: 243, ///<field type="Number">ScheduledDuration</field> ScheduledDuration: 244, ///<field type="Number">ScheduledFinish</field> ScheduledFinish: 245, ///<field type="Number">ScheduledStart</field> ScheduledStart: 246, ///<field type="Number">OutlineLevel</field> OutlineLevel: 247, ///<field type="Number">OvertimeCost</field> OvertimeCost: 248, ///<field type="Number">OvertimeWork</field> OvertimeWork: 249, ///<field type="Number">PercentComplete</field> PercentComplete: 250, ///<field type="Number">PercentWorkComplete</field> PercentWorkComplete: 251, ///<field type="Number">Predecessors</field> Predecessors: 252, ///<field type="Number">PreleveledFinish</field> PreleveledFinish: 253, ///<field type="Number">PreleveledStart</field> PreleveledStart: 254, ///<field type="Number">Priority</field> Priority: 255, ///<field type="Number">Active</field> Active: 256, ///<field type="Number">Critical</field> Critical: 257, ///<field type="Number">Milestone</field> Milestone: 258, ///<field type="Number">Overallocated</field> Overallocated: 259, ///<field type="Number">IsRollup</field> IsRollup: 260, ///<field type="Number">Summary</field> Summary: 261, ///<field type="Number">RegularWork</field> RegularWork: 262, ///<field type="Number">RemainingCost</field> RemainingCost: 263, ///<field type="Number">RemainingDuration</field> RemainingDuration: 264, ///<field type="Number">RemainingOvertimeCost</field> RemainingOvertimeCost: 265, ///<field type="Number">RemainingWork</field> RemainingWork: 266, ///<field type="Number">ResourceNames</field> ResourceNames: 267, ///<field type="Number">ResourceNames</field> ResourceNames: 268, ///<field type="Number">Cost</field> Cost: 269, ///<field type="Number">Finish</field> Finish: 270, ///<field type="Number">Start</field> Start: 271, ///<field type="Number">Work</field> Work: 272, ///<field type="Number">StartSlack</field> StartSlack: 273, ///<field type="Number">Status</field> Status: 274, ///<field type="Number">Successors</field> Successors: 275, ///<field type="Number">StatusManager</field> StatusManager: 276, ///<field type="Number">TotalSlack</field> TotalSlack: 277, ///<field type="Number">TaskGUID</field> TaskGUID: 278, ///<field type="Number">Type</field> Type: 279, ///<field type="Number">WBS</field> WBS: 280, ///<field type="Number">WBSPREDECESSORS</field> WBSPREDECESSORS: 281, ///<field type="Number">WBSSUCCESSORS</field> WBSSUCCESSORS: 282, ///<field type="Number">WSSID</field> WSSID: 283 } }, ProjectResourceFields: { value: { ///<field type="Number">Accrual</field> Accrual: 0, ///<field type="Number">ActualCost</field> ActualCost: 1, ///<field type="Number">ActualOvertimeCost</field> ActualOvertimeCost: 2, ///<field type="Number">ActualOvertimeWork</field> ActualOvertimeWork: 3, ///<field type="Number">ActualOvertimeWorkProtected</field> ActualOvertimeWorkProtected: 4, ///<field type="Number">ActualWork</field> ActualWork: 5, ///<field type="Number">ActualWorkProtected</field> ActualWorkProtected: 6, ///<field type="Number">BaseCalendar</field> BaseCalendar: 7, ///<field type="Number">Baseline10BudgetCost</field> Baseline10BudgetCost: 8, ///<field type="Number">Baseline10BudgetWork</field> Baseline10BudgetWork: 9, ///<field type="Number">Baseline10Cost</field> Baseline10Cost: 10, ///<field type="Number">Baseline10Work</field> Baseline10Work: 11, ///<field type="Number">Baseline1BudgetCost</field> Baseline1BudgetCost: 12, ///<field type="Number">Baseline1BudgetWork</field> Baseline1BudgetWork: 13, ///<field type="Number">Baseline1Cost</field> Baseline1Cost: 14, ///<field type="Number">Baseline1Work</field> Baseline1Work: 15, ///<field type="Number">Baseline2BudgetCost</field> Baseline2BudgetCost: 16, ///<field type="Number">Baseline2BudgetWork</field> Baseline2BudgetWork: 17, ///<field type="Number">Baseline2Cost</field> Baseline2Cost: 18, ///<field type="Number">Baseline2Work</field> Baseline2Work: 19, ///<field type="Number">Baseline3BudgetCost</field> Baseline3BudgetCost: 20, ///<field type="Number">Baseline3BudgetWork</field> Baseline3BudgetWork: 21, ///<field type="Number">Baseline3Cost</field> Baseline3Cost: 22, ///<field type="Number">Baseline3Work</field> Baseline3Work: 23, ///<field type="Number">Baseline4BudgetCost</field> Baseline4BudgetCost: 24, ///<field type="Number">Baseline4BudgetWork</field> Baseline4BudgetWork: 25, ///<field type="Number">Baseline4Cost</field> Baseline4Cost: 26, ///<field type="Number">Baseline4Work</field> Baseline4Work: 27, ///<field type="Number">Baseline5BudgetCost</field> Baseline5BudgetCost: 28, ///<field type="Number">Baseline5BudgetWork</field> Baseline5BudgetWork: 29, ///<field type="Number">Baseline5Cost</field> Baseline5Cost: 30, ///<field type="Number">Baseline5Work</field> Baseline5Work: 31, ///<field type="Number">Baseline6BudgetCost</field> Baseline6BudgetCost: 32, ///<field type="Number">Baseline6BudgetWork</field> Baseline6BudgetWork: 33, ///<field type="Number">Baseline6Cost</field> Baseline6Cost: 34, ///<field type="Number">Baseline6Work</field> Baseline6Work: 35, ///<field type="Number">Baseline7BudgetCost</field> Baseline7BudgetCost: 36, ///<field type="Number">Baseline7BudgetWork</field> Baseline7BudgetWork: 37, ///<field type="Number">Baseline7Cost</field> Baseline7Cost: 38, ///<field type="Number">Baseline7Work</field> Baseline7Work: 39, ///<field type="Number">Baseline8BudgetCost</field> Baseline8BudgetCost: 40, ///<field type="Number">Baseline8BudgetWork</field> Baseline8BudgetWork: 41, ///<field type="Number">Baseline8Cost</field> Baseline8Cost: 42, ///<field type="Number">Baseline8Work</field> Baseline8Work: 43, ///<field type="Number">Baseline9BudgetCost</field> Baseline9BudgetCost: 44, ///<field type="Number">Baseline9BudgetWork</field> Baseline9BudgetWork: 45, ///<field type="Number">Baseline9Cost</field> Baseline9Cost: 46, ///<field type="Number">Baseline9Work</field> Baseline9Work: 47, ///<field type="Number">BaselineBudgetCost</field> BaselineBudgetCost: 48, ///<field type="Number">BaselineBudgetWork</field> BaselineBudgetWork: 49, ///<field type="Number">BaselineCost</field> BaselineCost: 50, ///<field type="Number">BaselineWork</field> BaselineWork: 51, ///<field type="Number">BudgetCost</field> BudgetCost: 52, ///<field type="Number">BudgetWork</field> BudgetWork: 53, ///<field type="Number">ResourceCalendarGUID</field> ResourceCalendarGUID: 54, ///<field type="Number">Code</field> Code: 55, ///<field type="Number">Cost1</field> Cost1: 56, ///<field type="Number">Cost10</field> Cost10: 57, ///<field type="Number">Cost2</field> Cost2: 58, ///<field type="Number">Cost3</field> Cost3: 59, ///<field type="Number">Cost4</field> Cost4: 60, ///<field type="Number">Cost5</field> Cost5: 61, ///<field type="Number">Cost6</field> Cost6: 62, ///<field type="Number">Cost7</field> Cost7: 63, ///<field type="Number">Cost8</field> Cost8: 64, ///<field type="Number">Cost9</field> Cost9: 65, ///<field type="Number">ResourceCreationDate</field> ResourceCreationDate: 66, ///<field type="Number">Date1</field> Date1: 67, ///<field type="Number">Date10</field> Date10: 68, ///<field type="Number">Date2</field> Date2: 69, ///<field type="Number">Date3</field> Date3: 70, ///<field type="Number">Date4</field> Date4: 71, ///<field type="Number">Date5</field> Date5: 72, ///<field type="Number">Date6</field> Date6: 73, ///<field type="Number">Date7</field> Date7: 74, ///<field type="Number">Date8</field> Date8: 75, ///<field type="Number">Date9</field> Date9: 76, ///<field type="Number">Duration1</field> Duration1: 77, ///<field type="Number">Duration10</field> Duration10: 78, ///<field type="Number">Duration2</field> Duration2: 79, ///<field type="Number">Duration3</field> Duration3: 80, ///<field type="Number">Duration4</field> Duration4: 81, ///<field type="Number">Duration5</field> Duration5: 82, ///<field type="Number">Duration6</field> Duration6: 83, ///<field type="Number">Duration7</field> Duration7: 84, ///<field type="Number">Duration8</field> Duration8: 85, ///<field type="Number">Duration9</field> Duration9: 86, ///<field type="Number">Email</field> Email: 87, ///<field type="Number">End</field> End: 88, ///<field type="Number">Finish1</field> Finish1: 89, ///<field type="Number">Finish10</field> Finish10: 90, ///<field type="Number">Finish2</field> Finish2: 91, ///<field type="Number">Finish3</field> Finish3: 92, ///<field type="Number">Finish4</field> Finish4: 93, ///<field type="Number">Finish5</field> Finish5: 94, ///<field type="Number">Finish6</field> Finish6: 95, ///<field type="Number">Finish7</field> Finish7: 96, ///<field type="Number">Finish8</field> Finish8: 97, ///<field type="Number">Finish9</field> Finish9: 98, ///<field type="Number">Flag10</field> Flag10: 99, ///<field type="Number">Flag1</field> Flag1: 100, ///<field type="Number">Flag11</field> Flag11: 101, ///<field type="Number">Flag12</field> Flag12: 102, ///<field type="Number">Flag13</field> Flag13: 103, ///<field type="Number">Flag14</field> Flag14: 104, ///<field type="Number">Flag15</field> Flag15: 105, ///<field type="Number">Flag16</field> Flag16: 106, ///<field type="Number">Flag17</field> Flag17: 107, ///<field type="Number">Flag18</field> Flag18: 108, ///<field type="Number">Flag19</field> Flag19: 109, ///<field type="Number">Flag2</field> Flag2: 110, ///<field type="Number">Flag20</field> Flag20: 111, ///<field type="Number">Flag3</field> Flag3: 112, ///<field type="Number">Flag4</field> Flag4: 113, ///<field type="Number">Flag5</field> Flag5: 114, ///<field type="Number">Flag6</field> Flag6: 115, ///<field type="Number">Flag7</field> Flag7: 116, ///<field type="Number">Flag8</field> Flag8: 117, ///<field type="Number">Flag9</field> Flag9: 118, ///<field type="Number">Group</field> Group: 119, ///<field type="Number">Units</field> Units: 120, ///<field type="Number">Name</field> Name: 121, ///<field type="Number">Notes</field> Notes: 122, ///<field type="Number">Number1</field> Number1: 123, ///<field type="Number">Number10</field> Number10: 124, ///<field type="Number">Number11</field> Number11: 125, ///<field type="Number">Number12</field> Number12: 126, ///<field type="Number">Number13</field> Number13: 127, ///<field type="Number">Number14</field> Number14: 128, ///<field type="Number">Number15</field> Number15: 129, ///<field type="Number">Number16</field> Number16: 130, ///<field type="Number">Number17</field> Number17: 131, ///<field type="Number">Number18</field> Number18: 132, ///<field type="Number">Number19</field> Number19: 133, ///<field type="Number">Number2</field> Number2: 134, ///<field type="Number">Number20</field> Number20: 135, ///<field type="Number">Number3</field> Number3: 136, ///<field type="Number">Number4</field> Number4: 137, ///<field type="Number">Number5</field> Number5: 138, ///<field type="Number">Number6</field> Number6: 139, ///<field type="Number">Number7</field> Number7: 140, ///<field type="Number">Number8</field> Number8: 141, ///<field type="Number">Number9</field> Number9: 142, ///<field type="Number">OvertimeCost</field> OvertimeCost: 143, ///<field type="Number">OvertimeRate</field> OvertimeRate: 144, ///<field type="Number">OvertimeWork</field> OvertimeWork: 145, ///<field type="Number">PercentWorkComplete</field> PercentWorkComplete: 146, ///<field type="Number">CostPerUse</field> CostPerUse: 147, ///<field type="Number">Generic</field> Generic: 148, ///<field type="Number">OverAllocated</field> OverAllocated: 149, ///<field type="Number">RegularWork</field> RegularWork: 150, ///<field type="Number">RemainingCost</field> RemainingCost: 151, ///<field type="Number">RemainingOvertimeCost</field> RemainingOvertimeCost: 152, ///<field type="Number">RemainingOvertimeWork</field> RemainingOvertimeWork: 153, ///<field type="Number">RemainingWork</field> RemainingWork: 154, ///<field type="Number">ResourceGUID</field> ResourceGUID: 155, ///<field type="Number">Cost</field> Cost: 156, ///<field type="Number">Work</field> Work: 157, ///<field type="Number">Start</field> Start: 158, ///<field type="Number">Start1</field> Start1: 159, ///<field type="Number">Start10</field> Start10: 160, ///<field type="Number">Start2</field> Start2: 161, ///<field type="Number">Start3</field> Start3: 162, ///<field type="Number">Start4</field> Start4: 163, ///<field type="Number">Start5</field> Start5: 164, ///<field type="Number">Start6</field> Start6: 165, ///<field type="Number">Start7</field> Start7: 166, ///<field type="Number">Start8</field> Start8: 167, ///<field type="Number">Start9</field> Start9: 168, ///<field type="Number">StandardRate</field> StandardRate: 169, ///<field type="Number">Text1</field> Text1: 170, ///<field type="Number">Text10</field> Text10: 171, ///<field type="Number">Text11</field> Text11: 172, ///<field type="Number">Text12</field> Text12: 173, ///<field type="Number">Text13</field> Text13: 174, ///<field type="Number">Text14</field> Text14: 175, ///<field type="Number">Text15</field> Text15: 176, ///<field type="Number">Text16</field> Text16: 177, ///<field type="Number">Text17</field> Text17: 178, ///<field type="Number">Text18</field> Text18: 179, ///<field type="Number">Text19</field> Text19: 180, ///<field type="Number">Text2</field> Text2: 181, ///<field type="Number">Text20</field> Text20: 182, ///<field type="Number">Text21</field> Text21: 183, ///<field type="Number">Text22</field> Text22: 184, ///<field type="Number">Text23</field> Text23: 185, ///<field type="Number">Text24</field> Text24: 186, ///<field type="Number">Text25</field> Text25: 187, ///<field type="Number">Text26</field> Text26: 188, ///<field type="Number">Text27</field> Text27: 189, ///<field type="Number">Text28</field> Text28: 190, ///<field type="Number">Text29</field> Text29: 191, ///<field type="Number">Text3</field> Text3: 192, ///<field type="Number">Text30</field> Text30: 193, ///<field type="Number">Text4</field> Text4: 194, ///<field type="Number">Text5</field> Text5: 195, ///<field type="Number">Text6</field> Text6: 196, ///<field type="Number">Text7</field> Text7: 197, ///<field type="Number">Text8</field> Text8: 198, ///<field type="Number">Text9</field> Text9: 199 } }, context: { contents: { document: { contents: { getSelectedTaskAsync: { conditions: { reqs: ["method Document.getSelectedTaskAsync"] }, value: function (callback) { ///<summary> (Project only) Get the current selected Task's Id.</summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getTaskByIndexAsync: { conditions: { reqs: ["method Document.getTaskByIndexAsync"] }, value: function (taskIndex, callback) { ///<summary> (Project only) Get the Task's Id for provided task index.</summary> ///<param name="taskIndex" type="Object">Task index in task container</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getTaskAsync: { conditions: { reqs: ["method Document.getTaskAsync"] }, value: function (taskId, callback) { ///<summary> (Project only) Get the Task Name, WSS Task Id, and ResourceNames for given taskId .</summary> ///<param name="taskId" type="Object">Either a string or value of the Task Id.</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getTaskFieldAsync: { conditions: { reqs: ["method Document.getTaskFieldAsync"] }, value: function (taskId, taskField, callback) { ///<summary> (Project only) Get task field for provided task Id. (Ex. StartDate).</summary> ///<param name="taskId" type="Object">Either a string or value of the Task Id.</param> ///<param name="taskField" type="Office.ProjectTaskFields">Task Fields.</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getSelectedResourceAsync: { conditions: { reqs: ["method Document.getSelectedResourceAsync"] }, value: function (callback) { ///<summary> (Project only) Get the current selected Resource's Id.</summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getResourceByIndexAsync: { conditions: { reqs: ["method Document.getResourceByIndexAsync"] }, value: function (resourceIndex, callback) { ///<summary> (Project only) Get the Resource's Id for provided resource index.</summary> ///<param name="resourceIndex" type="Object">Resource index in resource container</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getResourceFieldAsync: { conditions: { reqs: ["method Document.getResourceFieldAsync"] }, value: function (resourceId, resourceField, callback) { ///<summary> (Project only) Get resource field for provided resource Id. (Ex.ResourceName)</summary> ///<param name="resourceId" type="Object">Either a string or value of the Resource Id.</param> ///<param name="resourceField" type="Office.ProjectResourceFields">Resource Fields.</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getProjectFieldAsync: { conditions: { reqs: ["method Document.getProjectFieldAsync"] }, value: function (projectField, callback) { ///<summary> (Project only) Get Project field (Ex. ProjectWebAccessURL).</summary> ///<param name="projectField" type="Office.ProjectProjectFields">Project level fields.</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getSelectedViewAsync: { conditions: { reqs: ["method Document.getSelectedViewAsync"] }, value: function (callback) { ///<summary> (Project only) Get the current selected View Type (Ex. Gantt) and View Name.</summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, getWSSURLAsync: { conditions: { reqs: ["method Document.getWSSURLAsync"] }, value: function (callback) { ///<summary> (Project only) Get the WSS Url and list name for the Tasks List, the MPP is synced too.</summary> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, setTaskFieldAsync: { conditions: { reqs: ["method Document.setTaskFieldAsync"] }, value: function (taskId, fieldId, fieldValue, callback) { ///<summary> (Project only) Set Taskfield (Ex. TaskName).</summary> ///<param name="taskId" type="Object">Either a string or value of the Task Id.</param> ///<param name="taskField" type="Office.ProjectTaskFields">Task Field.</param> ///<param name="fieldValue" type="Object">Either a string, number boolean or object for the data that you want to set.</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } }, setResourceFieldAsync: { conditions: { reqs: ["method Document.setResourceFieldAsync"] }, value: function (resourceId, fieldId, fieldValue, callback) { ///<summary> (Project only) Set Resource field (Ex. ResourceName).</summary> ///<param name="resourceId" type="Object">Either a string or value of the Resource Id.</param> ///<param name="resourceField" type="Office.ProjectResourceFields">Resource Field.</param> ///<param name="fieldValue" type="Object">Either a string, number boolean or object for the data that you want to set.</param> ///<param name="callback" type="function" optional="true">The optional callback method</param> } } } } } } } }); // Setup outlook Office._processItem(Office, { metaOnly: true, conditions: { hosts: ["outlook", "outlookcompose"], reqs: ["set Mailbox GE 1.1"] }, contents: { MailboxEnums: { value: new Office._MailboxEnums() }, context: { contents: { mailbox: { value: new Office._context_mailbox() }, roamingSettings: { value: new Office._settings() } } }, cast: { value: { item: new Office._cast_item() } } } }) // Setup CustomXMLParts Office._addEnumOnObject("CustomXmlNodeType", { ///<field type="String">Element</field> Element: "element", ///<field type="String">Attribute</field> Attribute: "attribute", ///<field type="String">String/field> Text: "text", ///<field type="String">CData</field> Cdata: "cdata", ///<field type="String">ProcessingInstruction</field> ProcessingInstruction: "processingInstruction", ///<field type="String">NodeComment</field> NodeComment: "nodeComment", ///<field type="String">NodeDocument</field> NodeDocument: "nodeDocument" }, Office, { hosts: ["word"] } ); // Other enumerations on Office Office._addEnumOnObject("AsyncResultStatus", { ///<field type="String">Operation failed, check error object</field> Failed: "failed", ///<field type="String">Operation succeeded</field> Succeeded: "succeeded" }, Office, { hosts: ["not outlook; not outlookcompose"] } ); Office._processItem(Office, { contents: { Text: { conditions: { hosts: ["excel", "word"], reqs: ["set TextBindings GE 1.1"] }, annotate: { ///<field type="String">Text based Binding</field> Text: undefined }, value: "text" }, Matrix: { conditions: { hosts: ["excel", "word"], reqs: ["set MatrixBindings GE 1.1"] }, annotate: { ///<field type="String">Matrix based Binding</field> Matrix: undefined }, value: "matrix" }, Table: { conditions: { hosts: ["excel", "word", "accesswebapp"], reqs: ["set TableBindings GE 1.1"] }, annotate: { ///<field type="String">Table based Binding</field> Table: undefined }, value: "table" } } }, "BindingType" ); Office._processItem(Office, { contents: { Table: { conditions: { hosts: ["word", "excel", "accesswebapp"], reqs: ["set TableCoercion GE 1.1"] }, annotate: { ///<field type="String">Coerce as Table</field> Table: undefined }, value: "table" }, Text: { conditions: { hosts: ["excel", "ppt", "project", "word"], reqs: ["set TextCoercion GE 1.1"] }, annotate: { ///<field type="String">Coerce as Text</field> Text: undefined }, value: "text" }, Matrix: { conditions: { hosts: ["excel", "word"], reqs: ["set MatrixCoercion GE 1.1"] }, annotate: { ///<field type="String">Coerce as Matrix</field> Matrix: undefined }, value: "matrix" }, Html: { conditions: { hosts: ["word"], reqs: ["set HtmlCoercion GE 1.1"] }, annotate: { ///<field type="String">Coerce as HTML</field> Html: undefined }, value: "html" }, Ooxml: { conditions: { hosts: ["word"], reqs: ["set OoxmlCoercion GE 1.1"] }, annotate: { ///<field type="String">Coerce as Office Open XML</field> Ooxml: undefined }, value: "ooxml" }, SlideRange: { conditions: { hosts: ["ppt"] }, annotate: { ///<field type="String">Coerce as JSON object containing an array of the ids, titles, and indexes of the selected slides.</field> SlideRange: undefined }, value: "slideRange" } } }, "CoercionType" ); Office._addEnumOnObject("DocumentMode", { ///<field type="String">Document in Read Only Mode</field> ReadOnly: "readOnly", ///<field type="String">Document in Read/Write Mode</field> ReadWrite: "readWrite" }, Office, { hosts: ["word", "excel", "accesswebapp"] } ); Office._addEnumOnObject("EventType", { ///<field type="String">Triggers when a document level selection happens</field> DocumentSelectionChanged: "documentSelectionChanged", ///<field type="String"> Triggers when a binding level selection happens</field> BindingSelectionChanged: "bindingSelectionChanged", ///<field type="String">Triggers when a binding level data change happens</field> BindingDataChanged: "bindingDataChanged", ///<field type="String">Triggers when settings change in a co-Auth session.</field> SettingsChanged: "settingsChanged", ///<field type="String">Triggers when a customXmlPart node was deleted</field> NodeDeleted: "nodeDeleted", ///<field type="String">Triggers when a customXmlPart node was inserted</field> NodeInserted: "nodeInserted", ///<field type="String">Triggers when a customXmlPart node was replaced</field> NodeReplaced: "nodeReplaced", ///<field type="String">Triggers when a Task selection happens in Project.</field> TaskSelectionChanged: "taskSelectionChanged", ///<field type="String"> Triggers when a Resource selection happens in Project.</field> ResourceSelectionChanged: "resourceSelectionChanged", ///<field type="String">Triggers when a View selection happens in Project.</field> ViewSelectionChanged: "viewSelectionChanged" }, Office, { hosts: ["not outlook; not outlookcompose"] } ); // EventType augmentations Office._processContents(Office.EventType, { ActiveViewChanged: { conditions: { hosts: ["ppt"] }, annotate: { ///<field type="String">Occurs when the user changes the current view of the document.</field> ActiveViewChanged: undefined }, value: "activeViewChanged" } }); Office._processItem(Office, { conditions: { hosts: ["not outlook; not outlookcompose; not accesswebapp"] }, contents: { Compressed: { conditions: { hosts: ["ppt", "word"], reqs: ["set CompressedFile GE 1.1"] }, annotate: { ///<field type="String">Returns the file as a byte array </field> Compressed: undefined }, value: "compressed" }, Pdf: { conditions: { hosts: ["ppt", "word"], reqs: ["set PdfFile GE 1.1"] }, annotate: { ///<field type="String">Returns the file in PDF format as a byte array</field> Pdf: undefined }, value: "pdf" }, Text: { conditions: { hosts: ["word"], reqs: ["set TextFile GE 1.1"] }, annotate: { ///<field type="String">Returns the file as plain text</field> Text: undefined }, value: "text" } } }, "FileType" ); Office._addEnumOnObject("FilterType", { ///<field type="String">Returns all items</field> All: "all", ///<field type="String">Returns only visible items</field> OnlyVisible: "onlyVisible" }, Office, { hosts: ["not outlook; not outlookcompose; not accesswebapp"] } ); Office._addEnumOnObject("InitializationReason", { ///<field type="String">Indicates the app was just inserted in the document /field> Inserted: "inserted", ///<field type="String">Indicated if the extension already existed in the document</field> DocumentOpened: "documentOpened" }, Office, { hosts: ["not outlook; not outlookcompose"] } ); Office._addEnumOnObject("ValueFormat", { ///<field type="String">Returns items with format</field> Formatted: "formatted", ///<field type="String">Returns items without format</field> Unformatted: "unformatted" }, Office, { hosts: ["not outlook; not outlookcompose"] } ); Office._processContents(Office, { GoToType: { contents: { Binding: { conditions: { hosts: ["excel", "word"] }, annotate: { ///<field type="String">Goes to a binding object using the specified binding id.</field> Binding: undefined }, value: "binding" }, NamedItem: { conditions: { hosts: ["excel"] }, annotate: { /// <field type="String"> /// Goes to a named item using that item's name. /// &#10; In Excel, you can use any structured reference for a named range or table: "Worksheet2!Table1" /// </field> NamedItem: undefined }, value: "namedItem" }, Slide: { conditions: { hosts: ["ppt"] }, annotate: { ///<field type="String">Goes to a slide using the specified id.</field> Slide: undefined }, value: "slide" }, Index: { conditions: { hosts: ["ppt"] }, annotate: { ///<field type="String">Goes to the specified index by slide number or enum Office.Index</field> Index: undefined }, value: "index" } } } }); Office._addEnumOnObject("Index", { First: "first", Last: "last", Next: "next", Previous: "previous" }, Office, { hosts: ["ppt"] } ); Office._addEnumOnObject("SelectionMode", { Default: "default", Selected: "selected", None: "none" }, Office, { hosts: ["word"] } ); if (!!intellisense) { intellisense.addEventListener('statementcompletion', function (event) { if (event.targetName === "this" || event.target === undefined || event.target === window) return; event.items = event.items.filter(function (item) { return !(item.name && item.name.charAt(0) === "_"); }); }); } Office._processContents(Office, Office._items); document.addEventListener("DOMContentLoaded", function () { Office.initialize(); }); var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var OfficeExtension; (function (OfficeExtension) { var ClientObject = (function () { function ClientObject() { /// <summary> /// An abstract proxy object that represents an object in an Office document. You create proxy objects from the context (or from other proxy objects), add commands to a queue to act on the object, and then synchronize the proxy object state with the document by calling "context.sync()". /// </summary> /// <field name="context" type="OfficeExtension.ClientRequestContext"></field> } return ClientObject; })(); OfficeExtension.ClientObject = ClientObject; })(OfficeExtension || (OfficeExtension = {})); var OfficeExtension; (function (OfficeExtension) { var ClientRequestContext = (function () { function ClientRequestContext(url) { /// <summary> /// An abstract RequestContext object that facilitates requests to the host Office application. The "Excel.run" and "Word.run" methods provide a request context. /// </summary> /// <field name="trackedObjects" type="OfficeExtension.TrackedObjects"> Collection of objects that are tracked for automatic adjustments based on surrounding changes in the document. </field> } ClientRequestContext.prototype.load = function (object, option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="object" type="OfficeExtension.ClientObject" /> /// <param name="option" type="string|string[]|{select?, expand?, top?, skip?}" /> }; ClientRequestContext.prototype.trace = function (message) { /// <summary> /// Adds a trace message to the queue. If the promise returned by "context.sync()" is rejected due to an error, this adds a ".traceMessages" array to the OfficeExtension.Error object, containing all trace messages that were executed. These messages can help you monitor the program execution sequence and detect the cause of the error. /// </summary> /// <param name="message" type="String" /> }; ClientRequestContext.prototype.sync = function (passThroughValue) { /// <summary> /// Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code.ÿThis method returns a promise, which is resolved when the synchronization is complete. /// </summary> /// <param name="passThroughValue" optional="true" /> return new OfficeExtension.IPromise(); }; ClientRequestContext.prototype.__proto__ = null; return ClientRequestContext; })(); OfficeExtension.ClientRequestContext = ClientRequestContext; })(OfficeExtension || (OfficeExtension = {})); var OfficeExtension; (function (OfficeExtension) { var ClientResult = (function () { function ClientResult() { /// <summary> /// Contains the result for methods that return primitive types. The object's value property is retrieved from the document after "context.sync()" is invoked. /// </summary> /// <field name="value"> /// The value of the result that is retrieved from the document after "context.sync()" is invoked. /// </field> } ClientResult.prototype.__proto__ = null; return ClientResult; })(); OfficeExtension.ClientResult = ClientResult; })(OfficeExtension || (OfficeExtension = {})); var OfficeExtension; (function (OfficeExtension) { var Error = (function () { function Error() { /// <summary> /// The error object returned by "context.sync()", if a promise is rejected due to an error while processing the request. /// </summary> /// <field name="name" type="String"> /// Error name: "OfficeExtension.Error" /// </field> /// <field name="message" type="String"> /// The error message passed through from the host Office application. /// </field> /// <field name="stack" type="String"> /// Stack trace, if applicable. /// </field> /// <field name="code" type="String"> /// Error code string, such as "InvalidArgument". /// </field> /// <field name="traceMessages" type="Array" elementType="string"> /// Trace messages (if any) that were added via a "context.trace()" invocation before calling "context.sync()". If there was an error, this contains all trace messages that were executed before the error occurred. These messages can help you monitor the program execution sequence and detect the case of the error. /// </field> /// <field name="debugInfo"> /// Debug info, if applicable. The ".errorLocation" property can describe the object and method or property that caused the error. /// </field> this.debugInfo = { __proto__: null, /// <field name="errorLocation" type="string" optional="true"> /// If applicable, will return the object type and the name of the method or property that caused the error. /// </field> errorLocation: "" }; } Error.prototype.__proto__ = null; return Error; })(); OfficeExtension.Error = Error; })(OfficeExtension || (OfficeExtension = {})); var OfficeExtension; (function (OfficeExtension) { var ErrorCodes = (function () { function ErrorCodes() { } ErrorCodes.__proto__ = null; ErrorCodes.accessDenied = ""; ErrorCodes.generalException = ""; ErrorCodes.activityLimitReached = ""; return ErrorCodes; })(); })(OfficeExtension || (OfficeExtension = {})); var OfficeExtension; (function (OfficeExtension) { var IPromise = (function () { /// <summary> /// A Promise object that represents a deferred interaction with the host Office application. Promises can be chained via ".then", and errors can be caught via ".catch". Remember to always use a ".catch" on the outer promise, and to return intermediary promises so as not to break the promise chain. /// </summary> IPromise.prototype.then = function (onFulfilled, onRejected) { /// <summary> /// This method will be called once the previous promise has been resolved. /// Both the onFulfilled on onRejected callbacks are optional. /// If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. /// Returns a new promise for the value or error that was returned from onFulfilled/onRejected. /// </summary> /// <param name="onFulfilled" type="Function" optional="true"></param> /// <param name="onRejected" type="Function" optional="true"></param> /// <returns type="OfficeExtension.IPromise"></returns> onRejected(new Error()); } IPromise.prototype.catch = function (onRejected) { /// <summary> /// Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. /// </summary> /// <param name="onRejected" type="Function" optional="true">function to be called if or when the promise rejects.</param> /// <returns type="OfficeExtension.IPromise"></returns> onRejected(new Error()); } IPromise.prototype.__proto__ = null; }) OfficeExtension.IPromise = IPromise; })(OfficeExtension || (OfficeExtension = {})); var OfficeExtension; (function (OfficeExtension) { var TrackedObjects = (function () { function TrackedObjects() { /// <summary> /// Collection of tracked objects, contained within a request context. See "context.trackedObjects" for more information. /// </summary> } TrackedObjects.prototype.add = function (object) { /// <summary> /// Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. /// </summary> /// <param name="object" type="OfficeExtension.ClientObject|OfficeExtension.ClientObject[]"></param> }; TrackedObjects.prototype.remove = function (object) { /// <summary> /// Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. /// </summary> /// <param name="object" type="OfficeExtension.ClientObject|OfficeExtension.ClientObject[]"></param> }; TrackedObjects.prototype.__proto__ = null; return TrackedObjects; })(); OfficeExtension.TrackedObjects = TrackedObjects; })(OfficeExtension || (OfficeExtension = {})); OfficeExtension.__proto__ = null; var Excel; (function (Excel) { var Application = (function(_super) { __extends(Application, _super); function Application() { /// <summary> Represents the Excel application that manages the workbook. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="calculationMode" type="String">Returns the calculation mode used in the workbook. See Excel.CalculationMode for details. Read-only.</field> } Application.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.Application"/> } Application.prototype.calculate = function(calculationType) { /// <summary> /// Recalculate all currently opened workbooks in Excel. /// </summary> /// <param name="calculationType" type="String">Specifies the calculation type to use. See Excel.CalculationType for details.</param> /// <returns ></returns> } return Application; })(OfficeExtension.ClientObject); Excel.Application = Application; })(Excel || (Excel = {})); var Excel; (function (Excel) { var Binding = (function(_super) { __extends(Binding, _super); function Binding() { /// <summary> Represents an Office.js binding that is defined in the workbook. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="id" type="String">Represents binding identifier. Read-only.</field> /// <field name="type" type="String">Returns the type of the binding. See Excel.BindingType for details. Read-only.</field> } Binding.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.Binding"/> } Binding.prototype.getRange = function() { /// <summary> /// Returns the range represented by the binding. Will throw an error if binding is not of the correct type. /// </summary> /// <returns type="Excel.Range"></returns> } Binding.prototype.getTable = function() { /// <summary> /// Returns the table represented by the binding. Will throw an error if binding is not of the correct type. /// </summary> /// <returns type="Excel.Table"></returns> } Binding.prototype.getText = function() { /// <summary> /// Returns the text represented by the binding. Will throw an error if binding is not of the correct type. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } return Binding; })(OfficeExtension.ClientObject); Excel.Binding = Binding; })(Excel || (Excel = {})); var Excel; (function (Excel) { var BindingCollection = (function(_super) { __extends(BindingCollection, _super); function BindingCollection() { /// <summary> Represents the collection of all the binding objects that are part of the workbook. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Returns the number of bindings in the collection. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.Binding">Gets the loaded child items in this collection.</field> } BindingCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.BindingCollection"/> } BindingCollection.prototype.getItem = function(id) { /// <summary> /// Gets a binding object by ID. /// </summary> /// <param name="id" type="String">Id of the binding object to be retrieved.</param> /// <returns type="Excel.Binding"></returns> } BindingCollection.prototype.getItemAt = function(index) { /// <summary> /// Gets a binding object based on its position in the items array. /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.Binding"></returns> } return BindingCollection; })(OfficeExtension.ClientObject); Excel.BindingCollection = BindingCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var BindingType = { __proto__: null, "range": "range", "table": "table", "text": "text", } Excel.BindingType = BindingType; })(Excel || (Excel = {})); var Excel; (function (Excel) { var BorderIndex = { __proto__: null, "edgeTop": "edgeTop", "edgeBottom": "edgeBottom", "edgeLeft": "edgeLeft", "edgeRight": "edgeRight", "insideVertical": "insideVertical", "insideHorizontal": "insideHorizontal", "diagonalDown": "diagonalDown", "diagonalUp": "diagonalUp", } Excel.BorderIndex = BorderIndex; })(Excel || (Excel = {})); var Excel; (function (Excel) { var BorderLineStyle = { __proto__: null, "none": "none", "continuous": "continuous", "dash": "dash", "dashDot": "dashDot", "dashDotDot": "dashDotDot", "dot": "dot", "double": "double", "slantDashDot": "slantDashDot", } Excel.BorderLineStyle = BorderLineStyle; })(Excel || (Excel = {})); var Excel; (function (Excel) { var BorderWeight = { __proto__: null, "hairline": "hairline", "thin": "thin", "medium": "medium", "thick": "thick", } Excel.BorderWeight = BorderWeight; })(Excel || (Excel = {})); var Excel; (function (Excel) { var CalculationMode = { __proto__: null, "automatic": "automatic", "automaticExceptTables": "automaticExceptTables", "manual": "manual", } Excel.CalculationMode = CalculationMode; })(Excel || (Excel = {})); var Excel; (function (Excel) { var CalculationType = { __proto__: null, "recalculate": "recalculate", "full": "full", "fullRebuild": "fullRebuild", } Excel.CalculationType = CalculationType; })(Excel || (Excel = {})); var Excel; (function (Excel) { var Chart = (function(_super) { __extends(Chart, _super); function Chart() { /// <summary> Represents a chart object in a workbook. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="axes" type="Excel.ChartAxes">Represents chart axes. Read-only.</field> /// <field name="dataLabels" type="Excel.ChartDataLabels">Represents the datalabels on the chart. Read-only.</field> /// <field name="format" type="Excel.ChartAreaFormat">Encapsulates the format properties for the chart area. Read-only.</field> /// <field name="height" type="Number">Represents the height, in points, of the chart object.</field> /// <field name="left" type="Number">The distance, in points, from the left side of the chart to the worksheet origin.</field> /// <field name="legend" type="Excel.ChartLegend">Represents the legend for the chart. Read-only.</field> /// <field name="name" type="String">Represents the name of a chart object.</field> /// <field name="series" type="Excel.ChartSeriesCollection">Represents either a single series or collection of series in the chart. Read-only.</field> /// <field name="title" type="Excel.ChartTitle">Represents the title of the specified chart, including the text, visibility, position and formating of the title. Read-only.</field> /// <field name="top" type="Number">Represents the distance, in points, from the top edge of the object to the top of row 1 (on a worksheet) or the top of the chart area (on a chart).</field> /// <field name="width" type="Number">Represents the width, in points, of the chart object.</field> } Chart.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.Chart"/> } Chart.prototype.delete = function() { /// <summary> /// Deletes the chart object. /// </summary> /// <returns ></returns> } Chart.prototype.setData = function(sourceData, seriesBy) { /// <summary> /// Resets the source data for the chart. /// </summary> /// <param name="sourceData" >The Range object corresponding to the source data.</param> /// <param name="seriesBy" type="String" optional="true">Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, Columns. See Excel.ChartSeriesBy for details.</param> /// <returns ></returns> } Chart.prototype.setPosition = function(startCell, endCell) { /// <summary> /// Positions the chart relative to cells on the worksheet. /// </summary> /// <param name="startCell" >The start cell. This is where the chart will be moved to. The start cell is the top-left or top-right cell, depending on the user&apos;s right-to-left display settings.</param> /// <param name="endCell" optional="true">(Optional) The end cell. If specified, the chart&apos;s width and height will be set to fully cover up this cell/range.</param> /// <returns ></returns> } return Chart; })(OfficeExtension.ClientObject); Excel.Chart = Chart; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartAreaFormat = (function(_super) { __extends(ChartAreaFormat, _super); function ChartAreaFormat() { /// <summary> Encapsulates the format properties for the overall chart area. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="fill" type="Excel.ChartFill">Represents the fill format of an object, which includes background formatting information. Read-only.</field> /// <field name="font" type="Excel.ChartFont">Represents the font attributes (font name, font size, color, etc.) for the current object. Read-only.</field> } ChartAreaFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartAreaFormat"/> } return ChartAreaFormat; })(OfficeExtension.ClientObject); Excel.ChartAreaFormat = ChartAreaFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartAxes = (function(_super) { __extends(ChartAxes, _super); function ChartAxes() { /// <summary> Represents the chart axes. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="categoryAxis" type="Excel.ChartAxis">Represents the category axis in a chart. Read-only.</field> /// <field name="seriesAxis" type="Excel.ChartAxis">Represents the series axis of a 3-dimensional chart. Read-only.</field> /// <field name="valueAxis" type="Excel.ChartAxis">Represents the value axis in an axis. Read-only.</field> } ChartAxes.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartAxes"/> } return ChartAxes; })(OfficeExtension.ClientObject); Excel.ChartAxes = ChartAxes; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartAxis = (function(_super) { __extends(ChartAxis, _super); function ChartAxis() { /// <summary> Represents a single axis in a chart. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartAxisFormat">Represents the formatting of a chart object, which includes line and font formatting. Read-only.</field> /// <field name="majorGridlines" type="Excel.ChartGridlines">Returns a gridlines object that represents the major gridlines for the specified axis. Read-only.</field> /// <field name="majorUnit" >Represents the interval between two major tick marks. Can be set to a numeric value or an empty string. The returned value is always a number.</field> /// <field name="maximum" >Represents the maximum value on the value axis. Can be set to a numeric value or an empty string (for automatic axis values). The returned value is always a number.</field> /// <field name="minimum" >Represents the minimum value on the value axis. Can be set to a numeric value or an empty string (for automatic axis values). The returned value is always a number.</field> /// <field name="minorGridlines" type="Excel.ChartGridlines">Returns a Gridlines object that represents the minor gridlines for the specified axis. Read-only.</field> /// <field name="minorUnit" >Represents the interval between two minor tick marks. &quot;Can be set to a numeric value or an empty string (for automatic axis values). The returned value is always a number.</field> /// <field name="title" type="Excel.ChartAxisTitle">Represents the axis title. Read-only.</field> } ChartAxis.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartAxis"/> } return ChartAxis; })(OfficeExtension.ClientObject); Excel.ChartAxis = ChartAxis; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartAxisFormat = (function(_super) { __extends(ChartAxisFormat, _super); function ChartAxisFormat() { /// <summary> Encapsulates the format properties for the chart axis. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="font" type="Excel.ChartFont">Represents the font attributes (font name, font size, color, etc.) for a chart axis element. Read-only.</field> /// <field name="line" type="Excel.ChartLineFormat">Represents chart line formatting. Read-only.</field> } ChartAxisFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartAxisFormat"/> } return ChartAxisFormat; })(OfficeExtension.ClientObject); Excel.ChartAxisFormat = ChartAxisFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartAxisTitle = (function(_super) { __extends(ChartAxisTitle, _super); function ChartAxisTitle() { /// <summary> Represents the title of a chart axis. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartAxisTitleFormat">Represents the formatting of chart axis title. Read-only.</field> /// <field name="text" type="String">Represents the axis title.</field> /// <field name="visible" type="Boolean">A boolean that specifies the visibility of an axis title.</field> } ChartAxisTitle.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartAxisTitle"/> } return ChartAxisTitle; })(OfficeExtension.ClientObject); Excel.ChartAxisTitle = ChartAxisTitle; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartAxisTitleFormat = (function(_super) { __extends(ChartAxisTitleFormat, _super); function ChartAxisTitleFormat() { /// <summary> Represents the chart axis title formatting. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="font" type="Excel.ChartFont">Represents the font attributes, such as font name, font size, color, etc. of chart axis title object. Read-only.</field> } ChartAxisTitleFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartAxisTitleFormat"/> } return ChartAxisTitleFormat; })(OfficeExtension.ClientObject); Excel.ChartAxisTitleFormat = ChartAxisTitleFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartCollection = (function(_super) { __extends(ChartCollection, _super); function ChartCollection() { /// <summary> A collection of all the chart objects on a worksheet. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Returns the number of charts in the worksheet. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.Chart">Gets the loaded child items in this collection.</field> } ChartCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartCollection"/> } ChartCollection.prototype.add = function(type, sourceData, seriesBy) { /// <summary> /// Creates a new chart. /// </summary> /// <param name="type" type="String">Represents the type of a chart. See Excel.ChartType for details.</param> /// <param name="sourceData" >The Range object corresponding to the source data.</param> /// <param name="seriesBy" type="String" optional="true">Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details.</param> /// <returns type="Excel.Chart"></returns> } ChartCollection.prototype.getItem = function(name) { /// <summary> /// Gets a chart using its name. If there are multiple charts with the same name, the first one will be returned. /// </summary> /// <param name="name" type="String">Name of the chart to be retrieved.</param> /// <returns type="Excel.Chart"></returns> } ChartCollection.prototype.getItemAt = function(index) { /// <summary> /// Gets a chart based on its position in the collection. /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.Chart"></returns> } return ChartCollection; })(OfficeExtension.ClientObject); Excel.ChartCollection = ChartCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartDataLabelFormat = (function(_super) { __extends(ChartDataLabelFormat, _super); function ChartDataLabelFormat() { /// <summary> Encapsulates the format properties for the chart data labels. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="fill" type="Excel.ChartFill">Represents the fill format of the current chart data label. Read-only.</field> /// <field name="font" type="Excel.ChartFont">Represents the font attributes (font name, font size, color, etc.) for a chart data label. Read-only.</field> } ChartDataLabelFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartDataLabelFormat"/> } return ChartDataLabelFormat; })(OfficeExtension.ClientObject); Excel.ChartDataLabelFormat = ChartDataLabelFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartDataLabelPosition = { __proto__: null, "invalid": "invalid", "none": "none", "center": "center", "insideEnd": "insideEnd", "insideBase": "insideBase", "outsideEnd": "outsideEnd", "left": "left", "right": "right", "top": "top", "bottom": "bottom", "bestFit": "bestFit", "callout": "callout", } Excel.ChartDataLabelPosition = ChartDataLabelPosition; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartDataLabels = (function(_super) { __extends(ChartDataLabels, _super); function ChartDataLabels() { /// <summary> Represents a collection of all the data labels on a chart point. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartDataLabelFormat">Represents the format of chart data labels, which includes fill and font formatting. Read-only.</field> /// <field name="position" type="String">DataLabelPosition value that represents the position of the data label. See Excel.ChartDataLabelPosition for details.</field> /// <field name="separator" type="String">String representing the separator used for the data labels on a chart.</field> /// <field name="showBubbleSize" type="Boolean">Boolean value representing if the data label bubble size is visible or not.</field> /// <field name="showCategoryName" type="Boolean">Boolean value representing if the data label category name is visible or not.</field> /// <field name="showLegendKey" type="Boolean">Boolean value representing if the data label legend key is visible or not.</field> /// <field name="showPercentage" type="Boolean">Boolean value representing if the data label percentage is visible or not.</field> /// <field name="showSeriesName" type="Boolean">Boolean value representing if the data label series name is visible or not.</field> /// <field name="showValue" type="Boolean">Boolean value representing if the data label value is visible or not.</field> } ChartDataLabels.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartDataLabels"/> } return ChartDataLabels; })(OfficeExtension.ClientObject); Excel.ChartDataLabels = ChartDataLabels; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartFill = (function(_super) { __extends(ChartFill, _super); function ChartFill() { /// <summary> Represents the fill formatting for a chart element. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> } ChartFill.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartFill"/> } ChartFill.prototype.clear = function() { /// <summary> /// Clear the fill color of a chart element. /// </summary> /// <returns ></returns> } ChartFill.prototype.setSolidColor = function(color) { /// <summary> /// Sets the fill formatting of a chart element to a uniform color. /// </summary> /// <param name="color" type="String">HTML color code representing the color of the border line, of the form #RRGGBB (e.g. &quot;FFA500&quot;) or as a named HTML color (e.g. &quot;orange&quot;).</param> /// <returns ></returns> } return ChartFill; })(OfficeExtension.ClientObject); Excel.ChartFill = ChartFill; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartFont = (function(_super) { __extends(ChartFont, _super); function ChartFont() { /// <summary> This object represents the font attributes (font name, font size, color, etc.) for a chart object. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="bold" type="Boolean">Represents the bold status of font.</field> /// <field name="color" type="String">HTML color code representation of the text color. E.g. #FF0000 represents Red.</field> /// <field name="italic" type="Boolean">Represents the italic status of the font.</field> /// <field name="name" type="String">Font name (e.g. &quot;Calibri&quot;)</field> /// <field name="size" type="Number">Size of the font (e.g. 11)</field> /// <field name="underline" type="String">Type of underline applied to the font. See Excel.ChartUnderlineStyle for details.</field> } ChartFont.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartFont"/> } return ChartFont; })(OfficeExtension.ClientObject); Excel.ChartFont = ChartFont; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartGridlines = (function(_super) { __extends(ChartGridlines, _super); function ChartGridlines() { /// <summary> Represents major or minor gridlines on a chart axis. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartGridlinesFormat">Represents the formatting of chart gridlines. Read-only.</field> /// <field name="visible" type="Boolean">Boolean value representing if the axis gridlines are visible or not.</field> } ChartGridlines.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartGridlines"/> } return ChartGridlines; })(OfficeExtension.ClientObject); Excel.ChartGridlines = ChartGridlines; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartGridlinesFormat = (function(_super) { __extends(ChartGridlinesFormat, _super); function ChartGridlinesFormat() { /// <summary> Encapsulates the format properties for chart gridlines. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="line" type="Excel.ChartLineFormat">Represents chart line formatting. Read-only.</field> } ChartGridlinesFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartGridlinesFormat"/> } return ChartGridlinesFormat; })(OfficeExtension.ClientObject); Excel.ChartGridlinesFormat = ChartGridlinesFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartLegend = (function(_super) { __extends(ChartLegend, _super); function ChartLegend() { /// <summary> Represents the legend in a chart. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartLegendFormat">Represents the formatting of a chart legend, which includes fill and font formatting. Read-only.</field> /// <field name="overlay" type="Boolean">Boolean value for whether the chart legend should overlap with the main body of the chart.</field> /// <field name="position" type="String">Represents the position of the legend on the chart. See Excel.ChartLegendPosition for details.</field> /// <field name="visible" type="Boolean">A boolean value the represents the visibility of a ChartLegend object.</field> } ChartLegend.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartLegend"/> } return ChartLegend; })(OfficeExtension.ClientObject); Excel.ChartLegend = ChartLegend; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartLegendFormat = (function(_super) { __extends(ChartLegendFormat, _super); function ChartLegendFormat() { /// <summary> Encapsulates the format properties of a chart legend. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="fill" type="Excel.ChartFill">Represents the fill format of an object, which includes background formating information. Read-only.</field> /// <field name="font" type="Excel.ChartFont">Represents the font attributes such as font name, font size, color, etc. of a chart legend. Read-only.</field> } ChartLegendFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartLegendFormat"/> } return ChartLegendFormat; })(OfficeExtension.ClientObject); Excel.ChartLegendFormat = ChartLegendFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartLegendPosition = { __proto__: null, "invalid": "invalid", "top": "top", "bottom": "bottom", "left": "left", "right": "right", "corner": "corner", "custom": "custom", } Excel.ChartLegendPosition = ChartLegendPosition; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartLineFormat = (function(_super) { __extends(ChartLineFormat, _super); function ChartLineFormat() { /// <summary> Enapsulates the formatting options for line elements. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="color" type="String">HTML color code representing the color of lines in the chart.</field> } ChartLineFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartLineFormat"/> } ChartLineFormat.prototype.clear = function() { /// <summary> /// Clear the line format of a chart element. /// </summary> /// <returns ></returns> } return ChartLineFormat; })(OfficeExtension.ClientObject); Excel.ChartLineFormat = ChartLineFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartPoint = (function(_super) { __extends(ChartPoint, _super); function ChartPoint() { /// <summary> Represents a point of a series in a chart. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartPointFormat">Encapsulates the format properties chart point. Read-only.</field> /// <field name="value" >Returns the value of a chart point. Read-only.</field> } ChartPoint.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartPoint"/> } return ChartPoint; })(OfficeExtension.ClientObject); Excel.ChartPoint = ChartPoint; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartPointFormat = (function(_super) { __extends(ChartPointFormat, _super); function ChartPointFormat() { /// <summary> Represents formatting object for chart points. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="fill" type="Excel.ChartFill">Represents the fill format of a chart, which includes background formating information. Read-only.</field> } ChartPointFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartPointFormat"/> } return ChartPointFormat; })(OfficeExtension.ClientObject); Excel.ChartPointFormat = ChartPointFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartPointsCollection = (function(_super) { __extends(ChartPointsCollection, _super); function ChartPointsCollection() { /// <summary> A collection of all the chart points within a series inside a chart. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Returns the number of chart points in the collection. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.ChartPoint">Gets the loaded child items in this collection.</field> } ChartPointsCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartPointsCollection"/> } ChartPointsCollection.prototype.getItemAt = function(index) { /// <summary> /// Retrieve a point based on its position within the series. /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.ChartPoint"></returns> } return ChartPointsCollection; })(OfficeExtension.ClientObject); Excel.ChartPointsCollection = ChartPointsCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartSeries = (function(_super) { __extends(ChartSeries, _super); function ChartSeries() { /// <summary> Represents a series in a chart. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartSeriesFormat">Represents the formatting of a chart series, which includes fill and line formatting. Read-only.</field> /// <field name="name" type="String">Represents the name of a series in a chart.</field> /// <field name="points" type="Excel.ChartPointsCollection">Represents a collection of all points in the series. Read-only.</field> } ChartSeries.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartSeries"/> } return ChartSeries; })(OfficeExtension.ClientObject); Excel.ChartSeries = ChartSeries; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartSeriesBy = { __proto__: null, "auto": "auto", "columns": "columns", "rows": "rows", } Excel.ChartSeriesBy = ChartSeriesBy; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartSeriesCollection = (function(_super) { __extends(ChartSeriesCollection, _super); function ChartSeriesCollection() { /// <summary> Represents a collection of chart series. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Returns the number of series in the collection. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.ChartSeries">Gets the loaded child items in this collection.</field> } ChartSeriesCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartSeriesCollection"/> } ChartSeriesCollection.prototype.getItemAt = function(index) { /// <summary> /// Retrieves a series based on its position in the collection /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.ChartSeries"></returns> } return ChartSeriesCollection; })(OfficeExtension.ClientObject); Excel.ChartSeriesCollection = ChartSeriesCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartSeriesFormat = (function(_super) { __extends(ChartSeriesFormat, _super); function ChartSeriesFormat() { /// <summary> encapsulates the format properties for the chart series </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="fill" type="Excel.ChartFill">Represents the fill format of a chart series, which includes background formating information. Read-only.</field> /// <field name="line" type="Excel.ChartLineFormat">Represents line formatting. Read-only.</field> } ChartSeriesFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartSeriesFormat"/> } return ChartSeriesFormat; })(OfficeExtension.ClientObject); Excel.ChartSeriesFormat = ChartSeriesFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartTitle = (function(_super) { __extends(ChartTitle, _super); function ChartTitle() { /// <summary> Represents a chart title object of a chart. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="format" type="Excel.ChartTitleFormat">Represents the formatting of a chart title, which includes fill and font formatting. Read-only.</field> /// <field name="overlay" type="Boolean">Boolean value representing if the chart title will overlay the chart or not.</field> /// <field name="text" type="String">Represents the title text of a chart.</field> /// <field name="visible" type="Boolean">A boolean value the represents the visibility of a chart title object.</field> } ChartTitle.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartTitle"/> } return ChartTitle; })(OfficeExtension.ClientObject); Excel.ChartTitle = ChartTitle; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartTitleFormat = (function(_super) { __extends(ChartTitleFormat, _super); function ChartTitleFormat() { /// <summary> Provides access to the office art formatting for chart title. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="fill" type="Excel.ChartFill">Represents the fill format of an object, which includes background formating information. Read-only.</field> /// <field name="font" type="Excel.ChartFont">Represents the font attributes (font name, font size, color, etc.) for an object. Read-only.</field> } ChartTitleFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.ChartTitleFormat"/> } return ChartTitleFormat; })(OfficeExtension.ClientObject); Excel.ChartTitleFormat = ChartTitleFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartType = { __proto__: null, "invalid": "invalid", "columnClustered": "columnClustered", "columnStacked": "columnStacked", "columnStacked100": "columnStacked100", "_3DColumnClustered": "_3DColumnClustered", "_3DColumnStacked": "_3DColumnStacked", "_3DColumnStacked100": "_3DColumnStacked100", "barClustered": "barClustered", "barStacked": "barStacked", "barStacked100": "barStacked100", "_3DBarClustered": "_3DBarClustered", "_3DBarStacked": "_3DBarStacked", "_3DBarStacked100": "_3DBarStacked100", "lineStacked": "lineStacked", "lineStacked100": "lineStacked100", "lineMarkers": "lineMarkers", "lineMarkersStacked": "lineMarkersStacked", "lineMarkersStacked100": "lineMarkersStacked100", "pieOfPie": "pieOfPie", "pieExploded": "pieExploded", "_3DPieExploded": "_3DPieExploded", "barOfPie": "barOfPie", "xyscatterSmooth": "xyscatterSmooth", "xyscatterSmoothNoMarkers": "xyscatterSmoothNoMarkers", "xyscatterLines": "xyscatterLines", "xyscatterLinesNoMarkers": "xyscatterLinesNoMarkers", "areaStacked": "areaStacked", "areaStacked100": "areaStacked100", "_3DAreaStacked": "_3DAreaStacked", "_3DAreaStacked100": "_3DAreaStacked100", "doughnutExploded": "doughnutExploded", "radarMarkers": "radarMarkers", "radarFilled": "radarFilled", "surface": "surface", "surfaceWireframe": "surfaceWireframe", "surfaceTopView": "surfaceTopView", "surfaceTopViewWireframe": "surfaceTopViewWireframe", "bubble": "bubble", "bubble3DEffect": "bubble3DEffect", "stockHLC": "stockHLC", "stockOHLC": "stockOHLC", "stockVHLC": "stockVHLC", "stockVOHLC": "stockVOHLC", "cylinderColClustered": "cylinderColClustered", "cylinderColStacked": "cylinderColStacked", "cylinderColStacked100": "cylinderColStacked100", "cylinderBarClustered": "cylinderBarClustered", "cylinderBarStacked": "cylinderBarStacked", "cylinderBarStacked100": "cylinderBarStacked100", "cylinderCol": "cylinderCol", "coneColClustered": "coneColClustered", "coneColStacked": "coneColStacked", "coneColStacked100": "coneColStacked100", "coneBarClustered": "coneBarClustered", "coneBarStacked": "coneBarStacked", "coneBarStacked100": "coneBarStacked100", "coneCol": "coneCol", "pyramidColClustered": "pyramidColClustered", "pyramidColStacked": "pyramidColStacked", "pyramidColStacked100": "pyramidColStacked100", "pyramidBarClustered": "pyramidBarClustered", "pyramidBarStacked": "pyramidBarStacked", "pyramidBarStacked100": "pyramidBarStacked100", "pyramidCol": "pyramidCol", "_3DColumn": "_3DColumn", "line": "line", "_3DLine": "_3DLine", "_3DPie": "_3DPie", "pie": "pie", "xyscatter": "xyscatter", "_3DArea": "_3DArea", "area": "area", "doughnut": "doughnut", "radar": "radar", } Excel.ChartType = ChartType; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ChartUnderlineStyle = { __proto__: null, "none": "none", "single": "single", } Excel.ChartUnderlineStyle = ChartUnderlineStyle; })(Excel || (Excel = {})); var Excel; (function (Excel) { var ClearApplyTo = { __proto__: null, "all": "all", "formats": "formats", "contents": "contents", } Excel.ClearApplyTo = ClearApplyTo; })(Excel || (Excel = {})); var Excel; (function (Excel) { var DeleteShiftDirection = { __proto__: null, "up": "up", "left": "left", } Excel.DeleteShiftDirection = DeleteShiftDirection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var HorizontalAlignment = { __proto__: null, "general": "general", "left": "left", "center": "center", "right": "right", "fill": "fill", "justify": "justify", "centerAcrossSelection": "centerAcrossSelection", "distributed": "distributed", } Excel.HorizontalAlignment = HorizontalAlignment; })(Excel || (Excel = {})); var Excel; (function (Excel) { var InsertShiftDirection = { __proto__: null, "down": "down", "right": "right", } Excel.InsertShiftDirection = InsertShiftDirection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var NamedItem = (function(_super) { __extends(NamedItem, _super); function NamedItem() { /// <summary> Represents a defined name for a range of cells or value. Names can be primitive named objects (as seen in the type below), range object, reference to a range. This object can be used to obtain range object associated with names. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="name" type="String">The name of the object. Read-only.</field> /// <field name="type" type="String">Indicates what type of reference is associated with the name. See Excel.NamedItemType for details. Read-only.</field> /// <field name="value" >Represents the formula that the name is defined to refer to. E.g. =Sheet14!$B$2:$H$12, =4.75, etc. Read-only.</field> /// <field name="visible" type="Boolean">Specifies whether the object is visible or not.</field> } NamedItem.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.NamedItem"/> } NamedItem.prototype.getRange = function() { /// <summary> /// Returns the range object that is associated with the name. Throws an exception if the named item&apos;s type is not a range. /// </summary> /// <returns type="Excel.Range"></returns> } return NamedItem; })(OfficeExtension.ClientObject); Excel.NamedItem = NamedItem; })(Excel || (Excel = {})); var Excel; (function (Excel) { var NamedItemCollection = (function(_super) { __extends(NamedItemCollection, _super); function NamedItemCollection() { /// <summary> A collection of all the nameditem objects that are part of the workbook. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="items" type="Array" elementType="Excel.NamedItem">Gets the loaded child items in this collection.</field> } NamedItemCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.NamedItemCollection"/> } NamedItemCollection.prototype.getItem = function(name) { /// <summary> /// Gets a nameditem object using its name /// </summary> /// <param name="name" type="String">nameditem name.</param> /// <returns type="Excel.NamedItem"></returns> } return NamedItemCollection; })(OfficeExtension.ClientObject); Excel.NamedItemCollection = NamedItemCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var NamedItemType = { __proto__: null, "string": "string", "integer": "integer", "double": "double", "boolean": "boolean", "range": "range", } Excel.NamedItemType = NamedItemType; })(Excel || (Excel = {})); var Excel; (function (Excel) { var Range = (function(_super) { __extends(Range, _super); function Range() { /// <summary> Range represents a set of one or more contiguous cells such as a cell, a row, a column, block of cells, etc. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="address" type="String">Represents the range reference in A1-style. Address value will contain the Sheet reference (e.g. Sheet1!A1:B4). Read-only.</field> /// <field name="addressLocal" type="String">Represents range reference for the specified range in the language of the user. Read-only.</field> /// <field name="cellCount" type="Number">Number of cells in the range. Read-only.</field> /// <field name="columnCount" type="Number">Represents the total number of columns in the range. Read-only.</field> /// <field name="columnIndex" type="Number">Represents the column number of the first cell in the range. Zero-indexed. Read-only.</field> /// <field name="format" type="Excel.RangeFormat">Returns a format object, encapsulating the range&apos;s font, fill, borders, alignment, and other properties. Read-only.</field> /// <field name="formulas" type="Array" elementType="Array">Represents the formula in A1-style notation.</field> /// <field name="formulasLocal" type="Array" elementType="Array">Represents the formula in A1-style notation, in the user&apos;s language and number-formatting locale. For example, the English &quot;=SUM(A1, 1.5)&quot; formula would become &quot;=SUMME(A1; 1,5)&quot; in German.</field> /// <field name="numberFormat" type="Array" elementType="Array">Represents Excel&apos;s number format code for the given cell.</field> /// <field name="rowCount" type="Number">Returns the total number of rows in the range. Read-only.</field> /// <field name="rowIndex" type="Number">Returns the row number of the first cell in the range. Zero-indexed. Read-only.</field> /// <field name="text" type="Array" elementType="Array">Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only.</field> /// <field name="valueTypes" type="Array" elementType="Array">Represents the type of data of each cell. Read-only.</field> /// <field name="values" type="Array" elementType="Array">Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.</field> /// <field name="worksheet" type="Excel.Worksheet">The worksheet containing the current range. Read-only.</field> } Range.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.Range"/> } Range.prototype.clear = function(applyTo) { /// <summary> /// Clear range values, format, fill, border, etc. /// </summary> /// <param name="applyTo" type="String" optional="true">Determines the type of clear action. See Excel.ClearApplyTo for details.</param> /// <returns ></returns> } Range.prototype.delete = function(shift) { /// <summary> /// Deletes the cells associated with the range. /// </summary> /// <param name="shift" type="String">Specifies which way to shift the cells. See Excel.DeleteShiftDirection for details.</param> /// <returns ></returns> } Range.prototype.getBoundingRect = function(anotherRange) { /// <summary> /// Gets the smallest range object that encompasses the given ranges. For example, the GetBoundingRect of &quot;B2:C5&quot; and &quot;D10:E15&quot; is &quot;B2:E16&quot;. /// </summary> /// <param name="anotherRange" >The range object or address or range name.</param> /// <returns type="Excel.Range"></returns> } Range.prototype.getCell = function(row, column) { /// <summary> /// Gets the range object containing the single cell based on row and column numbers. The cell can be outside the bounds of its parent range, so long as it&apos;s stays within the worksheet grid. The returned cell is located relative to the top left cell of the range. /// </summary> /// <param name="row" type="Number">Row number of the cell to be retrieved. Zero-indexed.</param> /// <param name="column" type="Number">Column number of the cell to be retrieved. Zero-indexed.</param> /// <returns type="Excel.Range"></returns> } Range.prototype.getColumn = function(column) { /// <summary> /// Gets a column contained in the range. /// </summary> /// <param name="column" type="Number">Column number of the range to be retrieved. Zero-indexed.</param> /// <returns type="Excel.Range"></returns> } Range.prototype.getEntireColumn = function() { /// <summary> /// Gets an object that represents the entire column of the range. /// </summary> /// <returns type="Excel.Range"></returns> } Range.prototype.getEntireRow = function() { /// <summary> /// Gets an object that represents the entire row of the range. /// </summary> /// <returns type="Excel.Range"></returns> } Range.prototype.getIntersection = function(anotherRange) { /// <summary> /// Gets the range object that represents the rectangular intersection of the given ranges. /// </summary> /// <param name="anotherRange" >The range object or range address that will be used to determine the intersection of ranges.</param> /// <returns type="Excel.Range"></returns> } Range.prototype.getLastCell = function() { /// <summary> /// Gets the last cell within the range. For example, the last cell of &quot;B2:D5&quot; is &quot;D5&quot;. /// </summary> /// <returns type="Excel.Range"></returns> } Range.prototype.getLastColumn = function() { /// <summary> /// Gets the last column within the range. For example, the last column of &quot;B2:D5&quot; is &quot;D2:D5&quot;. /// </summary> /// <returns type="Excel.Range"></returns> } Range.prototype.getLastRow = function() { /// <summary> /// Gets the last row within the range. For example, the last row of &quot;B2:D5&quot; is &quot;B5:D5&quot;. /// </summary> /// <returns type="Excel.Range"></returns> } Range.prototype.getOffsetRange = function(rowOffset, columnOffset) { /// <summary> /// Gets an object which represents a range that&apos;s offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an exception will be thrown. /// </summary> /// <param name="rowOffset" type="Number">The number of rows (positive, negative, or 0) by which the range is to be offset. Positive values are offset downward, and negative values are offset upward.</param> /// <param name="columnOffset" type="Number">The number of columns (positive, negative, or 0) by which the range is to be offset. Positive values are offset to the right, and negative values are offset to the left.</param> /// <returns type="Excel.Range"></returns> } Range.prototype.getRow = function(row) { /// <summary> /// Gets a row contained in the range. /// </summary> /// <param name="row" type="Number">Row number of the range to be retrieved. Zero-indexed.</param> /// <returns type="Excel.Range"></returns> } Range.prototype.getUsedRange = function() { /// <summary> /// Returns the used range of the given range object. /// </summary> /// <returns type="Excel.Range"></returns> } Range.prototype.insert = function(shift) { /// <summary> /// Inserts a cell or a range of cells into the worksheet in place of this range, and shifts the other cells to make space. Returns a new Range object at the now blank space. /// </summary> /// <param name="shift" type="String">Specifies which way to shift the cells. See Excel.InsertShiftDirection for details.</param> /// <returns type="Excel.Range"></returns> } Range.prototype.select = function() { /// <summary> /// Selects the specified range in the Excel UI. /// </summary> /// <returns ></returns> } return Range; })(OfficeExtension.ClientObject); Excel.Range = Range; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RangeBorder = (function(_super) { __extends(RangeBorder, _super); function RangeBorder() { /// <summary> Represents the border of an object. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="color" type="String">HTML color code representing the color of the border line, of the form #RRGGBB (e.g. &quot;FFA500&quot;) or as a named HTML color (e.g. &quot;orange&quot;).</field> /// <field name="sideIndex" type="String">Constant value that indicates the specific side of the border. See Excel.BorderIndex for details. Read-only.</field> /// <field name="style" type="String">One of the constants of line style specifying the line style for the border. See Excel.BorderLineStyle for details.</field> /// <field name="weight" type="String">Specifies the weight of the border around a range. See Excel.BorderWeight for details.</field> } RangeBorder.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.RangeBorder"/> } return RangeBorder; })(OfficeExtension.ClientObject); Excel.RangeBorder = RangeBorder; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RangeBorderCollection = (function(_super) { __extends(RangeBorderCollection, _super); function RangeBorderCollection() { /// <summary> Represents the border objects that make up range border. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Number of border objects in the collection. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.RangeBorder">Gets the loaded child items in this collection.</field> } RangeBorderCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.RangeBorderCollection"/> } RangeBorderCollection.prototype.getItem = function(index) { /// <summary> /// Gets a border object using its name /// </summary> /// <param name="index" type="String">Index value of the border object to be retrieved. See Excel.BorderIndex for details.</param> /// <returns type="Excel.RangeBorder"></returns> } RangeBorderCollection.prototype.getItemAt = function(index) { /// <summary> /// Gets a border object using its index /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.RangeBorder"></returns> } return RangeBorderCollection; })(OfficeExtension.ClientObject); Excel.RangeBorderCollection = RangeBorderCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RangeFill = (function(_super) { __extends(RangeFill, _super); function RangeFill() { /// <summary> Represents the background of a range object. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="color" type="String">HTML color code representing the color of the border line, of the form #RRGGBB (e.g. &quot;FFA500&quot;) or as a named HTML color (e.g. &quot;orange&quot;)</field> } RangeFill.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.RangeFill"/> } RangeFill.prototype.clear = function() { /// <summary> /// Resets the range background. /// </summary> /// <returns ></returns> } return RangeFill; })(OfficeExtension.ClientObject); Excel.RangeFill = RangeFill; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RangeFont = (function(_super) { __extends(RangeFont, _super); function RangeFont() { /// <summary> This object represents the font attributes (font name, font size, color, etc.) for an object. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="bold" type="Boolean">Represents the bold status of font.</field> /// <field name="color" type="String">HTML color code representation of the text color. E.g. #FF0000 represents Red.</field> /// <field name="italic" type="Boolean">Represents the italic status of the font.</field> /// <field name="name" type="String">Font name (e.g. &quot;Calibri&quot;)</field> /// <field name="size" type="Number">Font size.</field> /// <field name="underline" type="String">Type of underline applied to the font. See Excel.RangeUnderlineStyle for details.</field> } RangeFont.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.RangeFont"/> } return RangeFont; })(OfficeExtension.ClientObject); Excel.RangeFont = RangeFont; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RangeFormat = (function(_super) { __extends(RangeFormat, _super); function RangeFormat() { /// <summary> A format object encapsulating the range&apos;s font, fill, borders, alignment, and other properties. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="borders" type="Excel.RangeBorderCollection">Collection of border objects that apply to the overall range selected Read-only.</field> /// <field name="fill" type="Excel.RangeFill">Returns the fill object defined on the overall range. Read-only.</field> /// <field name="font" type="Excel.RangeFont">Returns the font object defined on the overall range selected Read-only.</field> /// <field name="horizontalAlignment" type="String">Represents the horizontal alignment for the specified object. See Excel.HorizontalAlignment for details.</field> /// <field name="verticalAlignment" type="String">Represents the vertical alignment for the specified object. See Excel.VerticalAlignment for details.</field> /// <field name="wrapText" type="Boolean">Indicates if Excel wraps the text in the object. A null value indicates that the entire range doesn&apos;t have uniform wrap setting</field> } RangeFormat.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.RangeFormat"/> } return RangeFormat; })(OfficeExtension.ClientObject); Excel.RangeFormat = RangeFormat; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RangeUnderlineStyle = { __proto__: null, "none": "none", "single": "single", "double": "double", "singleAccountant": "singleAccountant", "doubleAccountant": "doubleAccountant", } Excel.RangeUnderlineStyle = RangeUnderlineStyle; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RangeValueType = { __proto__: null, "unknown": "unknown", "empty": "empty", "string": "string", "integer": "integer", "double": "double", "boolean": "boolean", "error": "error", } Excel.RangeValueType = RangeValueType; })(Excel || (Excel = {})); var Excel; (function (Excel) { var SheetVisibility = { __proto__: null, "visible": "visible", "hidden": "hidden", "veryHidden": "veryHidden", } Excel.SheetVisibility = SheetVisibility; })(Excel || (Excel = {})); var Excel; (function (Excel) { var Table = (function(_super) { __extends(Table, _super); function Table() { /// <summary> Represents an Excel table. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="columns" type="Excel.TableColumnCollection">Represents a collection of all the columns in the table. Read-only.</field> /// <field name="id" type="Number">Returns a value that uniquely identifies the table in a given workbook. The value of the identifier remains the same even when the table is renamed. Read-only.</field> /// <field name="name" type="String">Name of the table.</field> /// <field name="rows" type="Excel.TableRowCollection">Represents a collection of all the rows in the table. Read-only.</field> /// <field name="showHeaders" type="Boolean">Indicates whether the header row is visible or not. This value can be set to show or remove the header row.</field> /// <field name="showTotals" type="Boolean">Indicates whether the total row is visible or not. This value can be set to show or remove the total row.</field> /// <field name="style" type="String">Constant value that represents the Table style. Possible values are: TableStyleLight1 thru TableStyleLight21, TableStyleMedium1 thru TableStyleMedium28, TableStyleStyleDark1 thru TableStyleStyleDark11. A custom user-defined style present in the workbook can also be specified.</field> } Table.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.Table"/> } Table.prototype.delete = function() { /// <summary> /// Deletes the table. /// </summary> /// <returns ></returns> } Table.prototype.getDataBodyRange = function() { /// <summary> /// Gets the range object associated with the data body of the table. /// </summary> /// <returns type="Excel.Range"></returns> } Table.prototype.getHeaderRowRange = function() { /// <summary> /// Gets the range object associated with header row of the table. /// </summary> /// <returns type="Excel.Range"></returns> } Table.prototype.getRange = function() { /// <summary> /// Gets the range object associated with the entire table. /// </summary> /// <returns type="Excel.Range"></returns> } Table.prototype.getTotalRowRange = function() { /// <summary> /// Gets the range object associated with totals row of the table. /// </summary> /// <returns type="Excel.Range"></returns> } return Table; })(OfficeExtension.ClientObject); Excel.Table = Table; })(Excel || (Excel = {})); var Excel; (function (Excel) { var TableCollection = (function(_super) { __extends(TableCollection, _super); function TableCollection() { /// <summary> Represents a collection of all the tables that are part of the workbook. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Returns the number of tables in the workbook. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.Table">Gets the loaded child items in this collection.</field> } TableCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.TableCollection"/> } TableCollection.prototype.add = function(address, hasHeaders) { /// <summary> /// Create a new table. The range source address determines the worksheet under which the table will be added. If the table cannot be added (e.g., because the address is invalid, or the table would overlap with another table), an error will be thrown. /// </summary> /// <param name="address" type="String">Address or name of the range object representing the data source. If the address does not contain a sheet name, the currently-active sheet is used.</param> /// <param name="hasHeaders" type="Boolean">Boolean value that indicates whether the data being imported has column labels. If the source does not contain headers (i.e,. when this property set to false), Excel will automatically generate header shifting the data down by one row.</param> /// <returns type="Excel.Table"></returns> } TableCollection.prototype.getItem = function(key) { /// <summary> /// Gets a table by Name or ID. /// </summary> /// <param name="key" >Name or ID of the table to be retrieved.</param> /// <returns type="Excel.Table"></returns> } TableCollection.prototype.getItemAt = function(index) { /// <summary> /// Gets a table based on its position in the collection. /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.Table"></returns> } return TableCollection; })(OfficeExtension.ClientObject); Excel.TableCollection = TableCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var TableColumn = (function(_super) { __extends(TableColumn, _super); function TableColumn() { /// <summary> Represents a column in a table. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="id" type="Number">Returns a unique key that identifies the column within the table. Read-only.</field> /// <field name="index" type="Number">Returns the index number of the column within the columns collection of the table. Zero-indexed. Read-only.</field> /// <field name="name" type="String">Returns the name of the table column. Read-only.</field> /// <field name="values" type="Array" elementType="Array">Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.</field> } TableColumn.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.TableColumn"/> } TableColumn.prototype.delete = function() { /// <summary> /// Deletes the column from the table. /// </summary> /// <returns ></returns> } TableColumn.prototype.getDataBodyRange = function() { /// <summary> /// Gets the range object associated with the data body of the column. /// </summary> /// <returns type="Excel.Range"></returns> } TableColumn.prototype.getHeaderRowRange = function() { /// <summary> /// Gets the range object associated with the header row of the column. /// </summary> /// <returns type="Excel.Range"></returns> } TableColumn.prototype.getRange = function() { /// <summary> /// Gets the range object associated with the entire column. /// </summary> /// <returns type="Excel.Range"></returns> } TableColumn.prototype.getTotalRowRange = function() { /// <summary> /// Gets the range object associated with the totals row of the column. /// </summary> /// <returns type="Excel.Range"></returns> } return TableColumn; })(OfficeExtension.ClientObject); Excel.TableColumn = TableColumn; })(Excel || (Excel = {})); var Excel; (function (Excel) { var TableColumnCollection = (function(_super) { __extends(TableColumnCollection, _super); function TableColumnCollection() { /// <summary> Represents a collection of all the columns that are part of the table. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Returns the number of columns in the table. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.TableColumn">Gets the loaded child items in this collection.</field> } TableColumnCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.TableColumnCollection"/> } TableColumnCollection.prototype.add = function(index, values) { /// <summary> /// Adds a new column to the table. /// </summary> /// <param name="index" type="Number">Specifies the relative position of the new column. The previous column at this position is shifted to the right. The index value should be equal to or less than the last column&apos;s index value, so it cannot be used to append a column at the end of the table. Zero-indexed.</param> /// <param name="values" optional="true">A 2-dimensional array of unformatted values of the table column.</param> /// <returns type="Excel.TableColumn"></returns> } TableColumnCollection.prototype.getItem = function(key) { /// <summary> /// Gets a column object by Name or ID. /// </summary> /// <param name="key" >Column Name or ID.</param> /// <returns type="Excel.TableColumn"></returns> } TableColumnCollection.prototype.getItemAt = function(index) { /// <summary> /// Gets a column based on its position in the collection. /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.TableColumn"></returns> } return TableColumnCollection; })(OfficeExtension.ClientObject); Excel.TableColumnCollection = TableColumnCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var TableRow = (function(_super) { __extends(TableRow, _super); function TableRow() { /// <summary> Represents a row in a table. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="index" type="Number">Returns the index number of the row within the rows collection of the table. Zero-indexed. Read-only.</field> /// <field name="values" type="Array" elementType="Array">Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.</field> } TableRow.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.TableRow"/> } TableRow.prototype.delete = function() { /// <summary> /// Deletes the row from the table. /// </summary> /// <returns ></returns> } TableRow.prototype.getRange = function() { /// <summary> /// Returns the range object associated with the entire row. /// </summary> /// <returns type="Excel.Range"></returns> } return TableRow; })(OfficeExtension.ClientObject); Excel.TableRow = TableRow; })(Excel || (Excel = {})); var Excel; (function (Excel) { var TableRowCollection = (function(_super) { __extends(TableRowCollection, _super); function TableRowCollection() { /// <summary> Represents a collection of all the rows that are part of the table. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="count" type="Number">Returns the number of rows in the table. Read-only.</field> /// <field name="items" type="Array" elementType="Excel.TableRow">Gets the loaded child items in this collection.</field> } TableRowCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.TableRowCollection"/> } TableRowCollection.prototype.add = function(index, values) { /// <summary> /// Adds a new row to the table. /// </summary> /// <param name="index" type="Number" optional="true">Specifies the relative position of the new row. If null, the addition happens at the end. Any rows below the inserted row are shifted downwards. Zero-indexed.</param> /// <param name="values" optional="true">A 2-dimensional array of unformatted values of the table row.</param> /// <returns type="Excel.TableRow"></returns> } TableRowCollection.prototype.getItemAt = function(index) { /// <summary> /// Gets a row based on its position in the collection. /// </summary> /// <param name="index" type="Number">Index value of the object to be retrieved. Zero-indexed.</param> /// <returns type="Excel.TableRow"></returns> } return TableRowCollection; })(OfficeExtension.ClientObject); Excel.TableRowCollection = TableRowCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var VerticalAlignment = { __proto__: null, "top": "top", "center": "center", "bottom": "bottom", "justify": "justify", "distributed": "distributed", } Excel.VerticalAlignment = VerticalAlignment; })(Excel || (Excel = {})); var Excel; (function (Excel) { var Workbook = (function(_super) { __extends(Workbook, _super); function Workbook() { /// <summary> Workbook is the top level object which contains related workbook objects such as worksheets, tables, ranges, etc. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="application" type="Excel.Application">Represents Excel application instance that contains this workbook. Read-only.</field> /// <field name="bindings" type="Excel.BindingCollection">Represents a collection of bindings that are part of the workbook. Read-only.</field> /// <field name="names" type="Excel.NamedItemCollection">Represents a collection of workbook scoped named items (named ranges and constants). Read-only.</field> /// <field name="tables" type="Excel.TableCollection">Represents a collection of tables associated with the workbook. Read-only.</field> /// <field name="worksheets" type="Excel.WorksheetCollection">Represents a collection of worksheets associated with the workbook. Read-only.</field> } Workbook.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.Workbook"/> } Workbook.prototype.getSelectedRange = function() { /// <summary> /// Gets the currently selected range from the workbook. /// </summary> /// <returns type="Excel.Range"></returns> } return Workbook; })(OfficeExtension.ClientObject); Excel.Workbook = Workbook; })(Excel || (Excel = {})); var Excel; (function (Excel) { var Worksheet = (function(_super) { __extends(Worksheet, _super); function Worksheet() { /// <summary> An Excel worksheet is a grid of cells. It can contain data, tables, charts, etc. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="charts" type="Excel.ChartCollection">Returns collection of charts that are part of the worksheet. Read-only.</field> /// <field name="id" type="String">Returns a value that uniquely identifies the worksheet in a given workbook. The value of the identifier remains the same even when the worksheet is renamed or moved. Read-only.</field> /// <field name="name" type="String">The display name of the worksheet.</field> /// <field name="position" type="Number">The zero-based position of the worksheet within the workbook.</field> /// <field name="tables" type="Excel.TableCollection">Collection of tables that are part of the worksheet. Read-only.</field> /// <field name="visibility" type="String">The Visibility of the worksheet, Read-only.</field> } Worksheet.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.Worksheet"/> } Worksheet.prototype.activate = function() { /// <summary> /// Activate the worksheet in the Excel UI. /// </summary> /// <returns ></returns> } Worksheet.prototype.delete = function() { /// <summary> /// Deletes the worksheet from the workbook. /// </summary> /// <returns ></returns> } Worksheet.prototype.getCell = function(row, column) { /// <summary> /// Gets the range object containing the single cell based on row and column numbers. The cell can be outside the bounds of its parent range, so long as it&apos;s stays within the worksheet grid. /// </summary> /// <param name="row" type="Number">The row number of the cell to be retrieved. Zero-indexed.</param> /// <param name="column" type="Number">the column number of the cell to be retrieved. Zero-indexed.</param> /// <returns type="Excel.Range"></returns> } Worksheet.prototype.getRange = function(address) { /// <summary> /// Gets the range object specified by the address or name. /// </summary> /// <param name="address" type="String" optional="true">The address or the name of the range. If not specified, the entire worksheet range is returned.</param> /// <returns type="Excel.Range"></returns> } Worksheet.prototype.getUsedRange = function() { /// <summary> /// The used range is the smallest range than encompasses any cells that have a value or formatting assigned to them. If the worksheet is blank, this function will return the top left cell. /// </summary> /// <returns type="Excel.Range"></returns> } return Worksheet; })(OfficeExtension.ClientObject); Excel.Worksheet = Worksheet; })(Excel || (Excel = {})); var Excel; (function (Excel) { var WorksheetCollection = (function(_super) { __extends(WorksheetCollection, _super); function WorksheetCollection() { /// <summary> Represents a collection of worksheet objects that are part of the workbook. </summary> /// <field name="context" type="Excel.RequestContext">The request context associated with this object</field> /// <field name="items" type="Array" elementType="Excel.Worksheet">Gets the loaded child items in this collection.</field> } WorksheetCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Excel.WorksheetCollection"/> } WorksheetCollection.prototype.add = function(name) { /// <summary> /// Adds a new worksheet to the workbook. The worksheet will be added at the end of existing worksheets. If you wish to activate the newly added worksheet, call &quot;.activate() on it. /// </summary> /// <param name="name" type="String" optional="true">The name of the worksheet to be added. If specified, name should be unqiue. If not specified, Excel determines the name of the new worksheet.</param> /// <returns type="Excel.Worksheet"></returns> } WorksheetCollection.prototype.getActiveWorksheet = function() { /// <summary> /// Gets the currently active worksheet in the workbook. /// </summary> /// <returns type="Excel.Worksheet"></returns> } WorksheetCollection.prototype.getItem = function(key) { /// <summary> /// Gets a worksheet object using its Name or ID. /// </summary> /// <param name="key" type="String">The Name or ID of the worksheet.</param> /// <returns type="Excel.Worksheet"></returns> } return WorksheetCollection; })(OfficeExtension.ClientObject); Excel.WorksheetCollection = WorksheetCollection; })(Excel || (Excel = {})); var Excel; (function (Excel) { var RequestContext = (function (_super) { __extends(RequestContext, _super); function RequestContext() { /// <summary> /// The RequestContext object facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. /// </summary> /// <field name="workbook" type="Excel.Workbook">Root object for interacting with the document</field> _super.call(this, null); } return RequestContext; })(OfficeExtension.ClientRequestContext); Excel.RequestContext = RequestContext; Excel.run = function (batch) { /// <summary> /// Executes a batch script that performs actions on the Excel object model. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. /// </summary> /// <param name="batch" type="function(context) { ... }"> /// A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). /// <br /> /// The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. /// </param> batch(new Excel.RequestContext()); return new OfficeExtension.IPromise(); } })(Excel || (Excel = {})); Excel.__proto__ = null; var Word; (function (Word) { var Alignment = { __proto__: null, "unknown": "unknown", "left": "left", "centered": "centered", "right": "right", "justified": "justified", } Word.Alignment = Alignment; })(Word || (Word = {})); var Word; (function (Word) { var Body = (function(_super) { __extends(Body, _super); function Body() { /// <summary> Represents the body of a document or a section. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="contentControls" type="Word.ContentControlCollection">Gets the collection of rich text content control objects that are in the body. Read-only.</field> /// <field name="font" type="Word.Font">Gets the text format of the body. Use this to get and set font name, size, color, and other properties. Read-only.</field> /// <field name="inlinePictures" type="Word.InlinePictureCollection">Gets the collection of inlinePicture objects that are in the body. The collection does not include floating images. Read-only.</field> /// <field name="paragraphs" type="Word.ParagraphCollection">Gets the collection of paragraph objects that are in the body. Read-only.</field> /// <field name="parentContentControl" type="Word.ContentControl">Gets the content control that contains the body. Returns null if there isn&apos;t a parent content control. Read-only.</field> /// <field name="style" type="String">Gets or sets the style used for the body. This is the name of the pre-installed or custom style.</field> /// <field name="text" type="String">Gets the text of the body. Use the insertText method to insert text. Read-only.</field> } Body.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.Body"/> } Body.prototype.clear = function() { /// <summary> /// Clears the contents of the body object. The user can perform the undo operation on the cleared content. /// </summary> /// <returns ></returns> } Body.prototype.getHtml = function() { /// <summary> /// Gets the HTML representation of the body object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } Body.prototype.getOoxml = function() { /// <summary> /// Gets the OOXML (Office Open XML) representation of the body object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } Body.prototype.insertBreak = function(breakType, insertLocation) { /// <summary> /// Inserts a break at the specified location. The insertLocation value can be &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="breakType" type="String">Required. The break type to add to the body.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Start&apos; or &apos;End&apos;.</param> /// <returns ></returns> } Body.prototype.insertContentControl = function() { /// <summary> /// Wraps the body object with a Rich Text content control. /// </summary> /// <returns type="Word.ContentControl"></returns> } Body.prototype.insertFileFromBase64 = function(base64File, insertLocation) { /// <summary> /// Inserts a document into the body at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="base64File" type="String">Required. The base64 encoded file contents to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Body.prototype.insertHtml = function(html, insertLocation) { /// <summary> /// Inserts HTML at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="html" type="String">Required. The HTML to be inserted in the document.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Body.prototype.insertOoxml = function(ooxml, insertLocation) { /// <summary> /// Inserts OOXML at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="ooxml" type="String">Required. The OOXML to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Body.prototype.insertParagraph = function(paragraphText, insertLocation) { /// <summary> /// Inserts a paragraph at the specified location. The insertLocation value can be &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="paragraphText" type="String">Required. The paragraph text to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Paragraph"></returns> } Body.prototype.insertText = function(text, insertLocation) { /// <summary> /// Inserts text into the body at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="text" type="String">Required. Text to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Body.prototype.search = function(searchText, searchOptions) { /// <summary> /// Performs a search with the specified searchOptions on the scope of the body object. The search results are a collection of range objects. /// </summary> /// <param name="searchText" type="String">Required. The search text.</param> /// <param name="searchOptions" type="Word.SearchOptions" optional="true">Optional. Options for the search.</param> /// <returns type="Word.SearchResultCollection"></returns> } Body.prototype.select = function() { /// <summary> /// Selects the body and navigates the Word UI to it. /// </summary> /// <returns ></returns> } return Body; })(OfficeExtension.ClientObject); Word.Body = Body; })(Word || (Word = {})); var Word; (function (Word) { var BreakType = { __proto__: null, "page": "page", "column": "column", "next": "next", "sectionContinuous": "sectionContinuous", "sectionEven": "sectionEven", "sectionOdd": "sectionOdd", "line": "line", "lineClearLeft": "lineClearLeft", "lineClearRight": "lineClearRight", "textWrapping": "textWrapping", } Word.BreakType = BreakType; })(Word || (Word = {})); var Word; (function (Word) { var ContentControl = (function(_super) { __extends(ContentControl, _super); function ContentControl() { /// <summary> Represents a content control. Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls may contain contents such as images, tables, or paragraphs of formatted text. Currently, only rich text content controls are supported. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="appearance" type="String">Gets or sets the appearance of the content control. The value can be &apos;boundingBox&apos;, &apos;tags&apos; or &apos;hidden&apos;.</field> /// <field name="cannotDelete" type="Boolean">Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited.</field> /// <field name="cannotEdit" type="Boolean">Gets or sets a value that indicates whether the user can edit the contents of the content control.</field> /// <field name="color" type="String">Gets or sets the color of the content control. Color is set in &quot;#RRGGBB&quot; format or by using the color name.</field> /// <field name="contentControls" type="Word.ContentControlCollection">Gets the collection of content control objects in the content control. Read-only.</field> /// <field name="font" type="Word.Font">Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. Read-only.</field> /// <field name="id" type="Number">Gets an integer that represents the content control identifier. Read-only.</field> /// <field name="inlinePictures" type="Word.InlinePictureCollection">Gets the collection of inlinePicture objects in the content control. The collection does not include floating images. Read-only.</field> /// <field name="paragraphs" type="Word.ParagraphCollection">Get the collection of paragraph objects in the content control. Read-only.</field> /// <field name="parentContentControl" type="Word.ContentControl">Gets the content control that contains the content control. Returns null if there isn&apos;t a parent content control. Read-only.</field> /// <field name="placeholderText" type="String">Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty.</field> /// <field name="removeWhenEdited" type="Boolean">Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete.</field> /// <field name="style" type="String">Gets or sets the style used for the content control. This is the name of the pre-installed or custom style.</field> /// <field name="tag" type="String">Gets or sets a tag to identify a content control.</field> /// <field name="text" type="String">Gets the text of the content control. Read-only.</field> /// <field name="title" type="String">Gets or sets the title for a content control.</field> /// <field name="type" type="String">Gets the content control type. Only rich text content controls are supported currently. Read-only.</field> } ContentControl.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.ContentControl"/> } ContentControl.prototype.clear = function() { /// <summary> /// Clears the contents of the content control. The user can perform the undo operation on the cleared content. /// </summary> /// <returns ></returns> } ContentControl.prototype.delete = function(keepContent) { /// <summary> /// Deletes the content control and its content. If keepContent is set to true, the content is not deleted. /// </summary> /// <param name="keepContent" type="Boolean">Required. Indicates whether the content should be deleted with the content control. If keepContent is set to true, the content is not deleted.</param> /// <returns ></returns> } ContentControl.prototype.getHtml = function() { /// <summary> /// Gets the HTML representation of the content control object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } ContentControl.prototype.getOoxml = function() { /// <summary> /// Gets the Office Open XML (OOXML) representation of the content control object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } ContentControl.prototype.insertBreak = function(breakType, insertLocation) { /// <summary> /// Inserts a break at the specified location. The insertLocation value can be &apos;Before&apos;, &apos;After&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="breakType" type="String">Required. Type of break (breakType.md)</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Before&apos;, &apos;After&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns ></returns> } ContentControl.prototype.insertFileFromBase64 = function(base64File, insertLocation) { /// <summary> /// Inserts a document into the current content control at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="base64File" type="String">Required. Base64 encoded contents of the file to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } ContentControl.prototype.insertHtml = function(html, insertLocation) { /// <summary> /// Inserts HTML into the content control at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="html" type="String">Required. The HTML to be inserted in to the content control.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } ContentControl.prototype.insertOoxml = function(ooxml, insertLocation) { /// <summary> /// Inserts OOXML into the content control at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="ooxml" type="String">Required. The OOXML to be inserted in to the content control.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } ContentControl.prototype.insertParagraph = function(paragraphText, insertLocation) { /// <summary> /// Inserts a paragraph at the specified location. The insertLocation value can be &apos;Before&apos;, &apos;After&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="paragraphText" type="String">Required. The paragrph text to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Before&apos;, &apos;After&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Paragraph"></returns> } ContentControl.prototype.insertText = function(text, insertLocation) { /// <summary> /// Inserts text into the content control at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="text" type="String">Required. The text to be inserted in to the content control.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } ContentControl.prototype.search = function(searchText, searchOptions) { /// <summary> /// Performs a search with the specified searchOptions on the scope of the content control object. The search results are a collection of range objects. /// </summary> /// <param name="searchText" type="String">Required. The search text.</param> /// <param name="searchOptions" type="Word.SearchOptions" optional="true">Optional. Options for the search.</param> /// <returns type="Word.SearchResultCollection"></returns> } ContentControl.prototype.select = function() { /// <summary> /// Selects the content control. This causes Word to scroll to the selection. /// </summary> /// <returns ></returns> } return ContentControl; })(OfficeExtension.ClientObject); Word.ContentControl = ContentControl; })(Word || (Word = {})); var Word; (function (Word) { var ContentControlAppearance = { __proto__: null, "boundingBox": "boundingBox", "tags": "tags", "hidden": "hidden", } Word.ContentControlAppearance = ContentControlAppearance; })(Word || (Word = {})); var Word; (function (Word) { var ContentControlCollection = (function(_super) { __extends(ContentControlCollection, _super); function ContentControlCollection() { /// <summary> Contains a collection of ContentControl objects. Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls may contain contents such as images, tables, or paragraphs of formatted text. Currently, only rich text content controls are supported. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="items" type="Array" elementType="Word.ContentControl">Gets the loaded child items in this collection.</field> } ContentControlCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.ContentControlCollection"/> } ContentControlCollection.prototype.getById = function(id) { /// <summary> /// Gets a content control by its identifier. /// </summary> /// <param name="id" type="Number">Required. A content control identifier.</param> /// <returns type="Word.ContentControl"></returns> } ContentControlCollection.prototype.getByTag = function(tag) { /// <summary> /// Gets the content controls that have the specified tag. /// </summary> /// <param name="tag" type="String">Required. A tag set on a content control.</param> /// <returns type="Word.ContentControlCollection"></returns> } ContentControlCollection.prototype.getByTitle = function(title) { /// <summary> /// Gets the content controls that have the specified title. /// </summary> /// <param name="title" type="String">Required. The title of a content control.</param> /// <returns type="Word.ContentControlCollection"></returns> } ContentControlCollection.prototype.getItem = function(index) { /// <summary> /// Gets a content control by its index in the collection. /// </summary> /// <param name="index" >The index</param> /// <returns type="Word.ContentControl"></returns> } return ContentControlCollection; })(OfficeExtension.ClientObject); Word.ContentControlCollection = ContentControlCollection; })(Word || (Word = {})); var Word; (function (Word) { var ContentControlType = { __proto__: null, "richText": "richText", } Word.ContentControlType = ContentControlType; })(Word || (Word = {})); var Word; (function (Word) { var Document = (function(_super) { __extends(Document, _super); function Document() { /// <summary> The Document object is the top level object. A Document object contains one or more sections, content controls, and the body that contains the contents of the document. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="body" type="Word.Body">Gets the body of the document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. Read-only.</field> /// <field name="contentControls" type="Word.ContentControlCollection">Gets the collection of content control objects that are in the current document. This includes content controls in the body of the document, headers, footers, textboxes, etc.. Read-only.</field> /// <field name="saved" type="Boolean">Indicates whether the changes in the document have been saved. A value of true indicates that the document hasn&apos;t changed since it was saved. Read-only.</field> /// <field name="sections" type="Word.SectionCollection">Gets the collection of section objects that are in the document. Read-only.</field> } Document.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.Document"/> } Document.prototype.getSelection = function() { /// <summary> /// Gets the current selection of the document. Multiple selections are not supported. /// </summary> /// <returns type="Word.Range"></returns> } Document.prototype.save = function() { /// <summary> /// Saves the document. This will use the Word default file naming convention if the document has not been saved before. /// </summary> /// <returns ></returns> } return Document; })(OfficeExtension.ClientObject); Word.Document = Document; })(Word || (Word = {})); var Word; (function (Word) { var Font = (function(_super) { __extends(Font, _super); function Font() { /// <summary> Represents a font. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="bold" type="Boolean">Gets or sets a value that indicates whether the font is bold. True if the font is formatted as bold, otherwise, false.</field> /// <field name="color" type="String">Gets or sets the color for the specified font. You can provide the value in the &quot;#RRGGBB&quot; format or the color name.</field> /// <field name="doubleStrikeThrough" type="Boolean">Gets or sets a value that indicates whether the font has a double strike through. True if the font is formatted as double strikethrough text, otherwise, false.</field> /// <field name="highlightColor" type="String">Gets or sets the highlight color for the specified font. You can provide the value as either in the &quot;#RRGGBB&quot; format or the color name.</field> /// <field name="italic" type="Boolean">Gets or sets a value that indicates whether the font is italicized. True if the font is italicized, otherwise, false.</field> /// <field name="name" type="String">Gets or sets a value that represents the name of the font.</field> /// <field name="size" type="Number">Gets or sets a value that represents the font size in points.</field> /// <field name="strikeThrough" type="Boolean">Gets or sets a value that indicates whether the font has a strike through. True if the font is formatted as strikethrough text, otherwise, false.</field> /// <field name="subscript" type="Boolean">Gets or sets a value that indicates whether the font is a subscript. True if the font is formatted as subscript, otherwise, false.</field> /// <field name="superscript" type="Boolean">Gets or sets a value that indicates whether the font is a superscript. True if the font is formatted as superscript, otherwise, false.</field> /// <field name="underline" type="String">Gets or sets a value that indicates the font&apos;s underline type. &apos;None&apos; if the font is not underlined.</field> } Font.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.Font"/> } return Font; })(OfficeExtension.ClientObject); Word.Font = Font; })(Word || (Word = {})); var Word; (function (Word) { var HeaderFooterType = { __proto__: null, "primary": "primary", "firstPage": "firstPage", "evenPages": "evenPages", } Word.HeaderFooterType = HeaderFooterType; })(Word || (Word = {})); var Word; (function (Word) { var InlinePicture = (function(_super) { __extends(InlinePicture, _super); function InlinePicture() { /// <summary> Represents an inline picture. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="altTextDescription" type="String">Gets or sets a string that represents the alternative text associated with the inline image</field> /// <field name="altTextTitle" type="String">Gets or sets a string that contains the title for the inline image.</field> /// <field name="height" type="Number">Gets or sets a number that describes the height of the inline image.</field> /// <field name="hyperlink" type="String">Gets or sets the hyperlink associated with the inline image.</field> /// <field name="lockAspectRatio" type="Boolean">Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it.</field> /// <field name="parentContentControl" type="Word.ContentControl">Gets the content control that contains the inline image. Returns null if there isn&apos;t a parent content control. Read-only.</field> /// <field name="width" type="Number">Gets or sets a number that describes the width of the inline image.</field> } InlinePicture.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.InlinePicture"/> } InlinePicture.prototype.getBase64ImageSrc = function() { /// <summary> /// Gets the base64 encoded string representation of the inline image. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } InlinePicture.prototype.insertContentControl = function() { /// <summary> /// Wraps the inline picture with a rich text content control. /// </summary> /// <returns type="Word.ContentControl"></returns> } return InlinePicture; })(OfficeExtension.ClientObject); Word.InlinePicture = InlinePicture; })(Word || (Word = {})); var Word; (function (Word) { var InlinePictureCollection = (function(_super) { __extends(InlinePictureCollection, _super); function InlinePictureCollection() { /// <summary> Contains a collection of [inlinePicture](inlinePicture.md) objects. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="items" type="Array" elementType="Word.InlinePicture">Gets the loaded child items in this collection.</field> } InlinePictureCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.InlinePictureCollection"/> } return InlinePictureCollection; })(OfficeExtension.ClientObject); Word.InlinePictureCollection = InlinePictureCollection; })(Word || (Word = {})); var Word; (function (Word) { var InsertLocation = { __proto__: null, "before": "before", "after": "after", "start": "start", "end": "end", "replace": "replace", } Word.InsertLocation = InsertLocation; })(Word || (Word = {})); var Word; (function (Word) { var Paragraph = (function(_super) { __extends(Paragraph, _super); function Paragraph() { /// <summary> Represents a single paragraph in a selection, range, content control, or document body. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="alignment" type="String">Gets or sets the alignment for a paragraph. The value can be &quot;left&quot;, &quot;centered&quot;, &quot;right&quot;, or &quot;justified&quot;.</field> /// <field name="contentControls" type="Word.ContentControlCollection">Gets the collection of content control objects that are in the paragraph. Read-only.</field> /// <field name="firstLineIndent" type="Number">Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent.</field> /// <field name="font" type="Word.Font">Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. Read-only.</field> /// <field name="inlinePictures" type="Word.InlinePictureCollection">Gets the collection of inlinePicture objects that are in the paragraph. The collection does not include floating images. Read-only.</field> /// <field name="leftIndent" type="Number">Gets or sets the left indent value, in points, for the paragraph.</field> /// <field name="lineSpacing" type="Number">Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12.</field> /// <field name="lineUnitAfter" type="Number">Gets or sets the amount of spacing, in grid lines. after the paragraph.</field> /// <field name="lineUnitBefore" type="Number">Gets or sets the amount of spacing, in grid lines, before the paragraph.</field> /// <field name="outlineLevel" type="Number">Gets or sets the outline level for the paragraph.</field> /// <field name="parentContentControl" type="Word.ContentControl">Gets the content control that contains the paragraph. Returns null if there isn&apos;t a parent content control. Read-only.</field> /// <field name="rightIndent" type="Number">Gets or sets the right indent value, in points, for the paragraph.</field> /// <field name="spaceAfter" type="Number">Gets or sets the spacing, in points, after the paragraph.</field> /// <field name="spaceBefore" type="Number">Gets or sets the spacing, in points, before the paragraph.</field> /// <field name="style" type="String">Gets or sets the style used for the paragraph. This is the name of the pre-installed or custom style.</field> /// <field name="text" type="String">Gets the text of the paragraph. Read-only.</field> } Paragraph.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.Paragraph"/> } Paragraph.prototype.clear = function() { /// <summary> /// Clears the contents of the paragraph object. The user can perform the undo operation on the cleared content. /// </summary> /// <returns ></returns> } Paragraph.prototype.delete = function() { /// <summary> /// Deletes the paragraph and its content from the document. /// </summary> /// <returns ></returns> } Paragraph.prototype.getHtml = function() { /// <summary> /// Gets the HTML representation of the paragraph object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } Paragraph.prototype.getOoxml = function() { /// <summary> /// Gets the Office Open XML (OOXML) representation of the paragraph object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } Paragraph.prototype.insertBreak = function(breakType, insertLocation) { /// <summary> /// Inserts a break at the specified location. The insertLocation value can be &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="breakType" type="String">Required. The break type to add to the document.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Before&apos; or &apos;After&apos;.</param> /// <returns ></returns> } Paragraph.prototype.insertContentControl = function() { /// <summary> /// Wraps the paragraph object with a rich text content control. /// </summary> /// <returns type="Word.ContentControl"></returns> } Paragraph.prototype.insertFileFromBase64 = function(base64File, insertLocation) { /// <summary> /// Inserts a document into the current paragraph at the specified location. The insertLocation value can be &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="base64File" type="String">Required. The file base64 encoded file contents to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Paragraph.prototype.insertHtml = function(html, insertLocation) { /// <summary> /// Inserts HTML into the paragraph at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="html" type="String">Required. The HTML to be inserted in the paragraph.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Paragraph.prototype.insertInlinePictureFromBase64 = function(base64EncodedImage, insertLocation) { /// <summary> /// Inserts a picture into the paragraph at the specified location. The insertLocation value can be &apos;Before&apos;, &apos;After&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="base64EncodedImage" type="String">Required. The HTML to be inserted in the paragraph.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Before&apos;, &apos;After&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.InlinePicture"></returns> } Paragraph.prototype.insertOoxml = function(ooxml, insertLocation) { /// <summary> /// Inserts OOXML into the paragraph at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="ooxml" type="String">Required. The OOXML to be inserted in the paragraph.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Paragraph.prototype.insertParagraph = function(paragraphText, insertLocation) { /// <summary> /// Inserts a paragraph at the specified location. The insertLocation value can be &apos;Before&apos; or &apos;After&apos;. /// </summary> /// <param name="paragraphText" type="String">Required. The paragraph text to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Before&apos; or &apos;After&apos;.</param> /// <returns type="Word.Paragraph"></returns> } Paragraph.prototype.insertText = function(text, insertLocation) { /// <summary> /// Inserts text into the paragraph at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="text" type="String">Required. Text to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Paragraph.prototype.search = function(searchText, searchOptions) { /// <summary> /// Performs a search with the specified searchOptions on the scope of the paragraph object. The search results are a collection of range objects. /// </summary> /// <param name="searchText" type="String">Required. The search text.</param> /// <param name="searchOptions" type="Word.SearchOptions" optional="true">Optional. Options for the search.</param> /// <returns type="Word.SearchResultCollection"></returns> } Paragraph.prototype.select = function() { /// <summary> /// Selects and navigates the Word UI to the paragraph. /// </summary> /// <returns ></returns> } return Paragraph; })(OfficeExtension.ClientObject); Word.Paragraph = Paragraph; })(Word || (Word = {})); var Word; (function (Word) { var ParagraphCollection = (function(_super) { __extends(ParagraphCollection, _super); function ParagraphCollection() { /// <summary> Contains a collection of [paragraph](paragraph.md) objects. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="items" type="Array" elementType="Word.Paragraph">Gets the loaded child items in this collection.</field> } ParagraphCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.ParagraphCollection"/> } return ParagraphCollection; })(OfficeExtension.ClientObject); Word.ParagraphCollection = ParagraphCollection; })(Word || (Word = {})); var Word; (function (Word) { var Range = (function(_super) { __extends(Range, _super); function Range() { /// <summary> Represents a contiguous area in a document. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="contentControls" type="Word.ContentControlCollection">Gets the collection of content control objects that are in the range. Read-only.</field> /// <field name="font" type="Word.Font">Gets the text format of the range. Use this to get and set font name, size, color, and other properties. Read-only.</field> /// <field name="paragraphs" type="Word.ParagraphCollection">Gets the collection of paragraph objects that are in the range. Read-only.</field> /// <field name="parentContentControl" type="Word.ContentControl">Gets the content control that contains the range. Returns null if there isn&apos;t a parent content control. Read-only.</field> /// <field name="style" type="String">Gets or sets the style used for the range. This is the name of the pre-installed or custom style.</field> /// <field name="text" type="String">Gets the text of the range. Read-only.</field> } Range.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.Range"/> } Range.prototype.clear = function() { /// <summary> /// Clears the contents of the range object. The user can perform the undo operation on the cleared content. /// </summary> /// <returns ></returns> } Range.prototype.delete = function() { /// <summary> /// Deletes the range and its content from the document. /// </summary> /// <returns ></returns> } Range.prototype.getHtml = function() { /// <summary> /// Gets the HTML representation of the range object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } Range.prototype.getOoxml = function() { /// <summary> /// Gets the OOXML representation of the range object. /// </summary> /// <returns type="OfficeExtension.ClientResult&lt;string&gt;"></returns> var result = new OfficeExtension.ClientResult(); result.__proto__ = null; result.value = ''; return result; } Range.prototype.insertBreak = function(breakType, insertLocation) { /// <summary> /// Inserts a break at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Before&apos; or &apos;After&apos;. /// </summary> /// <param name="breakType" type="String">Required. The break type to add to the range.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Before&apos; or &apos;After&apos;.</param> /// <returns ></returns> } Range.prototype.insertContentControl = function() { /// <summary> /// Wraps the range object with a rich text content control. /// </summary> /// <returns type="Word.ContentControl"></returns> } Range.prototype.insertFileFromBase64 = function(base64File, insertLocation) { /// <summary> /// Inserts a document into the range at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="base64File" type="String">Required. The file base64 encoded file contents to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Range.prototype.insertHtml = function(html, insertLocation) { /// <summary> /// Inserts HTML into the range at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="html" type="String">Required. The HTML to be inserted in the range.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Range.prototype.insertOoxml = function(ooxml, insertLocation) { /// <summary> /// Inserts OOXML into the range at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="ooxml" type="String">Required. The OOXML to be inserted in the range.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Range.prototype.insertParagraph = function(paragraphText, insertLocation) { /// <summary> /// Inserts a paragraph into the range at the specified location. The insertLocation value can be &apos;Before&apos; or &apos;After&apos;. /// </summary> /// <param name="paragraphText" type="String">Required. The paragraph text to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Before&apos; or &apos;After&apos;.</param> /// <returns type="Word.Paragraph"></returns> } Range.prototype.insertText = function(text, insertLocation) { /// <summary> /// Inserts text into the range at the specified location. The insertLocation value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;. /// </summary> /// <param name="text" type="String">Required. Text to be inserted.</param> /// <param name="insertLocation" type="String">Required. The value can be &apos;Replace&apos;, &apos;Start&apos; or &apos;End&apos;.</param> /// <returns type="Word.Range"></returns> } Range.prototype.search = function(searchText, searchOptions) { /// <summary> /// Performs a search with the specified searchOptions on the scope of the range object. The search results are a collection of range objects. /// </summary> /// <param name="searchText" type="String">Required. The search text.</param> /// <param name="searchOptions" type="Word.SearchOptions" optional="true">Optional. Options for the search.</param> /// <returns type="Word.SearchResultCollection"></returns> } Range.prototype.select = function() { /// <summary> /// Selects and navigates the Word UI to the range. /// </summary> /// <returns ></returns> } return Range; })(OfficeExtension.ClientObject); Word.Range = Range; })(Word || (Word = {})); var Word; (function (Word) { var SearchOptions = (function(_super) { __extends(SearchOptions, _super); function SearchOptions() { /// <summary> Specifies the options to be included in a search operation. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="ignorePunct" type="Boolean">Gets or sets a value that indicates whether to ignore all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box.</field> /// <field name="ignoreSpace" type="Boolean">Gets or sets a value that indicates whether to ignore all white space between words. Corresponds to the Ignore white-space characters check box in the Find and Replace dialog box.</field> /// <field name="matchCase" type="Boolean">Gets or sets a value that indicates whether to perform a case sensitive search. Corresponds to the Match case check box in the Find and Replace dialog box (Edit menu).</field> /// <field name="matchPrefix" type="Boolean">Gets or sets a value that indicates whether to match words that begin with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box.</field> /// <field name="matchSoundsLike" type="Boolean">Gets or sets a value that indicates whether to find words that sound similar to the search string. Corresponds to the Sounds like check box in the Find and Replace dialog box</field> /// <field name="matchSuffix" type="Boolean">Gets or sets a value that indicates whether to match words that end with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box.</field> /// <field name="matchWholeWord" type="Boolean">Gets or sets a value that indicates whether to find operation only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box.</field> /// <field name="matchWildCards" type="Boolean">Gets or sets a value that indicates whether the search will be performed using special search operators. Corresponds to the Use wildcards check box in the Find and Replace dialog box.</field> } SearchOptions.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.SearchOptions"/> } return SearchOptions; })(OfficeExtension.ClientObject); Word.SearchOptions = SearchOptions; })(Word || (Word = {})); var Word; (function (Word) { var SearchResultCollection = (function(_super) { __extends(SearchResultCollection, _super); function SearchResultCollection() { /// <summary> Contains a collection of [range](range.md) objects as a result of a search operation. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="items" type="Array" elementType="Word.Range">Gets the loaded child items in this collection.</field> } SearchResultCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.SearchResultCollection"/> } return SearchResultCollection; })(OfficeExtension.ClientObject); Word.SearchResultCollection = SearchResultCollection; })(Word || (Word = {})); var Word; (function (Word) { var Section = (function(_super) { __extends(Section, _super); function Section() { /// <summary> Represents a section in a Word document. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="body" type="Word.Body">Gets the body of the section. This does not include the header/footer and other section metadata. Read-only.</field> } Section.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.Section"/> } Section.prototype.getFooter = function(type) { /// <summary> /// Gets one of the section&apos;s footers. /// </summary> /// <param name="type" type="String">Required. The type of footer to return. This value can be: &apos;primary&apos;, &apos;firstPage&apos; or &apos;evenPages&apos;.</param> /// <returns type="Word.Body"></returns> } Section.prototype.getHeader = function(type) { /// <summary> /// Gets one of the section&apos;s headers. /// </summary> /// <param name="type" type="String">Required. The type of header to return. This value can be: &apos;primary&apos;, &apos;firstPage&apos; or &apos;evenPages&apos;.</param> /// <returns type="Word.Body"></returns> } return Section; })(OfficeExtension.ClientObject); Word.Section = Section; })(Word || (Word = {})); var Word; (function (Word) { var SectionCollection = (function(_super) { __extends(SectionCollection, _super); function SectionCollection() { /// <summary> Contains the collection of the document&apos;s [section](section.md) objects. </summary> /// <field name="context" type="Word.RequestContext">The request context associated with this object</field> /// <field name="items" type="Array" elementType="Word.Section">Gets the loaded child items in this collection.</field> } SectionCollection.prototype.load = function(option) { /// <summary> /// Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. /// </summary> /// <param name="option" type="string | string[] | OfficeExtension.LoadOption"/> /// <returns type="Word.SectionCollection"/> } return SectionCollection; })(OfficeExtension.ClientObject); Word.SectionCollection = SectionCollection; })(Word || (Word = {})); var Word; (function (Word) { var UnderlineType = { __proto__: null, "none": "none", "single": "single", "word": "word", "double": "double", "dotted": "dotted", "hidden": "hidden", "thick": "thick", "dashLine": "dashLine", "dotLine": "dotLine", "dotDashLine": "dotDashLine", "twoDotDashLine": "twoDotDashLine", "wave": "wave", } Word.UnderlineType = UnderlineType; })(Word || (Word = {})); var Word; (function (Word) { var RequestContext = (function (_super) { __extends(RequestContext, _super); function RequestContext() { /// <summary> /// The RequestContext object facilitates requests to the Word application. Since the Office add-in and the Word application run in two different processes, the request context is required to get access to the Word object model from the add-in. /// </summary> /// <field name="document" type="Word.Document">Root object for interacting with the document</field> _super.call(this, null); } return RequestContext; })(OfficeExtension.ClientRequestContext); Word.RequestContext = RequestContext; Word.run = function (batch) { /// <summary> /// Executes a batch script that performs actions on the Word object model. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. /// </summary> /// <param name="batch" type="function(context) { ... }"> /// A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). /// <br /> /// The context parameter facilitates requests to the Word application. Since the Office add-in and the Word application run in two different processes, the request context is required to get access to the Word object model from the add-in. /// </param> batch(new Word.RequestContext()); return new OfficeExtension.IPromise(); } })(Word || (Word = {})); Word.__proto__ = null;
'use strict'; var stubs = require('../stubs'); stubs.messageKeys(); var assert = require('assert'); var simpleAppMessage = require('../../../src/js/index'); var utils = require('../../../src/js/utils'); var fixtures = require('../fixtures'); var sinon = require('sinon'); var serialize = require('../../../src/js/lib/serialize'); describe('simpleAppMessage', function() { beforeEach(function() { stubs.Pebble(); simpleAppMessage._chunkSize = 0; }); describe('.send', function() { it('fetches the chunk size if not already defined then calls ._sendData()', function(done) { var appMessageData = fixtures.appMessageData(); sinon.stub(simpleAppMessage, '_sendData').callsArg(1); Pebble.sendAppMessage.callsArg(1); simpleAppMessage.send(appMessageData, function() { assert.strictEqual(simpleAppMessage._sendData.callCount, 1); simpleAppMessage._sendData.restore(); done(); }); Pebble.addEventListener .withArgs('appmessage') .callArgWith(1, { payload: utils.objectToMessageKeys({ SIMPLE_APP_MESSAGE_CHUNK_SIZE: 64 }) }); assert(Pebble.sendAppMessage.calledWith( utils.objectToMessageKeys({ SIMPLE_APP_MESSAGE_CHUNK_SIZE: 1 }) )); assert.strictEqual(simpleAppMessage._chunkSize, 64); }); it('does not fetch the chunk size if already defined then calls ._sendData', function(done) { var appMessageData = fixtures.appMessageData(); sinon.stub(simpleAppMessage, '_sendData').callsArg(1); simpleAppMessage._chunkSize = 64; Pebble.sendAppMessage.callsArg(1); simpleAppMessage.send(appMessageData, function() { assert.strictEqual(simpleAppMessage._sendData.callCount, 1); simpleAppMessage._sendData.restore(); done(); }); assert(Pebble.sendAppMessage.neverCalledWith( utils.objectToMessageKeys({ SIMPLE_APP_MESSAGE_CHUNK_SIZE: 1 }) )); assert.strictEqual(simpleAppMessage._chunkSize, 64); }); it('throws if the returned chunk size is zero', function() { var error = {error: 'someError'}; simpleAppMessage.send({}, function() {}); sinon.stub(simpleAppMessage, '_sendData'); sinon.stub(console, 'log'); Pebble.sendAppMessage.callArgWith(2, error); assert(Pebble.sendAppMessage.calledWith( utils.objectToMessageKeys({ SIMPLE_APP_MESSAGE_CHUNK_SIZE: 1 }) )); assert(console.log.calledWithMatch('Failed to request chunk size')); assert(console.log.calledWith(JSON.stringify(error))); simpleAppMessage._sendData.restore(); console.log.restore(); }); it('logs an error for failed app messages', function() { simpleAppMessage.send({}, function() {}); assert.throws(function() { Pebble.addEventListener .withArgs('appmessage') .callArgWith(1, { payload: utils.objectToMessageKeys({ SIMPLE_APP_MESSAGE_CHUNK_SIZE: 0 }) }); }); assert(Pebble.sendAppMessage.calledWith( utils.objectToMessageKeys({ SIMPLE_APP_MESSAGE_CHUNK_SIZE: 1 }) )); assert.strictEqual(simpleAppMessage._chunkSize, 0); }); }); describe('._sendData', function() { it('calls _sendChunk for each chunk in order', function(done) { var callback = sinon.spy(function() { done(); }); var data = {test1: 'value1', test2: 'value2'}; sinon.spy(simpleAppMessage, '_sendChunk'); simpleAppMessage._chunkSize = 16; Pebble.sendAppMessage.onFirstCall().callsArg(1); Pebble.sendAppMessage.onSecondCall().callsArg(1); simpleAppMessage._sendData(data, callback); var chunk1 = serialize(data).slice(0, 16); var chunk2 = serialize(data).slice(16); sinon.assert.callOrder( simpleAppMessage._sendChunk.withArgs(chunk1, 2), simpleAppMessage._sendChunk.withArgs(chunk2, 2), callback ); simpleAppMessage._sendChunk.restore(); }); it('passes an error to the callback if failed', function(done) { var expectedError = {some: 'error'}; simpleAppMessage._chunkSize = 16; // success on first message Pebble.sendAppMessage.onFirstCall().callsArg(1); // fail on second Pebble.sendAppMessage.onSecondCall().callsArgWith(2, expectedError); simpleAppMessage._sendData({test1: 'TEST1', test2: 'TEST2'}, function(error) { assert.deepEqual(error, expectedError); done(); }); }); it('does not pass an error to the callback if successful', function(done) { simpleAppMessage._chunkSize = 16; // success on first and second message Pebble.sendAppMessage.onFirstCall().callsArg(1); Pebble.sendAppMessage.onSecondCall().callsArgWith(1); simpleAppMessage._sendData({test1: 'TEST1', test2: 'TEST2'}, function(error) { assert.strictEqual(typeof error, 'undefined'); done(); }); }); }); describe('._sendChunk', function() { it('sends the chunk with the correct data and returns a promise', function() { var chunk = serialize({test1: 'TEST1', test2: 'TEST2'}); var result = simpleAppMessage._sendChunk(chunk, 1); sinon.assert.calledWith(Pebble.sendAppMessage, utils.objectToMessageKeys({ SIMPLE_APP_MESSAGE_CHUNK_DATA: chunk, SIMPLE_APP_MESSAGE_CHUNK_TOTAL: 1 })); assert.strictEqual(typeof result.then, 'function'); assert.strictEqual(typeof result.catch, 'function'); }); }); });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'li', classNameBindings: [':legislator', 'legislator.isSelected:selected'], legislator: null, click: function(){ this.sendAction(); this.get('legislator').set('isSelected', true); } });
//Autogenerated by ../../build_app.js import sampled_data from 'ember-fhir-adapter/models/sampled-data'; export default sampled_data;
/* * Globalize Culture hi-IN * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ msos.provide("msos.intl.hi.in"); msos.intl.hi['in'] = { name: "hi-IN", englishName: "Hindi (India)", nativeName: "हिंदी (भारत)", language: "hi", numberFormat: { groupSizes: [3,2], percent: { groupSizes: [3,2] }, currency: { pattern: ["$ -n","$ n"], groupSizes: [3,2], symbol: "रु" } }, calendars: { standard: { "/": "-", firstDay: 1, days: { names: ["रविवार","सोमवार","मंगलवार","बुधवार","गुरुवार","शुक्रवार","शनिवार"], namesAbbr: ["रवि.","सोम.","मंगल.","बुध.","गुरु.","शुक्र.","शनि."], namesShort: ["र","स","म","ब","ग","श","श"] }, months: { names: ["जनवरी","फरवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्तूबर","नवम्बर","दिसम्बर",""], namesAbbr: ["जनवरी","फरवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्तूबर","नवम्बर","दिसम्बर",""] }, AM: ["पूर्वाह्न","पूर्वाह्न","पूर्वाह्न"], PM: ["अपराह्न","अपराह्न","अपराह्न"], patterns: { d: "dd-MM-yyyy", D: "dd MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dd MMMM yyyy HH:mm", F: "dd MMMM yyyy HH:mm:ss", M: "dd MMMM" } } } };