code
stringlengths
2
1.05M
{ if (x === 104) { return null; } }
const path = require('path') const express = require('express') const bodyParser = require('body-parser') const github = require('./routes/github') const authRoutes = require('./routes/auth') const userRoutes = require('./routes/users') const tagRoutes = require('./routes/tags') const sprintRoutes = require('./routes/sprints') const userProfile = require('./routes/profile') const server = express() server.use(express.static(path.join(__dirname, 'public'))) server.use(bodyParser.json()) server.use('/auth/github', github) server.use('/api/v1/auth', authRoutes) server.use('/api/v1/users', userRoutes) server.use('/api/v1/tags', tagRoutes) server.use('/api/v1/sprints', sprintRoutes) server.use('/api/v1/profile', userProfile) // Default route for non-API requests server.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'public/index.html')) }) module.exports = server
/** * Broadcast updates to client when the model changes */ 'use strict'; var Law = require('./law.model'); exports.register = function (socket) { Law.schema.post('save', function (doc) { onSave(socket, doc); }); Law.schema.post('remove', function (doc) { onRemove(socket, doc); }); } function onSave(socket, doc, cb) { socket.emit('law:save', doc); } function onRemove(socket, doc, cb) { socket.emit('law:remove', doc); }
'use strict'; angular.module('mean.icu.data.settingsservice', []) .service('SettingServices', function($http) { function getAll() { return $http.get('/api/admin/moduleSettings/icu').then(function(result) { return result.data; }); } return { getAll: getAll }; });
'use strict'; angular.module('contentCardsApp.version', [ 'contentCardsApp.version.CardView' ]) .value('version', '0.1');
import {BreezeObservationAdapter} from '../src/observation-adapter'; import breeze from 'breeze'; import getEntityManager from './breeze-setup'; describe('breeze observation adapter', function() { var entityManager, memberType, repositoryType; beforeAll(() => { entityManager = getEntityManager(); memberType = entityManager.metadataStore.getEntityType('Member'); repositoryType = entityManager.metadataStore.getEntityType('Repository'); }); beforeEach(() => { entityManager.clear(); }); it('can construct the adapter', () => { var adapter = new BreezeObservationAdapter(); expect(adapter).toBeDefined(); }); it('ignores entity properties that are not observable', () => { var adapter = new BreezeObservationAdapter(), entity = memberType.createEntity(); expect(adapter.handlesProperty(entity, 'entityAspect')).toBe(false); expect(adapter.handlesProperty(entity, 'entityType')).toBe(false); }); it('ignores pojo properties', () => { var adapter = new BreezeObservationAdapter(), entity = { foo: 'bar' }; expect(adapter.handlesProperty(entity, 'foo')).toBe(false); }); it('ignores undefined properties', () => { var adapter = new BreezeObservationAdapter(), entity = {}; expect(adapter.handlesProperty(entity, 'foo')).toBe(false); }); it('handles breeze scalar properties', () => { var adapter = new BreezeObservationAdapter(), entity = memberType.createEntity(); expect(adapter.handlesProperty(entity, 'id')).toBe(true); }); it('handles non-scalar navigation properties', () => { var adapter = new BreezeObservationAdapter(), member = entityManager.createEntity(memberType, { memberId: 1, id: 1 }), repository = entityManager.createEntity(repositoryType, { id: 'aurelia/binding', memberId: 1 }); expect(member.repositories).toBeDefined(); expect(member.repositories.constructor).toBe(Array); expect(member.repositories.length).toBe(1); var descriptor = Object.getPropertyDescriptor(member, 'repository'); expect(descriptor).toBeUndefined(); expect(adapter.handlesProperty(member, 'repositories')).toBe(false); }); it('handles scalar navigation properties', () => { var adapter = new BreezeObservationAdapter(), member = entityManager.createEntity(memberType, { memberId: 1, id: 1 }), repository = entityManager.createEntity(repositoryType, { id: 'aurelia/binding', memberId: 1 }); expect(repository.member).toBeDefined(); var descriptor = Object.getPropertyDescriptor(repository, 'member'); expect(descriptor).toBeDefined(); expect(adapter.handlesProperty(repository, 'member')).toBe(true); }); it('handles non-scalar data properties', () => { var adapter = new BreezeObservationAdapter(), member = entityManager.createEntity(memberType, { memberId: 1, id: 1 }), repository = entityManager.createEntity(repositoryType, { id: 'aurelia/binding', memberId: 1, files: ['breeze.js', 'aurelia.js'] }); expect(repository.files).toBeDefined(); var descriptor = Object.getPropertyDescriptor(repository, 'files'); expect(descriptor).toBeDefined(); expect(adapter.handlesProperty(repository, 'files')).toBe(true); }); it('handles detached entities', () => { var adapter = new BreezeObservationAdapter(), entity = memberType.createEntity({ id: 0 }); expect(adapter.handlesProperty(entity, 'id')).toBe(true); expect(adapter.handlesProperty(entity, 'login')).toBe(true); }); it('handles attached entities', () => { var adapter = new BreezeObservationAdapter(), entity = entityManager.createEntity(memberType, { memberId: 0, id: 0 }); expect(adapter.handlesProperty(entity, 'id')).toBe(true); expect(adapter.handlesProperty(entity, 'login')).toBe(true); }); it('returns observer matching property-observer interface', () => { var adapter = new BreezeObservationAdapter(), entity = entityManager.createEntity(memberType, { memberId: 0, id: 0 }), observer = adapter.getObserver(entity, 'id'); expect(observer.propertyName).toBe('id'); expect(Object.prototype.toString.call(observer.getValue)).toBe('[object Function]'); expect(Object.prototype.toString.call(observer.setValue)).toBe('[object Function]'); expect(Object.prototype.toString.call(observer.subscribe)).toBe('[object Function]'); }); it('reuses property observers', () => { var adapter = new BreezeObservationAdapter(), entity = entityManager.createEntity(memberType, { memberId: 0, id: 0 }), observer1 = adapter.getObserver(entity, 'id'), observer2 = adapter.getObserver(entity, 'id'); expect(observer1).toBe(observer2); }); }); describe('detached entity observation', function() { var entityManager, memberType, repositoryType, adapter, entity, idObserver, disposeId, loginObserver, disposeLogin, change; beforeAll(() => { entityManager = getEntityManager(); memberType = entityManager.metadataStore.getEntityType('Member'); repositoryType = entityManager.metadataStore.getEntityType('Repository'); adapter = new BreezeObservationAdapter(), entity = memberType.createEntity({ id: 0, login: 'foo' }), idObserver = adapter.getObserver(entity, 'id'), loginObserver = adapter.getObserver(entity, 'login'); }); it('is a detached entity', () => { expect(entity.entityAspect.entityState.isDetached()).toBe(true); }); it('gets and sets value', () => { expect(idObserver.getValue()).toBe(entity.id); expect(loginObserver.getValue()).toBe(entity.login); entity.id = 1; entity.login = 'bar'; expect(idObserver.getValue()).toBe(entity.id); expect(loginObserver.getValue()).toBe(entity.login); idObserver.setValue(0); loginObserver.setValue('foo'); expect(entity.id).toBe(0); expect(entity.login).toBe('foo'); expect(idObserver.getValue()).toBe(entity.id); expect(loginObserver.getValue()).toBe(entity.login); // }); // // it('subscribes', () => { disposeId = idObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); disposeLogin = loginObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); expect(Object.prototype.toString.call(disposeId)).toBe('[object Function]'); expect(Object.prototype.toString.call(disposeLogin)).toBe('[object Function]'); // }); // // it('tracks changes while subscribed', () => { change = null; entity.id = 1; expect(change && change.newValue === 1 && change.oldValue === 0).toBe(true); change = null; idObserver.setValue(2); expect(change && change.newValue === 2 && change.oldValue === 1).toBe(true); change = null; entity.login = 'bar'; expect(change && change.newValue === 'bar' && change.oldValue === 'foo').toBe(true); change = null; loginObserver.setValue('baz'); expect(change && change.newValue === 'baz' && change.oldValue === 'bar').toBe(true); // }); // // it('unsubscribes', () => { expect(entity.__breezeObserver__.callbackCount).toBe(2); disposeId(); expect(entity.__breezeObserver__.callbackCount).toBe(1); disposeLogin(); expect(entity.__breezeObserver__.callbackCount).toBe(0); // todo: find out if disposing extra times should throw. disposeId(); disposeLogin(); expect(entity.__breezeObserver__.callbackCount).toBe(0); // }); // // it('does not track changes while unsubscribed', () => { change = null; entity.id = 3; expect(change).toBe(null); idObserver.setValue(0); expect(change).toBe(null); entity.login = 'fizz'; expect(change).toBe(null); change = null; loginObserver.setValue('foo'); expect(change).toBe(null); // }); // // it('re-subscribes', () => { disposeId = idObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); disposeLogin = loginObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); expect(Object.prototype.toString.call(disposeId)).toBe('[object Function]'); expect(Object.prototype.toString.call(disposeLogin)).toBe('[object Function]'); // }); // // it('tracks changes after re-subscribing', () => { change = null; entity.id = 1; expect(change && change.newValue === 1 && change.oldValue === 0).toBe(true); change = null; idObserver.setValue(2); expect(change && change.newValue === 2 && change.oldValue === 1).toBe(true); change = null; entity.login = 'bar'; expect(change && change.newValue === 'bar' && change.oldValue === 'foo').toBe(true); change = null; loginObserver.setValue('baz'); expect(change && change.newValue === 'baz' && change.oldValue === 'bar').toBe(true); }); }); // todo: find way to reuse previous set of tests. describe('attached entity observation', function() { var entityManager, memberType, repositoryType, adapter, entity, idObserver, disposeId, loginObserver, disposeLogin, change; beforeAll(() => { entityManager = getEntityManager(); memberType = entityManager.metadataStore.getEntityType('Member'); repositoryType = entityManager.metadataStore.getEntityType('Repository'); adapter = new BreezeObservationAdapter(), entity = memberType.createEntity({ id: 0, login: 'foo' }), idObserver = adapter.getObserver(entity, 'id'), loginObserver = adapter.getObserver(entity, 'login'); entityManager.attachEntity(entity); }); it('is an attached entity', () => { expect(entity.entityAspect.entityState.isDetached()).toBe(false); }); it('gets and sets value', () => { expect(idObserver.getValue()).toBe(entity.id); expect(loginObserver.getValue()).toBe(entity.login); entity.id = 1; entity.login = 'bar'; expect(idObserver.getValue()).toBe(entity.id); expect(loginObserver.getValue()).toBe(entity.login); idObserver.setValue(0); loginObserver.setValue('foo'); expect(entity.id).toBe(0); expect(entity.login).toBe('foo'); expect(idObserver.getValue()).toBe(entity.id); expect(loginObserver.getValue()).toBe(entity.login); // }); // // it('subscribes', () => { disposeId = idObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); disposeLogin = loginObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); expect(Object.prototype.toString.call(disposeId)).toBe('[object Function]'); expect(Object.prototype.toString.call(disposeLogin)).toBe('[object Function]'); // }); // // it('tracks changes while subscribed', () => { change = null; entity.id = 1; expect(change && change.newValue === 1 && change.oldValue === 0).toBe(true); change = null; idObserver.setValue(2); expect(change && change.newValue === 2 && change.oldValue === 1).toBe(true); change = null; entity.login = 'bar'; expect(change && change.newValue === 'bar' && change.oldValue === 'foo').toBe(true); change = null; loginObserver.setValue('baz'); expect(change && change.newValue === 'baz' && change.oldValue === 'bar').toBe(true); // }); // // it('unsubscribes', () => { expect(entity.__breezeObserver__.callbackCount).toBe(2); disposeId(); expect(entity.__breezeObserver__.callbackCount).toBe(1); disposeLogin(); expect(entity.__breezeObserver__.callbackCount).toBe(0); // todo: find out if disposing extra times should throw. disposeId(); disposeLogin(); expect(entity.__breezeObserver__.callbackCount).toBe(0); // }); // // it('does not track changes while unsubscribed', () => { change = null; entity.id = 3; expect(change).toBe(null); idObserver.setValue(0); expect(change).toBe(null); entity.login = 'fizz'; expect(change).toBe(null); change = null; loginObserver.setValue('foo'); expect(change).toBe(null); // }); // // it('re-subscribes', () => { disposeId = idObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); disposeLogin = loginObserver.subscribe((newValue, oldValue) => { change = { newValue: newValue, oldValue: oldValue }; }); expect(Object.prototype.toString.call(disposeId)).toBe('[object Function]'); expect(Object.prototype.toString.call(disposeLogin)).toBe('[object Function]'); // }); // // it('tracks changes after re-subscribing', () => { change = null; entity.id = 1; expect(change && change.newValue === 1 && change.oldValue === 0).toBe(true); change = null; idObserver.setValue(2); expect(change && change.newValue === 2 && change.oldValue === 1).toBe(true); change = null; entity.login = 'bar'; expect(change && change.newValue === 'bar' && change.oldValue === 'foo').toBe(true); change = null; loginObserver.setValue('baz'); expect(change && change.newValue === 'baz' && change.oldValue === 'bar').toBe(true); entityManager.acceptChanges(); entity.login = 'boom'; expect(change && change.newValue === 'boom' && change.oldValue === 'baz').toBe(true); change = null; entityManager.rejectChanges(); expect(change && change.newValue === 'baz' && change.oldValue === 'boom').toBe(true); }); });
/*jshint esversion:6 */ const mongoose = require('mongoose'); const mongoose_config = require('../../../mongoose_config'); mongoose.Promise = global.Promise; // // fall- back // mongoose.connect('mongodb://mongoose_config.user:mongoose_config.password@192.168.1.30/mongoose_config.database'); // var db = mongoose.connection; var opts = { server: { auto_reconnect: false }, user: mongoose_config.user, pass: mongoose_config.password }; db = mongoose.createConnection(mongoose_config.host, mongoose_config.database, mongoose_config.port, opts); // var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } // db = mongoose.createConnection('localhost', 'database', port, opts) db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("connected"); }); var kittySchema = new mongoose.Schema({ name: { type: String, required: true, index: { unique: true }, trim: true } }); kittySchema.methods.meow = function () { var greeting = this.name ? "Meow name is " + this.name : "I don't have a name"; console.log(greeting); }; var Kitten = db.model('Kitten', kittySchema); module.exports.Kitten = Kitten;
var searchData= [ ['what',['what',['../classtracery_1_1_tracery_exception.html#a3706603e7ec4aee2902022d2b1545809',1,'tracery::TraceryException']]] ];
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _sharedStyle = require('../../shared-style'); var SharedStyle = _interopRequireWildcard(_sharedStyle); var _md = require('react-icons/md'); var _constants = require('../../constants'); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } 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 STYLE_INPUT = { display: 'block', width: '100%', padding: '0 2px', fontSize: '13px', lineHeight: '1.25', color: SharedStyle.PRIMARY_COLOR.input, backgroundColor: SharedStyle.COLORS.white, backgroundImage: 'none', border: '1px solid rgba(0,0,0,.15)', outline: 'none', height: '30px' }; var confirmStyle = { position: 'absolute', cursor: 'pointer', width: '2em', height: '2em', right: '0.35em', top: '0.35em', backgroundColor: SharedStyle.SECONDARY_COLOR.main, color: '#FFF', transition: 'all 0.1s linear' }; var FormNumberInput = function (_Component) { _inherits(FormNumberInput, _Component); function FormNumberInput(props, context) { _classCallCheck(this, FormNumberInput); var _this = _possibleConstructorReturn(this, (FormNumberInput.__proto__ || Object.getPrototypeOf(FormNumberInput)).call(this, props, context)); _this.state = { focus: false, valid: true, showedValue: props.value }; return _this; } _createClass(FormNumberInput, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.value !== nextProps.value) { this.setState({ showedValue: nextProps.value }); } } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, value = _props.value, min = _props.min, max = _props.max, precision = _props.precision, onChange = _props.onChange, onValid = _props.onValid, onInvalid = _props.onInvalid, style = _props.style, placeholder = _props.placeholder; var numericInputStyle = _extends({}, STYLE_INPUT, style); if (this.state.focus) numericInputStyle.border = '1px solid ' + SharedStyle.SECONDARY_COLOR.main; var regexp = new RegExp('^-?([0-9]+)?\\.?([0-9]{0,' + precision + '})?$'); if (!isNaN(min) && isFinite(min) && this.state.showedValue < min) this.setState({ showedValue: min }); // value = min; if (!isNaN(max) && isFinite(max) && this.state.showedValue > max) this.setState({ showedValue: max }); // value = max; var currValue = regexp.test(this.state.showedValue) ? this.state.showedValue : parseFloat(this.state.showedValue).toFixed(precision); var different = parseFloat(this.props.value).toFixed(precision) !== parseFloat(this.state.showedValue).toFixed(precision); var saveFn = function saveFn(e) { e.stopPropagation(); if (_this2.state.valid) { var savedValue = _this2.state.showedValue !== '' && _this2.state.showedValue !== '-' ? parseFloat(_this2.state.showedValue) : 0; _this2.setState({ showedValue: savedValue }); onChange({ target: { value: savedValue } }); } }; return _react2.default.createElement( 'div', { style: { position: 'relative' } }, _react2.default.createElement('input', { type: 'text', value: currValue, style: numericInputStyle, onChange: function onChange(evt) { var valid = regexp.test(evt.nativeEvent.target.value); if (valid) { _this2.setState({ showedValue: evt.nativeEvent.target.value }); if (onValid) onValid(evt.nativeEvent); } else { if (onInvalid) onInvalid(evt.nativeEvent); } _this2.setState({ valid: valid }); }, onFocus: function onFocus(e) { return _this2.setState({ focus: true }); }, onBlur: function onBlur(e) { return _this2.setState({ focus: false }); }, onKeyDown: function onKeyDown(e) { var keyCode = e.keyCode || e.which; if ((keyCode == _constants.KEYBOARD_BUTTON_CODE.ENTER || keyCode == _constants.KEYBOARD_BUTTON_CODE.TAB) && different) { saveFn(e); } }, placeholder: placeholder }), _react2.default.createElement( 'div', { onClick: function onClick(e) { if (different) saveFn(e); }, title: this.context.translator.t('Confirm'), style: _extends({}, confirmStyle, { visibility: different ? 'visible' : 'hidden', opacity: different ? '1' : '0' }) }, _react2.default.createElement(_md.MdUpdate, { style: { width: '100%', height: '100%', padding: '0.2em', color: '#FFF' } }) ) ); } }]); return FormNumberInput; }(_react.Component); exports.default = FormNumberInput; FormNumberInput.propTypes = { value: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]), style: _propTypes2.default.object, onChange: _propTypes2.default.func.isRequired, onValid: _propTypes2.default.func, onInvalid: _propTypes2.default.func, min: _propTypes2.default.number, max: _propTypes2.default.number, precision: _propTypes2.default.number, placeholder: _propTypes2.default.string }; FormNumberInput.contextTypes = { translator: _propTypes2.default.object.isRequired }; FormNumberInput.defaultProps = { value: 0, style: {}, min: Number.MIN_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER, precision: 3 };
/** * Module dependencies. */ var Application = require('./application') , Controller = require('./controller'); /** * Expose default singleton. * * @api public */ exports = module.exports = new Application(); /** * Framework version. */ require('pkginfo')(module, 'version'); /** * Export constructors. */ exports.emvc = exports.Application = Application; exports.Controller = Controller; /** * Export boot phases. */ exports.boot.controllers = require('./boot/controllers'); exports.boot.views = require('./boot/views'); exports.boot.routes = require('./boot/routes'); exports.boot.httpServer = require('./boot/httpserver'); exports.boot.httpServerCluster = require('./boot/httpservercluster'); exports.boot.httpsServer = require('./boot/httpsserver'); exports.boot.httpsServerCluster = require('./boot/httpsservercluster'); exports.boot.di = {}; exports.boot.di.routes = require('./boot/di/routes');
// @ts-check const { app, protocol, session } = require('electron'); const { readFile } = require('fs'); const isDev = require('electron-is-dev'); const { setupAutoUpdates } = require('../updates'); const { InMemoryStore } = require('../store'); const WindowManager = require('./window'); const settingsStore = require('../settings/main/store'); class ElectronApp { start() { const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { console.log('An instance already exists.'); return app.quit(); } this.store = new InMemoryStore(); this.windowManager = new WindowManager(this); protocol.registerSchemesAsPrivileged([ { scheme: 'altair', privileges: { standard: true, secure: true, corsEnabled: true, supportFetchAPI: true } } ]); this.manageEvents(); } manageEvents() { // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', async () => { /** * @type any */ const settings = settingsStore.get('settings'); console.log(settings); if (settings) { /** * @type Electron.Config */ const proxyConfig = { mode: 'direct', }; switch (settings.proxy_setting) { case 'none': proxyConfig.mode = 'direct'; break; case 'autodetect': proxyConfig.mode = 'auto_detect'; break; case 'system': proxyConfig.mode = 'system'; break; case 'pac': proxyConfig.mode = 'pac_script'; proxyConfig.pacScript = settings.pac_address; break; case 'proxy_server': proxyConfig.mode = 'fixed_servers'; proxyConfig.proxyRules = `${settings.proxy_host}:${settings.proxy_port}`; break; default: } await session.defaultSession.setProxy(proxyConfig); const proxy = await session.defaultSession.resolveProxy('http://localhost'); console.log(proxy, proxyConfig); } this.windowManager.createWindow(); if (!isDev) { setupAutoUpdates(); } }); // Quit when all windows are closed. app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (!this.windowManager.getInstance()) { this.windowManager.createWindow(); } }); app.on('will-finish-launching', () => { app.on('open-file', (ev, path) => { readFile(path, 'utf8', (err, data) => { if (err) { return; } const instance = this.windowManager.getInstance(); if (instance) { instance.webContents.send('file-opened', data); } this.store.set('file-opened', data); }); }); }); app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { event.preventDefault(); callback(true); // Inform user of invalid certificate webContents.send('certificate-error', error); }); app.on('web-contents-created', (event, contents) => { contents.on('new-window', (e, navigationUrl) => { // Ask the operating system to open this event's url in the default browser. e.preventDefault(); const { shell } = require('electron'); shell.openExternal(navigationUrl); }); }); } } module.exports = ElectronApp;
var express = require("express") , app = express() , http = require("http").createServer(app) , bodyParser = require("body-parser") , io = require("socket.io").listen(http) , _ = require("underscore"); var participants = []; var pointsDrawn = [] var undoPointStore = [] app.set('port', process.env.PORT || 8080); app.use(bodyParser.json()); app.set("views", __dirname + "/views"); app.set("view engine", "jade"); app.use(express.static("public", __dirname + "/public")); /* Server routing */ app.get("/", function(request, response) { response.render("index"); }); app.post("/message", function(request, response) { var message = request.body.message; if(_.isUndefined(message) || _.isEmpty(message.trim())) { return response.json(400, {error: "Message is invalid"}); } var name = request.body.name; io.sockets.emit("incomingMessage", {message: message, name: name}); response.json(200, {message: "Message received"}); }); /* Socket.IO events */ io.on("connection", function(socket){ socket.on("newUser", function(data) { participants.push({id: data.id, name: data.name}); io.sockets.emit("newConnection", {participants: participants, pointsDrawn: pointsDrawn, undoPointStore: undoPointStore}); }); socket.on("drawPoint", function(data) { pointsDrawn = data.pointsDrawn undoPointStore = data.undoPointStore socket.broadcast.emit("redrawFrame", {pointsDrawn: pointsDrawn, undoPointStore: undoPointStore}) }); socket.on("nameChange", function(data) { _.findWhere(participants, {id: socket.id}).name = data.name; io.sockets.emit("nameChanged", {id: data.id, name: data.name}); }); socket.on("disconnect", function() { participants = _.without(participants,_.findWhere(participants, {id: socket.id})); io.sockets.emit("userDisconnected", {id: socket.id, sender:"system"}); }); }); http.listen(process.env.PORT || 8080, function() { console.log("Server up and running."); });
var connect = require('react-redux').connect; var SecurityActions = require('../actions/SecurityActions'); var SecurityTemplateActions = require('../actions/SecurityTemplateActions'); var ErrorActions = require('../actions/ErrorActions'); var SecuritiesTab = require('../components/SecuritiesTab'); function mapStateToProps(state) { var selectedSecurityAccounts = []; for (var accountId in state.accounts.map) { if (state.accounts.map.hasOwnProperty(accountId) && state.accounts.map[accountId].SecurityId == state.selectedSecurity) selectedSecurityAccounts.push(state.accounts.map[accountId]); } return { user: state.user, securities: state.securities.map, security_list: state.securities.list, selectedSecurityAccounts: selectedSecurityAccounts, selectedSecurity: state.selectedSecurity, securityTemplates: state.securityTemplates } } function mapDispatchToProps(dispatch) { return { onCreateSecurity: function(security) {dispatch(SecurityActions.create(security))}, onUpdateSecurity: function(security) {dispatch(SecurityActions.update(security))}, onDeleteSecurity: function(securityId) {dispatch(SecurityActions.remove(securityId))}, onSelectSecurity: function(securityId) {dispatch(SecurityActions.select(securityId))}, onSearchTemplates: function(search, type, limit) {dispatch(SecurityTemplateActions.search(search, type, limit))}, onUserError: function(error) {dispatch(ErrorActions.userError(error))} } } module.exports = connect( mapStateToProps, mapDispatchToProps )(SecuritiesTab)
var app = require('../../lib/app.js'), request = require('request'); var World = function(cb) { this.app = app; this.currentPage = '/'; this.request = request; this.proxiedServer = undefined; this.proxiedChunk = ""; cb(); } module.exports = World;
var searchData= [ ['h',['h',['../struct_s_fixed_font_info.html#a5116a6259c857fffdbbfc0867ced31b9',1,'SFixedFontInfo']]], ['height',['height',['../structssd1306__lcd__t.html#af576fdaf144fefdb8e278ca3cb90f49e',1,'ssd1306_lcd_t::height()'],['../struct_s_font_header_record.html#ad650740842794fe175eb1dccfa3cedea',1,'SFontHeaderRecord::height()'],['../struct_s_char_info.html#a8bd0a76b2bebe145437473ab3c1b8a2b',1,'SCharInfo::height()']]] ];
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react = require("react"); var _react2 = _interopRequireDefault(_react); var _propTypes = require("prop-types"); var _propTypes2 = _interopRequireDefault(_propTypes); var _BarSeries = require("./BarSeries"); var _BarSeries2 = _interopRequireDefault(_BarSeries); var _LineSeries = require("./LineSeries"); var _LineSeries2 = _interopRequireDefault(_LineSeries); var _StraightLine = require("./StraightLine"); var _StraightLine2 = _interopRequireDefault(_StraightLine); 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 MACDSeries = function (_Component) { _inherits(MACDSeries, _Component); function MACDSeries(props) { _classCallCheck(this, MACDSeries); var _this = _possibleConstructorReturn(this, (MACDSeries.__proto__ || Object.getPrototypeOf(MACDSeries)).call(this, props)); _this.yAccessorForMACD = _this.yAccessorForMACD.bind(_this); _this.yAccessorForSignal = _this.yAccessorForSignal.bind(_this); _this.yAccessorForDivergence = _this.yAccessorForDivergence.bind(_this); _this.yAccessorForDivergenceBase = _this.yAccessorForDivergenceBase.bind(_this); return _this; } _createClass(MACDSeries, [{ key: "yAccessorForMACD", value: function yAccessorForMACD(d) { var yAccessor = this.props.yAccessor; return yAccessor(d) && yAccessor(d).macd; } }, { key: "yAccessorForSignal", value: function yAccessorForSignal(d) { var yAccessor = this.props.yAccessor; return yAccessor(d) && yAccessor(d).signal; } }, { key: "yAccessorForDivergence", value: function yAccessorForDivergence(d) { var yAccessor = this.props.yAccessor; return yAccessor(d) && yAccessor(d).divergence; } }, { key: "yAccessorForDivergenceBase", value: function yAccessorForDivergenceBase(xScale, yScale /* , d */) { return yScale(0); } }, { key: "render", value: function render() { var _props = this.props, className = _props.className, opacity = _props.opacity, divergenceStroke = _props.divergenceStroke; var _props2 = this.props, stroke = _props2.stroke, fill = _props2.fill; var clip = this.props.clip; var _props3 = this.props, zeroLineStroke = _props3.zeroLineStroke, zeroLineOpacity = _props3.zeroLineOpacity; return _react2.default.createElement( "g", { className: className }, _react2.default.createElement(_BarSeries2.default, { baseAt: this.yAccessorForDivergenceBase, className: "macd-divergence", widthRatio: 0.5, stroke: divergenceStroke, fill: fill.divergence, opacity: opacity, clip: clip, yAccessor: this.yAccessorForDivergence }), _react2.default.createElement(_LineSeries2.default, { yAccessor: this.yAccessorForMACD, stroke: stroke.macd, fill: "none" }), _react2.default.createElement(_LineSeries2.default, { yAccessor: this.yAccessorForSignal, stroke: stroke.signal, fill: "none" }), _react2.default.createElement(_StraightLine2.default, { stroke: zeroLineStroke, opacity: zeroLineOpacity, yValue: 0 }) ); } }]); return MACDSeries; }(_react.Component); MACDSeries.propTypes = { className: _propTypes2.default.string, yAccessor: _propTypes2.default.func.isRequired, opacity: _propTypes2.default.number, divergenceStroke: _propTypes2.default.bool, zeroLineStroke: _propTypes2.default.string, zeroLineOpacity: _propTypes2.default.number, clip: _propTypes2.default.bool.isRequired, stroke: _propTypes2.default.shape({ macd: _propTypes2.default.string.isRequired, signal: _propTypes2.default.string.isRequired }).isRequired, fill: _propTypes2.default.shape({ divergence: _propTypes2.default.string.isRequired }).isRequired }; MACDSeries.defaultProps = { className: "react-stockcharts-macd-series", zeroLineStroke: "#000000", zeroLineOpacity: 0.3, opacity: 0.6, divergenceStroke: false, clip: true }; exports.default = MACDSeries;
$(function() { var containerItems = $('.NavBar-items'); var page = 1; // var size = 30; var scrollTop = 0; var opts = { 'url': 'api/MDM0001/MDM000105', 'data': { Method: 'Q', Content: { PageNo: page, PageSize: 30, SearchText: '' } }, beforeSend: function(result) { $(".products-wrapper").prepend(html.load); }, complete: function(result) { if (result.status == 200) { Util.Sticky('数据加载成功', result.status, 'success'); } else { Util.Sticky('出现未知错误,请重试。', result.status, 'error'); } $('.Load-wrapper').remove(); } } // 定义请求的通用选项 $('.right-content').on('click', '#searchBtn', function(e) { e.preventDefault(); var val = $('#searchBar').val(); opts.data.Content.SearchText = val; $('.sear-wrapper').addClass('disapear'); getData(1); }); // 请求服务加载数据的方法 function getData(page) { XHR.getData(opts, function(resp) { if (resp.length == 0) { containerItems.html('<div class="u_no_data"><i class="fa fa-info-circle fa-5x"></i><span>没有查询到相关数据</span></div>'); } else { var products = ''; for (var i = 0; i < resp.length; i++) { products += html.productHtml(i, resp[i], page); } if (page > 1) { containerItems.append(products); } else { containerItems.empty().html(products); } } }, function() { }) } $('.NavBar-content').scroll(function(e) { var content = $(this); var height = content.height(); var newTop = content.scrollTop(); var offsetHeight = content[0].scrollHeight; //整个div的高度包括可见部分和不可见部分 var position = (offsetHeight - height) - content.scrollTop(); if (position < 30) { ++page; newTop = page * height; console.log(page); console.log(newTop); getData(page); } }); });
var mongoose = require('mongoose') var Snapshot = mongoose.model('Snapshot', { owner: String, createdAt: { type: Date, expires: 15 * 60, default: Date.now } }); module.exports = Snapshot;
'use strict'; angular.module('issueTracker.labels', []) .factory('Labels', [ '$http', '$q', 'BASE_URL', function ($http, $q, BASE_URL) { function getLabelsByFilter(filter) { var defered = $q.defer(); var url = BASE_URL + 'labels/?filter=' + filter; $http.get(url) .then(function (success) { defered.resolve(success.data); }, function (error) { defered.reject(error); console.log(error); }); return defered.promise; } return{ getLabelsByFilter: getLabelsByFilter }; } ]);
/* eslint-disable max-nested-callbacks */ import { Record, List } from 'immutable' import expect from 'expect' import Constraint from '../Constraint' describe('models/Constraint.js', () => { describe('{ Constraint }', () => { it('should be a Record', () => { const instance = new Constraint.Constraint({}) expect(instance).toBeA(Record) }) describe('#fields', () => { const fields = [ 'name', 'value', 'expression' ] for (const field of fields) { it('should have a `' + field + '` field', () => { const key = field const value = 'test' const data = {} data[key] = value const instance = new Constraint.Constraint(data) expect(instance.get(key)).toEqual(value) }) } }) describe('@evaluate', () => { it('should return false', () => { const mod = new Constraint.Constraint() const expected = false const actual = mod.evaluate() expect(actual).toEqual(expected) }) }) describe('@toJSONSchema', () => { it('should work', () => { const mod = new Constraint.Constraint({ name: 'test', value: 28 }) const expected = { test: 28 } const actual = mod.toJSONSchema() expect(actual).toEqual(expected) }) }) }) describe('{ MultipleOfConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.MultipleOf(4) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.MultipleOf(4) expect(mod.evaluate(4)).toEqual(true) expect(mod.evaluate(24)).toEqual(true) expect(mod.evaluate(5)).toEqual(false) expect(mod.evaluate(5.5)).toEqual(false) }) describe('@toJSONSchema', () => { it('should work', () => { const mod = new Constraint.MultipleOf(4) const expected = { multipleOf: 4 } const actual = mod.toJSONSchema() expect(actual).toEqual(expected) }) }) }) describe('{ MaximumConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.Maximum(4) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.Maximum(4) expect(mod.evaluate(3)).toEqual(true) expect(mod.evaluate(4)).toEqual(true) expect(mod.evaluate(5)).toEqual(false) }) describe('@toJSONSchema', () => { it('should work', () => { const mod = new Constraint.Maximum(4) const expected = { maximum: 4 } const actual = mod.toJSONSchema() expect(actual).toEqual(expected) }) }) }) describe('{ ExclusiveMaximumConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.ExclusiveMaximum(4) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.ExclusiveMaximum(4) expect(mod.evaluate(3)).toEqual(true) expect(mod.evaluate(4)).toEqual(false) expect(mod.evaluate(5)).toEqual(false) }) it('@toJSONSchema works as expected', () => { const mod = new Constraint.ExclusiveMaximum(4) const expected = { maximum: 4, exclusiveMaximum: true } const actual = mod.toJSONSchema() expect(actual).toEqual(expected) }) }) describe('{ MinimumConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.Minimum(4) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.Minimum(4) expect(mod.evaluate(3)).toEqual(false) expect(mod.evaluate(4)).toEqual(true) expect(mod.evaluate(5)).toEqual(true) }) }) describe('{ ExclusiveMinimumConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.ExclusiveMinimum(4) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.ExclusiveMinimum(4) expect(mod.evaluate(3)).toEqual(false) expect(mod.evaluate(4)).toEqual(false) expect(mod.evaluate(5)).toEqual(true) }) it('@toJSONSchema works as expected', () => { const mod = new Constraint.ExclusiveMinimum(4) const expected = { minimum: 4, exclusiveMinimum: true } const actual = mod.toJSONSchema() expect(actual).toEqual(expected) }) }) describe('{ MaximumLengthConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.MaximumLength(4) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.MaximumLength(5) expect(mod.evaluate('this')).toEqual(true) expect(mod.evaluate('short')).toEqual(true) expect(mod.evaluate('too long')).toEqual(false) }) }) describe('{ MinimumLengthConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.MinimumLength(4) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.MinimumLength(10) expect(mod.evaluate('too short')).toEqual(false) expect(mod.evaluate('just right')).toEqual(true) expect(mod.evaluate('long enough')).toEqual(true) }) }) describe('{ PatternConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.Pattern(/.*valid.*/) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.Pattern(/.*valid.*/) expect(mod.evaluate('this is valid')).toEqual(true) expect(mod.evaluate('this is not')).toEqual(false) }) }) describe('{ MaximumItemsConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.MaximumItems(3) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.MaximumItems(3) expect(mod.evaluate([ 1, 2 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, 4 ])).toEqual(false) expect(mod.evaluate(List([ 1, 2, 3 ]))).toEqual(true) expect(mod.evaluate(List([ 1, 2, 3, 4 ]))).toEqual(false) }) it('should work if no value provided', () => { const mod = new Constraint.MaximumItems() expect(mod.evaluate([ 1, 2 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, 4 ])).toEqual(true) }) it('should work if null value provided', () => { const mod = new Constraint.MaximumItems(null) expect(mod.evaluate([ 1, 2 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, 4 ])).toEqual(true) }) }) describe('{ MinimumItemsConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.MinimumItems(3) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.MinimumItems(3) expect(mod.evaluate(List([ 1, 2 ]))).toEqual(false) expect(mod.evaluate(List([ 1, 2, 3 ]))).toEqual(true) expect(mod.evaluate([ 1, 2 ])).toEqual(false) expect(mod.evaluate([ 1, 2, 3 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, 4 ])).toEqual(true) }) it('should work with default value', () => { const mod = new Constraint.MinimumItems() expect(mod.evaluate(List([ 1, 2 ]))).toEqual(true) expect(mod.evaluate(List([ 1, 2, 3 ]))).toEqual(true) expect(mod.evaluate([ 1, 2 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, 4 ])).toEqual(true) }) }) describe('{ UniqueItemsConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.UniqueItems(true) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.UniqueItems(true) expect(mod.evaluate(List([ 1, 2 ]))).toEqual(true) expect(mod.evaluate(List([ 1, 2, 3, 2 ]))).toEqual(false) expect(mod.evaluate([ 1, 2 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, 2 ])).toEqual(false) expect(mod.evaluate([ 1, 2, 3, [ 1, 2, 3 ] ])).toEqual(true) }) it('should work if no value provided', () => { const mod = new Constraint.UniqueItems() expect(mod.evaluate([ 1, 2 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, 2 ])).toEqual(true) expect(mod.evaluate([ 1, 2, 3, [ 1, 2, 3 ] ])).toEqual(true) }) }) describe('{ MaximumPropertiesConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.MaximumProperties(3) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.MaximumProperties(3) expect(mod.evaluate({ a: 1, b: 2 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3, d: 4 })).toEqual(false) }) it('should work if no value provided', () => { const mod = new Constraint.MaximumProperties() expect(mod.evaluate({ a: 1, b: 2 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3, d: 4 })).toEqual(true) }) it('should work if null value provided', () => { const mod = new Constraint.MaximumProperties(null) expect(mod.evaluate({ a: 1, b: 2 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3, d: 4 })).toEqual(true) }) }) describe('{ MinimumPropertiesConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.MinimumProperties(3) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.MinimumProperties(3) expect(mod.evaluate({ a: 1, b: 2 })).toEqual(false) expect(mod.evaluate({ a: 1, b: 2, c: 3 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3, d: 4 })).toEqual(true) }) it('should work with default value', () => { const mod = new Constraint.MinimumProperties() expect(mod.evaluate({ a: 1, b: 2 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3 })).toEqual(true) expect(mod.evaluate({ a: 1, b: 2, c: 3, d: 4 })).toEqual(true) }) }) describe('{ EnumConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.Enum([ 'one', 'two', 'three' ]) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.Enum([ 'one', 'two', 'three' ]) expect(mod.evaluate('one')).toEqual(true) expect(mod.evaluate('two')).toEqual(true) expect(mod.evaluate('four')).toEqual(false) }) }) describe('{ JSONSchemaConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.JSONSchema({ type: 'integer', minimum: 3, maximum: 6 }) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.JSONSchema({ type: 'integer', minimum: 3, maximum: 6 }) expect(mod.evaluate(1)).toEqual(true) expect(mod.evaluate(4)).toEqual(true) expect(mod.evaluate(7)).toEqual(true) }) it('should work with default schema', () => { const mod = new Constraint.JSONSchema() expect(mod.evaluate(1)).toEqual(true) expect(mod.evaluate(4)).toEqual(true) expect(mod.evaluate(7)).toEqual(true) }) describe('@toJSONSchema', () => { it('should work', () => { const mod = new Constraint.JSONSchema({ type: 'integer', minimum: 3, maximum: 6 }) const expected = { type: 'integer', minimum: 3, maximum: 6 } const actual = mod.toJSONSchema() expect(actual).toEqual(expected) }) }) }) describe('{ XMLSchemaConstraint }', () => { it('should be a Constraint', () => { const mod = new Constraint.XMLSchema( `<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="userId" type="xs:string"/> </xs:schema>` ) expect(mod).toBeA(Constraint.Constraint) }) it('should work', () => { const mod = new Constraint.XMLSchema( `<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="userId" type="xs:string"/> </xs:schema>` ) expect(mod.evaluate('1')).toEqual(true) expect(mod.evaluate(4)).toEqual(true) expect(mod.evaluate(null)).toEqual(true) }) it('should work with default value', () => { const mod = new Constraint.XMLSchema() expect(mod.evaluate('1')).toEqual(true) expect(mod.evaluate(4)).toEqual(true) expect(mod.evaluate(null)).toEqual(true) }) describe('@toJSONSchema', () => { it('should work', () => { const mod = new Constraint.XMLSchema( `<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="userId" type="xs:string"/> </xs:schema>` ) const expected = { 'x-xml': `<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="userId" type="xs:string"/> </xs:schema>` } const actual = mod.toJSONSchema() expect(actual).toEqual(expected) }) }) }) })
import Express from 'express'; import Routes from './Routes'; class RouterService { initialize() { const router = new Express.Router(); Routes.addTo(router); return router; } } export default new RouterService();
'use strict'; var server = require('./src/server/main'), config = require('./src/config')(); server.startServer(config);
/********************************************************************************** * Backbone Classes **********************************************************************************/ function genVal() { return Math.floor(Math.random() * 100000); } var TestModel = Backbone.Model.extend({ defaults: { value: undefined }, getPrecision: function() { return this.has("value") ? String(this.get("value")).length : 0; } }); var TestCollection = Backbone.Collection.extend({ model: TestModel, totalValue: function() { return this.reduce(function(memo, model) { return memo + model.get("value"); }, 0); }, oddModels: function() { return this.filter(function(model) { return model.get("value") % 2; }); // within the collection this won't be proxy mapped }, comparator: 'value' // necessary for Reactive Backbone }); var collectionJson, collection2Json; function populateCollections() { return new Promise(function(resolve) { var testCollection = new TestCollection(); for (var i = 0; i < 1000; i++) { testCollection.add({ value: genVal() }); } collectionJson = JSON.stringify(testCollection.toJSON()); testCollection = new TestCollection(); for (var i = 0; i < 1000; i++) { testCollection.add({ value: genVal() }); } collection2Json = JSON.stringify(testCollection.toJSON()); completeTask(resolve); }); }
'use strict'; var libpath = require('path'); var formatters = require('es6-module-transpiler/lib/formatters'); var Container = require('es6-module-transpiler/lib/container'); var NPMFileResolver = require('es6-module-transpiler-npm-resolver'); var UMDWrapperResolver = require('../lib/global-resolver'); var FileResolver = require('es6-module-transpiler/lib/file_resolver'); var FormatterClass = formatters[formatters.DEFAULT]; var resolverClasses = [FileResolver, UMDWrapperResolver, NPMFileResolver]; module.exports = function(grunt) { grunt.registerMultiTask('bundle_jsnext', 'Grunt plugin to bundle ES6 Modules into a library for Browsers.', function() { var pkg; if (!grunt.file.exists('./package.json')) { grunt.log.warn('package.json not found.'); return false; } else { pkg = require(libpath.resolve('./package.json')); } var config = this.options({ namespace: pkg && pkg.name, main: pkg && pkg["jsnext:main"], namedExport: 'default' }); var resolvers = resolverClasses.map(function(ResolverClass) { return new ResolverClass([libpath.resolve('./')]); }); var container = new Container({ formatter: new FormatterClass(), resolvers: resolvers, basePath: config.basePath, sourceRoot: config.sourceRoot }); var filepath = config.main; if (!filepath) { grunt.fatal('Missing `jsnext:main` value in ' + libpath.resolve('./package.json')); return; } // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return; } try { container.globalDepedency = filepath; container.globalNamespace = config.namespace; container.globalNamedExport = config.namedExport; container.getModule("global-wrapper"); } catch (err) { grunt.fatal('Error converting ES6 modules: ' + err); return; } var dest = (this.data && this.data.dest) || this.data; var destIsFile = libpath.extname(dest) === '.js'; if (!destIsFile) { grunt.fatal('Destination (dest) should be a javascript file instead of "' + dest + '"'); } grunt.file.mkdir(libpath.dirname(dest)); try { container.write(dest); grunt.log.ok('Bundled library written in ' + dest); } catch (err) { grunt.fatal('Error writing bundle in "' + dest + '": ' + err); return; } }); };
function solve([n,k]) { let seq = [1]; for (let current = 1; current < n; current++) { let start = Math.max(0, current - k); let end = current - 1; let sum = 0; for (let i = start; i <= end; i++) { sum += seq[i]; } seq[current] = sum; } console.log(seq.join(' ')); } solve(['6', '3']);
/** @type {import("../../../../").Configuration} */ module.exports = { output: { filename: "[name].mjs", library: { type: "module" } }, target: ["web", "es2020"], experiments: { outputModule: true }, optimization: { minimize: true, runtimeChunk: "single", splitChunks: { cacheGroups: { separate: { test: /separate/, chunks: "all", filename: "separate.mjs", enforce: true } } } }, externals: { "external-self": "./main.mjs" } };
/** * @ngdoc directive * @name refigureApp.directive:mostVisited * @restrict E * @description * Search Results * @example * <collection-row item="refigureObject"></collection-row> */ (function (angular) { 'use strict'; angular .module('refigureShared') .component('collectionRow', { templateUrl: 'view/collectionRow.component.html', controllerAs: 'vm', bindings:{ item: '<' }, controller: Controller }); Controller.$inject = ['$state']; function Controller($state) { var vm = this; vm.$onInit = activate; ////////////////////////////////////// function activate() { vm.currentState = $state.current.name; } } })(window.angular);
export class Contactme { constructor() { this.title = 'Contact Me'; this.description = 'Router is working' this.items = []; this.displayName = "Eddy Ma"; this.photoURL = ""; this.email = "eddy.ma616@gmail.com" } }
const fs = require("fs"); const path = require("path"); const PostModel = require("../models/post_model"); const appDir = path.dirname(require.main.filename); module.exports = { /** Creates a new post document with specified attributes */ create(request, response, next) { const { file, params } = request; const publicPath = "/images/posts/" + file.originalname; const savePath = path.resolve(appDir + "/../public" + publicPath); // Attempt to save the document's image file fs.writeFile(savePath, file.buffer, error => { if (error) { next(error); } const postData = JSON.parse(request.body.post); postData.imgSrc = publicPath; const post = new PostModel(postData); post.save((error) => { if (error) { return next(error); } response.json({post}); }); }); }, /** Deletes a specified document from the posts collection */ destroy(request, response, next) { PostModel.findByIdAndRemove(request.params.post_id, (error, raw) => { if (error) { return next(error); } response.json(raw); } ); }, /** Returns all documents from the posts collection */ list(request, response, next) { PostModel.find( (error, posts) => { response.json({posts}); } ).sort({date: "descending"}); }, /** Returns a specified document from the posts collection */ show(request, response, next) { PostModel.findOne({_id: request.params.post_id}, (error, post) => { response.json({post}); } ); }, /** Updates a specified post document */ update(request, response, next) { const { file, params } = request; const publicPath = "/images/posts/" + file.originalname; const savePath = path.resolve(appDir + "/../public" + publicPath); const post = JSON.parse(request.body.post); const updatePost = () => { const query = {_id: request.params.post_id}; PostModel.updateOne(query, post, (error, raw) => { if (error) { next(error); } PostModel.findOne({_id: request.params.post_id}, (error, post) => { response.json({post}); } ); } ); }; // Do not try to save the image file if it is already exists if(file.originalname === "blob") { updatePost(); } else { // Attempt to save the document's image file fs.writeFile(savePath, file.buffer, error => { if (error) { next(error); } post.imgSrc = publicPath; updatePost(); }); } } };
(function(module) { var homeController = {}; homeController.reveal = function() { $('.hero').slideDown('slow', function() { $('.main-content').fadeIn(500); }); }; module.homeController = homeController; })(window);
import TestUtils from 'react-addons-test-utils' import { bindActionCreators } from 'redux' import { DaveHomeView } from 'views/DaveHomeView' function shallowRender (component) { const renderer = TestUtils.createRenderer() renderer.render(component) return renderer.getRenderOutput() } function renderWithProps (props = {}) { return TestUtils.renderIntoDocument(<DaveHomeView {...props} />) } function shallowRenderWithProps (props = {}) { return shallowRender(<DaveHomeView {...props} />) } describe('(View) Home', function () { let _component, _rendered, _props, _spies beforeEach(function () { _spies = {} _props = { counter: 0, ...bindActionCreators({ doubleAsync: (_spies.doubleAsync = sinon.spy()), increment: (_spies.increment = sinon.spy()) }, _spies.dispatch = sinon.spy()) } _component = shallowRenderWithProps(_props) _rendered = renderWithProps(_props) }) it('Should render as a <div>.', function () { expect(_component.type).to.equal('div') }) it('Should include an <h1> with welcome text.', function () { const h1 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h1') expect(h1).to.exist expect(h1.textContent).to.match(/Welcome to the React Redux Starter Kit/) }) it('Should render with an <h2> that includes Sample Counter text.', function () { const h2 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h2') expect(h2).to.exist expect(h2.textContent).to.match(/Sample Counter/) }) it('Should render props.counter at the end of the sample counter <h2>.', function () { const h2 = TestUtils.findRenderedDOMComponentWithTag( renderWithProps({ ..._props, counter: 5 }), 'h2' ) expect(h2).to.exist expect(h2.textContent).to.match(/5$/) }) describe('An increment button...', function () { let _btn beforeEach(() => { _btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button') .filter(a => /Increment/.test(a.textContent))[0] }) it('should be rendered.', function () { expect(_btn).to.exist }) it('should dispatch an action when clicked.', function () { _spies.dispatch.should.have.not.been.called TestUtils.Simulate.click(_btn) _spies.dispatch.should.have.been.called }) }) describe('A Double (Async) button...', function () { let _btn beforeEach(() => { _btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button') .filter(a => /Double/.test(a.textContent))[0] }) it('should be rendered.', function () { expect(_btn).to.exist }) it('should dispatch an action when clicked.', function () { _spies.dispatch.should.have.not.been.called TestUtils.Simulate.click(_btn) _spies.dispatch.should.have.been.called }) }) })
const webpack = require('webpack'); const path = require('path'); module.exports = { entry: [ // files to run at startup (points are where self-contained scripts go) 'babel-polyfill', './src/main.jsx', './assets/styles/main.scss', './assets/index.html', 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server' ], output: { // where to serve compiled files from publicPath: '/', path: 'dist', filename: 'main.js' }, devtool: 'source-map', // serve the source module: { loaders: [ // list of loaders (where you put things which transform your code) { test: /\.jsx?$/, exclude: /node_modules/, include: path.resolve(__dirname, 'src/'), loaders: ['react-hot', 'babel'] }, { test: /\.html$/, include: path.resolve(__dirname, 'assets/'), loader: 'file-loader?name=[name].[ext]' }, { test: /\.scss$/, include: path.resolve(__dirname, 'assets/styles/'), loader: "style!css!autoprefixer!sass" }, { test: /\.(png|jpg|jpeg|gif|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=8192' }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" } ] }, plugins: [ new webpack.HotModuleReplacementPlugin() ], debug: true, devServer: { contentBase: "./", port: 3000 } };
'user strict'; /** * Module dependencies */ var app = module.exports = require('express').Router(); var formHome = require('shared/home-form'); var jade = require('jade'); var templatePath = require.resolve('./index.jade'); var template = jade.compileFile(templatePath, {'cache': true}); /** * Render */ function render(req, res) { var form = formHome(); var html = template({ 'form': form.toHTML() }); res.header('Content-Type', 'text/html; charset=utf-8'); res.write(html); res.end(); } /** * Routes */ app.get('/', render);
describe("Authentication", function () { beforeEach(() => { cy.app("clean"); }); describe("admin", () => { it("can login", () => { //call a scenario in app_commands/scenarios cy.appScenario("admin"); cy.visit("/users/sign_in"); cy.get('input[type="email"]').type("administrator@mampf.edu"); cy.get('input[type="password"]').type("test123456"); cy.get('input[type="submit"]').click(); cy.url().should("contain", "main/start"); cy.contains("Veranstaltungen").should("exist"); }); }); }); describe("Clicker Admin", function () { beforeEach(() => { cy.app("clean"); cy.appScenario("admin"); cy.visit("/users/sign_in"); cy.get('input[type="email"]').type("administrator@mampf.edu"); cy.get('input[type="password"]').type("test123456"); cy.get('input[type="submit"]').click(); }); it("can create clicker", () => { cy.visit("/administration"); cy.get('a[title="Clicker anlegen"]').click(); cy.get('input[name="clicker[title]"]').type("ErsterClicker"); cy.get("div#new-clicker-area").contains("Speichern").click(); cy.contains("ErsterClicker").should("exist"); }); it("can show clicker qr", () => { cy.appFactories([ ['create', 'clicker', 'with_editor'] ]).then((clickers) => { cy.visit(`/clickers/${clickers[0].id}/edit`); cy.contains("QR-Code zeigen").click(); cy.get("li#clickerQRCode").should("exist"); }); }); });
ngf.declare("sap.sbo.ngf.C", null, [], function() { console.log("C"); return this._super.extend({ info: "C" }); });
/* @flow */ 'use strict' /* :: import type { CLIFlags, CLIOptions } from '../types.js' */ const os = require('os') const displayCors = require('../lib/cors/display.js') const displayRoutes = require('../lib/routes/display.js') const scope = require('../lib/scope.js') const variables = require('../lib/variables.js') const network = require('../lib/network.js') module.exports = function( input /* : Array<string> */, flags /* : CLIFlags */, logger /* : typeof console */, options /* : CLIOptions */ ) /* : Promise<void> */ { const tasks = [ () => scope.display(logger, flags.cwd, flags.env), () => displayCors(logger, flags.cwd), () => displayRoutes(logger, flags.cwd), () => variables.display(logger, flags.cwd, flags.env), () => network.displayNetwork(logger, flags.cwd, flags.env) ] // Catch all errors and let all tasks run before // transforming into a single error const errors = [] return tasks .reduce((prev, task) => { return prev.then(() => task()).catch(error => errors.push(error)) }, Promise.resolve()) .then(() => { if (errors && errors.length) { return Promise.reject( new Error(errors.map(error => error.message).join(os.EOL)) ) } }) }
import React from 'react'; import {compose} from 'recompose'; import withHighcharts from './../withHighcharts'; import withStackedColumn from './withStackedColumn'; import CustomLegend from './../customLegend/customLegend'; const ColumnChart = ({ children, customLegendData, displayHighContrast, }) => { return ( <div> <span className="chart">{children}</span> {customLegendData && customLegendData.length > 0 && <CustomLegend data={customLegendData} displayHighContrast={displayHighContrast} />} </div> ) }; const HighchartifiedStackedColumnChart = compose( withHighcharts, withStackedColumn, )(ColumnChart); export default HighchartifiedStackedColumnChart;
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.UploadCollection. sap.ui.define(['jquery.sap.global', './MessageBox', './Dialog', './library', 'sap/ui/core/Control', 'sap/ui/unified/FileUploaderParameter', "sap/ui/unified/FileUploader", 'sap/ui/core/format/FileSizeFormat', 'sap/m/Link', 'sap/m/OverflowToolbar', './ObjectAttribute', './ObjectStatus', "./UploadCollectionItem", "sap/ui/core/HTML", "./BusyIndicator", "./CustomListItem", "./CustomListItemRenderer", "sap/ui/core/HTMLRenderer", "./LinkRenderer", "./ObjectAttributeRenderer", "./ObjectStatusRenderer", "./TextRenderer", "./DialogRenderer"], function(jQuery, MessageBox, Dialog, Library, Control, FileUploaderParamter, FileUploader, FileSizeFormat, Link, OverflowToolbar, ObjectAttribute, ObjectStatus, UploadCollectionItem, HTML, BusyIndicator, CustomListItem) { "use strict"; /** * Constructor for a new UploadCollection. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * This control allows users to upload single or multiple files from their devices (desktop PC, tablet or phone) and attach them into the application. * @extends sap.ui.core.Control * * @author SAP SE * @version 1.36.6 * * @constructor * @public * @since 1.26 * @alias sap.m.UploadCollection * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var UploadCollection = Control.extend("sap.m.UploadCollection", /** @lends sap.m.UploadCollection.prototype */ { constructor : function(sId, mSettings) { // Delete 'instantUpload' before calling the super constructor to avoid unwanted error logs var bInstantUpload; if (mSettings && mSettings.instantUpload === false) { bInstantUpload = mSettings.instantUpload; delete mSettings.instantUpload; } else if (sId && sId.instantUpload === false) { bInstantUpload = sId.instantUpload; delete sId.instantUpload; } if (mSettings && mSettings.mode === sap.m.ListMode.MultiSelect && bInstantUpload === false){ mSettings.mode = sap.m.ListMode.None; jQuery.sap.log.info("sap.m.ListMode.MultiSelect is not supported by UploadCollection for Upload Pending scenario. Value has been resetted to 'None'"); }else if (sId && sId.mode === sap.m.ListMode.MultiSelect && bInstantUpload === false){ sId.mode = sap.m.ListMode.None; jQuery.sap.log.info("sap.m.ListMode.MultiSelect is not supported by UploadCollection for Upload Pending scenario. Value has been resetted to 'None'"); } try { Control.apply(this, arguments); if (bInstantUpload === false) { this.bInstantUpload = bInstantUpload; this._oFormatDecimal = FileSizeFormat.getInstance({binaryFilesize: false, maxFractionDigits: 1, maxIntegerDigits: 3}); } } catch (e) { this.destroy(); throw e; } }, metadata : { library : "sap.m", properties : { /** * Defines the allowed file types for the upload. * The chosen files will be checked against an array of file types. * If at least one file does not fit the file type requirements, the upload is prevented. Example: ["jpg", "png", "bmp"]. */ fileType : {type : "string[]", group : "Data", defaultValue : null}, /** * Specifies the maximum length of a file name. * If the maximum file name length is exceeded, the corresponding event 'filenameLengthExceed' is triggered. */ maximumFilenameLength : {type : "int", group : "Data", defaultValue : null}, /** * Specifies a file size limit in megabytes that prevents the upload if at least one file exceeds the limit. * This property is not supported by Internet Explorer 8 and 9. */ maximumFileSize : {type : "float", group : "Data", defaultValue : null}, /** * Defines the allowed MIME types of files to be uploaded. * The chosen files will be checked against an array of MIME types. * If at least one file does not fit the MIME type requirements, the upload is prevented. * This property is not supported by Internet Explorer 8 and 9. Example: mimeType ["image/png", "image/jpeg"]. */ mimeType : {type : "string[]", group : "Data", defaultValue : null}, /** * Lets the user select multiple files from the same folder and then upload them. * Internet Explorer 8 and 9 do not support this property. * Please note that the various operating systems for mobile devices can react differently to the property so that fewer upload functions may be available in some cases. */ multiple : {type : "boolean", group : "Behavior", defaultValue : false}, /** * Allows you to set your own text for the 'No data' label. */ noDataText : {type : "string", group : "Behavior", defaultValue : null}, /** * Allows the user to use the same name for a file when editing the file name. 'Same name' refers to an already existing file name in the list. */ sameFilenameAllowed : {type : "boolean", group : "Behavior", defaultValue : false}, /** * Defines whether separators are shown between list items. */ showSeparators : {type : "sap.m.ListSeparators", group : "Appearance", defaultValue : sap.m.ListSeparators.All}, /** * Enables the upload of a file. */ uploadEnabled : {type : "boolean", group : "Behavior", defaultValue : true}, /** * Specifies the URL where the uploaded files have to be stored. */ uploadUrl : {type : "string", group : "Data", defaultValue : "../../../upload"}, /** * If false, no upload is triggered when a file is selected. In addition, if a file was selected, a new FileUploader instance is created to ensure that multiple files from multiple folders can be chosen. * @since 1.30 */ instantUpload : {type : "boolean", group : "Behavior", defaultValue : true}, /** * Sets the title text in the toolbar of the list of attachments. * To show as well the number of attachments in brackets like the default text does. The number of attachments could be retrieved via "getItems().length". * If a new title is set, the default is deactivated. * The default value is set to language-dependent "Attachments (n)". * @since 1.30 */ numberOfAttachmentsText : {type : "string" , group : "Appearance", defaultValue : null}, /** * Defines the selection mode of the control (e.g. None, SingleSelect, MultiSelect, SingleSelectLeft, SingleSelectMaster). * Since the UploadCollection reacts like a list for attachments, the API is close to the ListBase Interface. * sap.m.ListMode.Delete mode is not supported and will be automatically set to sap.m.ListMode.None. * In addition, if instant upload is set to false the mode sap.m.ListMode.MultiSelect is not supported and will be automatically set to sap.m.ListMode.None. * * @since 1.34 */ mode: {type : "sap.m.ListMode", group : "Behavior", defaultValue : "None"} }, defaultAggregation : "items", aggregations : { /** * Uploaded items. */ items : {type : "sap.m.UploadCollectionItem", multiple : true, singularName : "item"}, /** * Specifies the header parameters for the FileUploader that are submitted only with XHR requests. * Header parameters are not supported by Internet Explorer 8 and 9. */ headerParameters : {type : "sap.m.UploadCollectionParameter", multiple : true, singularName : "headerParameter"}, /** * Specifies the parameters for the FileUploader that are rendered as a hidden input field. */ parameters : {type : "sap.m.UploadCollectionParameter", multiple : true, singularName : "parameter"}, /** * Specifies the toolbar. * @since 1.34 */ toolbar : {type: "sap.m.OverflowToolbar", multiple : false}, /** * Internal aggregation to hold the list in controls tree. * @since 1.34 */ _list : { type : "sap.m.List", multiple : false, visibility : "hidden" } }, events : { /** * The event is triggered when files are selected in the FileUploader dialog. Applications can set parameters and headerParameters which will be dispatched to the embedded FileUploader control. * Limitation: parameters and headerParameters are not supported by Internet Explorer 9. */ change : { parameters : { /** * An unique Id of the attached document. * This parameter is deprecated since version 1.28.0, use parameter files instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter files instead. */ documentId : {type : "string"}, /** * A FileList of individually selected files from the underlying system. See www.w3.org for the FileList Interface definition. * Limitation: Internet Explorer 9 supports only single file with property file.name. * Since version 1.28.0. */ files : {type : "object[]"} } }, /** * The event is triggered when an uploaded attachment is selected and the Delete button is pressed. */ fileDeleted : { parameters : { /** * An unique Id of the attached document. * This parameter is deprecated since version 1.28.0, use parameter item instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter item instead. */ documentId : {type : "string"}, /** * An item to be deleted from the collection. * Since version 1.28.0. */ item : {type : "sap.m.UploadCollectionItem"} } }, /** * The event is triggered when the name of a chosen file is longer than the value specified with the maximumFilenameLength property (only if provided by the application). */ filenameLengthExceed : { parameters : { /** * An unique Id of the attached document. * This parameter is deprecated since version 1.28.0, use parameter files instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter files instead. */ documentId : {type : "string"}, /** * A FileList of individually selected files from the underlying system. * Limitation: Internet Explorer 9 supports only single file with property file.name. * Since version 1.28.0. */ files : {type : "object[]"} } }, /** * The event is triggered when the file name is changed. */ fileRenamed : { parameters : { /** * An unique Id of the attached document. * This parameter is deprecated since version 1.28.0, use parameter item instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter item instead. */ documentId : {type : "string"}, /** * The new file name. * This parameter is deprecated since version 1.28.0, use parameter item instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter item instead. */ fileName : {type : "string"}, /** * The renamed UI element as a UploadCollectionItem. * Since version 1.28.0. */ item : {type : "sap.m.UploadCollectionItem"} } }, /** * The event is triggered when the file size of an uploaded file is exceeded (only if the maxFileSize property was provided by the application). * This event is not supported by Internet Explorer 9. */ fileSizeExceed : { parameters : { /** * An unique Id of the attached document. * This parameter is deprecated since version 1.28.0, use parameter files instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter files instead. */ documentId : {type : "string"}, /** * The size in MB of a file to be uploaded. * This parameter is deprecated since version 1.28.0, use parameter files instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter files instead. */ fileSize : {type : "string"}, /** * A FileList of individually selected files from the underlying system. * Limitation: Internet Explorer 9 supports only single file with property file.name. * Since version 1.28.0. */ files : {type : "object[]"} } }, /** * The event is triggered when the file type or the MIME type don't match the permitted types (only if the fileType property or the mimeType property are provided by the application). */ typeMissmatch : { parameters : { /** * An unique Id of the attached document. * This parameter is deprecated since version 1.28.0, use parameter files instead. * @deprecated Since version 1.28.0. Use parameter files instead. */ documentId : {type : "string"}, /** * File type. * This parameter is deprecated since version 1.28.0, use parameter files instead. * @deprecated Since version 1.28.0. Use parameter files instead. */ fileType : {type : "string"}, /** * MIME type. *This parameter is deprecated since version 1.28.0, use parameter files instead. * @deprecated Since version 1.28.0. Use parameter files instead. */ mimeType : {type : "string"}, /** * A FileList of individually selected files from the underlying system. * Limitation: Internet Explorer 9 supports only single file. * Since version 1.28.0. */ files : {type : "object[]"} } }, /** * The event is triggered as soon as the upload request is completed. */ uploadComplete : { parameters : { /** * Ready state XHR. This parameter is deprecated since version 1.28.0., use parameter files instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter files instead. */ readyStateXHR : {type : "string"}, /** * Response of the completed upload request. This parameter is deprecated since version 1.28.0., use parameter files instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter files instead. */ response : {type : "string"}, /** * Status Code of the completed upload event. This parameter is deprecated since version 1.28.0., use parameter files instead. * @deprecated Since version 1.28.0. This parameter is deprecated, use parameter files instead. */ status : {type : "string"}, /** * A list of uploaded files. Each entry contains the following members. * fileName : The name of a file to be uploaded. * response : Response message which comes from the server. On the server side, this response has to be put within the 'body' tags of the response document of the iFrame. It can consist of a return code and an optional message. This does not work in cross-domain scenarios. * responseRaw : HTTP-Response which comes from the server. This property is not supported by Internet Explorer Versions lower than 9. * status : Status of the XHR request. This property is not supported by Internet Explorer 9 and lower. * headers : HTTP-Response-Headers which come from the server. Provided as a JSON-map, i.e. each header-field is reflected by a property in the header-object, with the property value reflecting the header-field's content. This property is not supported by Internet Explorer 9 and lower. * Since version 1.28.0. */ files : {type : "object[]"} } }, /** * The event is triggered as soon as the upload request was terminated by the user. */ uploadTerminated : { parameters: { /** * Specifies the name of the file of which the upload is to be terminated. */ fileName: {type : "string"}, /** * This callback function returns the corresponding header parameter (type sap.m.UploadCollectionParameter) if available. */ getHeaderParameter: {type : "function", parameters: { /** * The (optional) name of the header parameter. If no parameter is provided all header parameters are returned. */ headerParameterName: {type : "string"} } } } }, /** * The event is triggered before the actual upload starts. An event is fired per file. All the necessary header parameters should be set here. */ beforeUploadStarts : { parameters: { /** * Specifies the name of the file to be uploaded. */ fileName: {type : "string"}, /** * Adds a header parameter to the file that will be uploaded. */ addHeaderParameter: {type : "function", parameters: { /** * Specifies a header parameter that will be added */ headerParameter: {type : "sap.m.UploadCollectionParameter"} } }, /** * Returns the corresponding header parameter (type sap.m.UploadCollectionParameter) if available. */ getHeaderParameter: {type : "function", parameters: { /** * The (optional) name of the header parameter. If no parameter is provided all header parameters are returned. */ headerParameterName: {type : "string"} } } } }, /** * Fires when selection is changed via user interaction inside the control. * @since 1.36.0 */ selectionChange : { parameters : { /** * The item whose selection has changed. In <code>MultiSelect</code> mode, only the selected item upmost is returned. This parameter can be used for single-selection modes. */ selectedItem : {type : "sap.m.UploadCollectionItem"}, /** * Array of items whose selection has changed. This parameter can be used for <code>MultiSelect</code> mode. */ selectedItems : {type : "sap.m.UploadCollectionItem[]"}, /** * Indicates whether the <code>listItem</code> parameter is selected or not. */ selected : {type : "boolean"} } } } }}); UploadCollection._uploadingStatus = "uploading"; UploadCollection._displayStatus = "display"; UploadCollection._toBeDeletedStatus = "toBeDeleted"; UploadCollection._pendingUploadStatus = "pendingUploadStatus"; // UploadCollectionItem has this status only if UploadCollection is used with the property 'instantUpload' = false UploadCollection._placeholderCamera = 'sap-icon://camera'; /** * @description This file defines behavior for the control * @private */ UploadCollection.prototype.init = function() { UploadCollection.prototype._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m"); this._headerParamConst = { requestIdName : "requestId" + jQuery.now(), fileNameRequestIdName : "fileNameRequestId" + jQuery.now() }; this._requestIdValue = 0; this._iFUCounter = 0; // it is necessary to count FileUploader instances in case of 'instantUpload' = false this._oList = new sap.m.List(this.getId() + "-list"); this.setAggregation("_list", this._oList, true); this._oList.addStyleClass("sapMUCList"); this._cAddItems = 0; this._iUploadStartCallCounter = 0; this.aItems = []; this._aDeletedItemForPendingUpload = []; this._aFileUploadersForPendingUpload = []; this._iFileUploaderPH = null; // Index of the place holder for the File Uploader this._oListEventDelegate = null; }; /* =========================================================== */ /* Redefinition of setter and getter methods */ /* =========================================================== */ UploadCollection.prototype.setFileType = function(aFileTypes) { if (!aFileTypes) { return this; } if (!this.getInstantUpload()) { jQuery.sap.log.info("As property instantUpload is false it is not allowed to change fileType at runtime."); } else { var cLength = aFileTypes.length; for (var i = 0; i < cLength; i++) { aFileTypes[i] = aFileTypes[i].toLowerCase(); } this.setProperty("fileType", aFileTypes); if (this._getFileUploader().getFileType() !== aFileTypes) { this._getFileUploader().setFileType(aFileTypes); } } return this; }; UploadCollection.prototype.setMaximumFilenameLength = function(iMaximumFilenameLength) { if (!this.getInstantUpload()) { jQuery.sap.log.info("As property instantUpload is false it is not allowed to change maximumFilenameLength at runtime."); } else { this.setProperty("maximumFilenameLength", iMaximumFilenameLength, true); if (this._getFileUploader().getMaximumFilenameLength() !== iMaximumFilenameLength) { this._getFileUploader().setMaximumFilenameLength(iMaximumFilenameLength); } } return this; }; UploadCollection.prototype.setMaximumFileSize = function(iMaximumFileSize) { if (!this.getInstantUpload()) { jQuery.sap.log.info("As property instantUpload is false it is not allowed to change maximumFileSize at runtime."); } else { this.setProperty("maximumFileSize", iMaximumFileSize, true); if (this._getFileUploader().getMaximumFileSize() !== iMaximumFileSize) { this._getFileUploader().setMaximumFileSize(iMaximumFileSize); } } return this; }; UploadCollection.prototype.setMimeType = function(aMimeTypes) { if (!this.getInstantUpload()) { jQuery.sap.log.info("As property instantUpload is false it is not allowed to change mimeType at runtime."); } else { this.setProperty("mimeType", aMimeTypes); if (this._getFileUploader().getMimeType() !== aMimeTypes) { this._getFileUploader().setMimeType(aMimeTypes); } return this; } }; UploadCollection.prototype.setMultiple = function(bMultiple) { if (!this.getInstantUpload()) { jQuery.sap.log.info("As property instantUpload is false it is not allowed to change multiple at runtime."); } else { this.setProperty("multiple", bMultiple); if (this._getFileUploader().getMultiple() !== bMultiple) { this._getFileUploader().setMultiple(bMultiple); } return this; } }; UploadCollection.prototype.setNoDataText = function(sNoDataText) { this.setProperty("noDataText", sNoDataText); if (this._oList.getNoDataText() !== sNoDataText) { this._oList.setNoDataText(sNoDataText); } return this; }; UploadCollection.prototype.setShowSeparators = function(bShowSeparators) { this.setProperty("showSeparators", bShowSeparators); if (this._oList.getShowSeparators() !== bShowSeparators) { this._oList.setShowSeparators(bShowSeparators); } return this; }; UploadCollection.prototype.setUploadEnabled = function(bUploadEnabled) { if (!this.getInstantUpload()) { jQuery.sap.log.info("As property instantUpload is false it is not allowed to change uploadEnabled at runtime."); } else { this.setProperty("uploadEnabled", bUploadEnabled); if (this._getFileUploader().getEnabled() !== bUploadEnabled) { this._getFileUploader().setEnabled(bUploadEnabled); } } return this; }; UploadCollection.prototype.setUploadUrl = function(sUploadUrl) { if (!this.getInstantUpload()) { jQuery.sap.log.info("As property instantUpload is false it is not allowed to change uploadUrl at runtime."); } else { this.setProperty("uploadUrl", sUploadUrl); if (this._getFileUploader().getUploadUrl() !== sUploadUrl) { this._getFileUploader().setUploadUrl(sUploadUrl); } } return this; }; UploadCollection.prototype.setInstantUpload = function() { jQuery.sap.log.error("It is not supported to change the behavior at runtime."); return this; }; UploadCollection.prototype.setMode = function(mode) { if (mode === sap.m.ListMode.Delete) { this._oList.setMode(sap.m.ListMode.None); jQuery.sap.log.info("sap.m.ListMode.Delete is not supported by UploadCollection. Value has been resetted to 'None'"); }else if (mode === sap.m.ListMode.MultiSelect && !this.getInstantUpload()) { this._oList.setMode(sap.m.ListMode.None); jQuery.sap.log.info("sap.m.ListMode.MultiSelect is not supported by UploadCollection for Pending Upload. Value has been resetted to 'None'"); }else { this._oList.setMode(mode); } }; UploadCollection.prototype.getMode = function() { return this._oList.getMode(); }; UploadCollection.prototype.getToolbar = function(){ return this._oHeaderToolbar; }; /* =========================================================== */ /* API methods */ /* =========================================================== */ /** * @description Starts the upload for all selected files. * @type {void} * @public * @since 1.30 */ UploadCollection.prototype.upload = function() { if (this.getInstantUpload()) { jQuery.sap.log.error("Not a valid API call. 'instantUpload' should be set to 'false'."); } var iFileUploadersCounter = this._aFileUploadersForPendingUpload.length; for (var i = 0; i < iFileUploadersCounter; i++) { this._iUploadStartCallCounter = 0; this._aFileUploadersForPendingUpload[i].upload(); } }; /** * @description Returns an array containing the selected UploadCollectionItems. * @returns {sap.m.UploadCollectionItem[]} array with selected items * @public * @since 1.34 */ UploadCollection.prototype.getSelectedItems = function() { var aSelectedListItems = this._oList.getSelectedItems(); return this._getUploadCollectionItemsByListItems(aSelectedListItems); }; /** * @description Returns selected UploadCollectionItem. * @returns {sap.m.UploadCollectionItem} selected item * @since 1.34 * @public */ UploadCollection.prototype.getSelectedItem = function() { var oSelectedListItem = this._oList.getSelectedItem(); if (oSelectedListItem) { return this._getUploadCollectionItemByListItem(oSelectedListItem); } }; /** * @description Sets a UploadCollectionItem to be selected by id. In single mode, the method removes the previous selection. * @param {string} id The id of the item whose selection to be changed. * @param {boolean} select Sets selected status of the item. Default value is true. * @returns {sap.m.UploadCollection} The current UploadCollection * @since 1.34 * @public */ UploadCollection.prototype.setSelectedItemById = function(id, select) { this._oList.setSelectedItemById(id + "-cli", select); this._setSelectedForItems([this._getUploadCollectionItemById(id)], select); return this; }; /** * @description Selects or deselects the given list item. * @param {sap.m.UploadCollectionItem} uploadCollectionItem The item whose selection to be changed. This parameter is mandatory. * @param {boolean} select Sets selected status of the item. Default value is true. * @returns {sap.m.UploadCollection} The current UploadCollection * @since 1.34 * @public */ UploadCollection.prototype.setSelectedItem = function(uploadCollectionItem, select) { this.setSelectedItemById(uploadCollectionItem.getId(), select); return this; }; /** * @description Select all items in "MultiSelection" mode. * @returns {sap.m.UploadCollection} The current UploadCollection * @since 1.34 * @public */ UploadCollection.prototype.selectAll = function() { var aSelectedList = this._oList.selectAll(); if (aSelectedList.getItems().length !== this.getItems().length) { jQuery.sap.log.info("Internal 'List' and external 'UploadCollection' are not in sync."); } this._setSelectedForItems(this.getItems(), true); return this; }; /** * Downloads the given item. * This function delegates to {sap.m.UploadCollectionItem.download}. * @param {sap.m.UploadCollectionItem} uploadCollectionItem The item to download. This parameter is mandatory. * @param {boolean} askForLocation Decides whether to ask for a location to download or not. * @returns {boolean} True if the download has started successfully. False if the download couldn't be started. * @since 1.36.0 * @public */ UploadCollection.prototype.downloadItem = function(uploadCollectionItem, askForLocation) { if (!this.getInstantUpload()) { jQuery.sap.log.info("Download is not possible on Pending Upload mode"); return false; } else { return uploadCollectionItem.download(askForLocation); } }; UploadCollection.prototype.removeAggregation = function(sAggregationName, vObject, bSuppressInvalidate) { if (!this.getInstantUpload() && sAggregationName === "items" && vObject) { this._aDeletedItemForPendingUpload.push(vObject); } if (Control.prototype.removeAggregation) { return Control.prototype.removeAggregation.apply(this, arguments); } }; UploadCollection.prototype.removeAllAggregation = function(sAggregationName, bSuppressInvalidate) { if (!this.getInstantUpload() && sAggregationName === "items") { if (this._aFileUploadersForPendingUpload) { for (var i = 0; i < this._aFileUploadersForPendingUpload.length; i++) { this._aFileUploadersForPendingUpload[i].destroy(); this._aFileUploadersForPendingUpload[i] = null; } this._aFileUploadersForPendingUpload = []; } } if (Control.prototype.removeAllAggregation) { return Control.prototype.removeAllAggregation.apply(this, arguments); } }; /* =========================================================== */ /* Lifecycle methods */ /* =========================================================== */ /** * @description Required adaptations before rendering. * @private */ UploadCollection.prototype.onBeforeRendering = function() { this._RenderManager = this._RenderManager || sap.ui.getCore().createRenderManager(); var i, cAitems; if (this._oListEventDelegate) { this._oList.removeEventDelegate(this._oListEventDelegate); this._oListEventDelegate = null; } checkInstantUpload.bind(this)(); if (!this.getInstantUpload()) { this.aItems = this.getItems(); this._getListHeader(this.aItems.length); this._clearList(); this._fillList(this.aItems); this._oList.setHeaderToolbar(this._oHeaderToolbar); return; } if (this.aItems.length > 0) { cAitems = this.aItems.length; // collect items with the status "uploading" var aUploadingItems = []; for (i = 0; i < cAitems; i++) { if (this.aItems[i] && this.aItems[i]._status === UploadCollection._uploadingStatus && this.aItems[i]._percentUploaded !== 100) { aUploadingItems.push(this.aItems[i]); } else if (this.aItems[i] && this.aItems[i]._status !== UploadCollection._uploadingStatus && this.aItems[i]._percentUploaded === 100 && this.getItems().length === 0) { // Skip this rendering because of model refresh only aUploadingItems.push(this.aItems[i]); } } if (aUploadingItems.length === 0) { this.aItems = []; this.aItems = this.getItems(); } } else { // this.aItems is empty this.aItems = this.getItems(); } //prepare the list with list items this._getListHeader(this.aItems.length); this._clearList(); this._fillList(this.aItems); this._oList.setAggregation("headerToolbar", this._oHeaderToolbar, true); // note: suppress re-rendering // FileUploader does not support parallel uploads in IE9 if ((sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9) && this.aItems.length > 0 && this.aItems[0]._status === UploadCollection._uploadingStatus) { this._oFileUploader.setEnabled(false); } else { // enable/disable FileUploader according to error state if (this.sErrorState !== "Error") { if (this.getUploadEnabled() !== this._oFileUploader.getEnabled()) { this._oFileUploader.setEnabled(this.getUploadEnabled()); } } else { this._oFileUploader.setEnabled(false); } } if (this.sDeletedItemId){ jQuery(document.activeElement).blur(); } // This function checks if instantUpload needs to be set. In case of the properties like fileType are set by the // model instead of the constructor, the setting happens later and is still valid. To support this as well, you // need to wait for modification until the first rendering. function checkInstantUpload () { if (this.bInstantUpload === false) { this.setProperty("instantUpload", this.bInstantUpload, true); delete this.bInstantUpload; } } }; /** * @description Required adaptations after rendering. * @private */ UploadCollection.prototype.onAfterRendering = function() { var that = this; if (this.getInstantUpload()) { if (this.aItems || (this.aItems === this.getItems())) { if (this.editModeItem) { var $oEditBox = jQuery.sap.byId(this.editModeItem + "-ta_editFileName-inner"); if ($oEditBox) { var sId = this.editModeItem; if (!sap.ui.Device.os.ios) { $oEditBox.focus(function() { $oEditBox.selectText(0, $oEditBox.val().length); }); } $oEditBox.focus(); this._oListEventDelegate = { onclick: function(oEvent) { sap.m.UploadCollection.prototype._handleClick(oEvent, that, sId); } }; this._oList.addDelegate(this._oListEventDelegate); } } else if (this.sFocusId) { //set focus on line item after status = Edit sap.m.UploadCollection.prototype._setFocus2LineItem(this.sFocusId); this.sFocusId = null; } else if (this.sDeletedItemId) { //set focus on line item after an item was deleted sap.m.UploadCollection.prototype._setFocusAfterDeletion(this.sDeletedItemId, that); } } } else { if (this.sFocusId) { //set focus after removal of file from upload list sap.m.UploadCollection.prototype._setFocus2LineItem(this.sFocusId); this.sFocusId = null; } } }; /** * @description Cleans up before destruction. * @private */ UploadCollection.prototype.exit = function() { var i, iPendingUploadsNumber; if (this._oFileUploader) { this._oFileUploader.destroy(); this._oFileUploader = null; } if (this._oHeaderToolbar) { this._oHeaderToolbar.destroy(); this._oHeaderToolbar = null; } if (this._oNumberOfAttachmentsTitle) { this._oNumberOfAttachmentsTitle.destroy(); this._oNumberOfAttachmentsTitle = null; } if (this._RenderManager) { this._RenderManager.destroy(); } if (this._aFileUploadersForPendingUpload) { iPendingUploadsNumber = this._aFileUploadersForPendingUpload.length; for (i = 0; i < iPendingUploadsNumber; i++) { this._aFileUploadersForPendingUpload[i].destroy(); this._aFileUploadersForPendingUpload[i] = null; } this._aFileUploadersForPendingUpload = null; } }; /* =========================================================== */ /* Private methods */ /* =========================================================== */ /** * @description Hides FileUploader instance after OverflowToolbar is rendered. * @private */ UploadCollection.prototype._hideFileUploaders = function () { var iToolbarElements, i; if (!this.getInstantUpload()) { iToolbarElements = this._oHeaderToolbar.getContent().length; if (this._aFileUploadersForPendingUpload.length) { for (i = 0; i < iToolbarElements; i++) { // Only the newest instance of FileUploader is useful, which will be in the place holder position. // Other ones can be hidden. if (this._oHeaderToolbar.getContent()[i] instanceof sap.ui.unified.FileUploader && i !== this._iFileUploaderPH){ this._oHeaderToolbar.getContent()[i].$().hide(); } } } return; } }; /** * @description Creates or gets a Toolbar * @param {int} iItemNumber Number of items in the list * @private */ UploadCollection.prototype._getListHeader = function(iItemNumber) { var oFileUploader, i; this._setNumberOfAttachmentsTitle(iItemNumber); if (!this._oHeaderToolbar) { if (!!this._oFileUploader && !this.getInstantUpload()) { this._oFileUploader.destroy(); } oFileUploader = this._getFileUploader(); this._oHeaderToolbar = this.getAggregation("toolbar"); if (!this._oHeaderToolbar){ this._oHeaderToolbar = new sap.m.OverflowToolbar(this.getId() + "-toolbar", { content : [this._oNumberOfAttachmentsTitle, new sap.m.ToolbarSpacer(), oFileUploader] }).addEventDelegate({ onAfterRendering : this._hideFileUploaders }, this); this._iFileUploaderPH = 2; } else { this._oHeaderToolbar.addEventDelegate({ onAfterRendering : this._hideFileUploaders }, this); this._iFileUploaderPH = this._getFileUploaderPlaceHolderPosition(this._oHeaderToolbar); if (this._oHeaderToolbar && this._iFileUploaderPH > -1) { this._setFileUploaderInToolbar(oFileUploader); } else { jQuery.sap.log.info("A place holder of type 'sap.m.UploadCollectionPlaceholder' needs to be provided."); } } } else if (!this.getInstantUpload()) { //create a new FU Instance only if the current FU instance has been used for selection of a file for the future upload. //If the method is called after an item has been deleted from the list there is no need to create a new FU instance. var iPendingUploadsNumber = this._aFileUploadersForPendingUpload.length; for (i = iPendingUploadsNumber - 1; i >= 0; i--) { if (this._aFileUploadersForPendingUpload[i].getId() == this._oFileUploader.getId()) { oFileUploader = this._getFileUploader(); this._oHeaderToolbar.insertAggregation("content", oFileUploader, this._iFileUploaderPH, true); break; } } } }; /** * @description Gives the position of the place holder for the FileUploader that every toolbar provided * by the application must have * @param {sap.m.OverflowToolbar} oToolbar Toolbar where to find the place holder * @return {int} The position of the place holder or -1 if there's no place holder. * @private */ UploadCollection.prototype._getFileUploaderPlaceHolderPosition = function(oToolbar){ for (var i = 0; i < oToolbar.getContent().length; i++) { if (oToolbar.getContent()[i] instanceof sap.m.UploadCollectionToolbarPlaceholder){ return i; } } return -1; }; /** * @description Sets the given FileUploader object in to the current Toolbar on the position where the place holder is * @param {sap.ui.unified.FileUploader} oFileUploader The FileUploader object to set in the Toolbar * @private */ UploadCollection.prototype._setFileUploaderInToolbar = function(oFileUploader){ this._oHeaderToolbar.getContent()[this._iFileUploaderPH].setVisible(false); this._oHeaderToolbar.insertContent(oFileUploader, this._iFileUploaderPH); }; /** * @description Map an item to the list item. * @param {sap.ui.core.Item} oItem Base information to generate the list items * @returns {sap.m.CustomListItem | null} oListItem List item which will be displayed * @private */ UploadCollection.prototype._mapItemToListItem = function(oItem) { if (!oItem) { return null; } var sItemId, sStatus, sFileNameLong, oBusyIndicator, oListItem, sContainerId, $container, oContainer, oItemIcon, that = this; sItemId = oItem.getId(); sStatus = oItem._status; sFileNameLong = oItem.getFileName(); if (sStatus === UploadCollection._uploadingStatus) { oBusyIndicator = new sap.m.BusyIndicator(sItemId + "-ia_indicator", { visible: true }).addStyleClass("sapMUCloadingIcon"); } else { oItemIcon = this._createIcon(oItem, sItemId, sFileNameLong, that); } sContainerId = sItemId + "-container"; // UploadCollection has to destroy the container as sap.ui.core.HTML is preserved by default which leads to problems at rerendering $container = jQuery.sap.byId(sContainerId); if (!!$container) { $container.remove(); $container = null; } oContainer = new sap.ui.core.HTML({content : // a container for a text container and a button container "<span id=" + sContainerId + " class= sapMUCTextButtonContainer> </span>", afterRendering : function() { that._renderContent(oItem, sContainerId, that); } }); oListItem = new sap.m.CustomListItem(sItemId + "-cli", { content : [oBusyIndicator, oItemIcon, oContainer], selected : oItem.getSelected() }); oListItem._status = sStatus; oListItem.addStyleClass("sapMUCItem"); return oListItem; }; /** * @description Renders fileName, attributes, statuses and buttons(except for IE9) into the oContainer. Later it should be moved to the UploadCollectionItemRenderer. * @param {sap.ui.core.Item} oItem Base information to generate the list items * @param {string} sContainerId ID of the container where the content will be rendered to * @param {object} that Context * @private */ UploadCollection.prototype._renderContent = function(oItem, sContainerId, that) { var sItemId, i, iAttrCounter, iStatusesCounter, sPercentUploaded, aAttributes, aStatuses, oRm, sStatus; sPercentUploaded = oItem._percentUploaded; aAttributes = oItem.getAllAttributes(); aStatuses = oItem.getStatuses(); sItemId = oItem.getId(); iAttrCounter = aAttributes.length; iStatusesCounter = aStatuses.length; sStatus = oItem._status; oRm = that._RenderManager; oRm.write('<div class="sapMUCTextContainer '); // text container for fileName, attributes and statuses if (sStatus === "Edit") { oRm.write('sapMUCEditMode '); } oRm.write('" >'); oRm.renderControl(this._getFileNameControl(oItem, that)); // if status is uploading only the progress label is displayed under the Filename if (sStatus === UploadCollection._uploadingStatus && !(sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9)) { oRm.renderControl(this._createProgressLabel(sItemId, sPercentUploaded)); } else { if (iAttrCounter > 0) { oRm.write('<div class="sapMUCAttrContainer">'); // begin of attributes container for (i = 0; i < iAttrCounter; i++ ) { aAttributes[i].addStyleClass("sapMUCAttr"); oRm.renderControl(aAttributes[i]); if ((i + 1) < iAttrCounter) { oRm.write('<div class="sapMUCSeparator">&nbsp&#x00B7&#160</div>'); // separator between attributes } } oRm.write('</div>'); // end of attributes container } if (iStatusesCounter > 0) { oRm.write('<div class="sapMUCStatusContainer">'); // begin of statuses container for (i = 0; i < iStatusesCounter; i++ ) { aStatuses[i].detachBrowserEvent("hover"); oRm.renderControl(aStatuses[i]); if ((i + 1) < iStatusesCounter){ oRm.write('<div class="sapMUCSeparator">&nbsp&#x00B7&#160</div>'); // separator between statuses } } oRm.write('</div>'); // end of statuses container } } oRm.write('</div>'); // end of container for Filename, attributes and statuses this._renderButtons(oRm, oItem, sStatus, sItemId, that); oRm.flush(jQuery.sap.byId(sContainerId)[0], true); // after removal to UploadCollectionItemRenderer delete this line }; /** * @description Renders buttons of the item in scope. * @param {object} oRm Render manager * @param {sap.ui.core.Item} oItem Item in scope * @param {string} sStatus Internal status of the item in scope * @param {string} sItemId ID of the container where the content will be rendered to * @param {object} that Context * @private */ UploadCollection.prototype._renderButtons = function(oRm, oItem, sStatus, sItemId, that) { var aButtons, iButtonCounter; aButtons = this._getButtons(oItem, sStatus, sItemId, that); if (!!aButtons) { // is necessary for IE9 iButtonCounter = aButtons.length; } // render div container only if there is at least one button if (iButtonCounter > 0) { oRm.write('<div class="sapMUCButtonContainer">'); //begin of div for buttons for (var i = 0; i < iButtonCounter; i++ ) { if ((i + 1) < iButtonCounter) { // if both buttons are displayed aButtons[i].addStyleClass("sapMUCFirstButton"); } oRm.renderControl(aButtons[i]); } oRm.write('</div>'); // end of div for buttons } }; /** * @description Gets a file name which is a sap.m.Link in display mode and a sap.m.Input with a description (file extension) in edit mode * @param {sap.ui.core.Item} oItem Base information to generate the list items * @param {object} that Context * @return {sap.m.Link | sap.m.Input} oFileName is a file name of sap.m.Link type in display mode and sap.m.Input type in edit mode * @private */ UploadCollection.prototype._getFileNameControl = function(oItem, that) { var bEnabled, oFileName, oFile, sFileName, sFileNameLong, sItemId, sStatus, iMaxLength, sValueState, bShowValueStateMessage, oFileNameEditBox, sValueStateText; sFileNameLong = oItem.getFileName(); sItemId = oItem.getId(); sStatus = oItem._status; if (sStatus !== "Edit") { bEnabled = true; if (this.sErrorState === "Error" || !jQuery.trim(oItem.getUrl())) { bEnabled = false; } oFileName = sap.ui.getCore().byId(sItemId + "-ta_filenameHL"); if (!oFileName) { oFileName = new sap.m.Link(sItemId + "-ta_filenameHL", { enabled : bEnabled, press : function(oEvent) { this._triggerLink(oEvent, that); }.bind(this) }).addStyleClass("sapMUCFileName"); oFileName.setModel(oItem.getModel()); oFileName.setText(sFileNameLong); } else { oFileName.setModel(oItem.getModel()); oFileName.setText(sFileNameLong); oFileName.setEnabled(bEnabled); } return oFileName; } else { oFile = that._splitFilename(sFileNameLong); iMaxLength = that.getMaximumFilenameLength(); sValueState = "None"; bShowValueStateMessage = false; sFileName = oFile.name; if (oItem.errorState === "Error") { bShowValueStateMessage = true; sValueState = "Error"; sFileName = oItem.changedFileName; if (sFileName.length === 0) { sValueStateText = this._oRb.getText("UPLOADCOLLECTION_TYPE_FILENAME"); } else { sValueStateText = this._oRb.getText("UPLOADCOLLECTION_EXISTS"); } } oFileNameEditBox = sap.ui.getCore().byId(sItemId + "-ta_editFileName"); if (!oFileNameEditBox) { oFileNameEditBox = new sap.m.Input(sItemId + "-ta_editFileName", { type : sap.m.InputType.Text, fieldWidth: "75%", valueState : sValueState, valueStateText : sValueStateText, showValueStateMessage: bShowValueStateMessage, description: oFile.extension }).addStyleClass("sapMUCEditBox"); oFileNameEditBox.setModel(oItem.getModel()); oFileNameEditBox.setValue(sFileName); } else { oFileNameEditBox.setModel(oItem.getModel()); oFileNameEditBox.setValueState(sValueState); oFileNameEditBox.setFieldWidth("75%"); oFileNameEditBox.setValueStateText(sValueStateText); oFileNameEditBox.setValue(sFileName); oFileNameEditBox.setDescription(oFile.extension); oFileNameEditBox.setShowValueStateMessage(bShowValueStateMessage); } if ((iMaxLength - oFile.extension.length) > 0) { oFileNameEditBox.setProperty("maxLength", iMaxLength - oFile.extension.length, true); } return oFileNameEditBox; } }; /** * @description Creates a label for upload progress * @param {string} sItemId ID of the item being processed * @param {string} sPercentUploaded per cent having been uploaded * @return {sap.m.Label} oProgressLabel * @private */ UploadCollection.prototype._createProgressLabel = function(sItemId, sPercentUploaded) { var oProgressLabel; oProgressLabel = sap.ui.getCore().byId(sItemId + "-ta_progress"); if (!oProgressLabel) { oProgressLabel = new sap.m.Label(sItemId + "-ta_progress", { text : this._oRb.getText("UPLOADCOLLECTION_UPLOADING", [sPercentUploaded]) }).addStyleClass("sapMUCProgress"); } else { oProgressLabel.setText(this._oRb.getText("UPLOADCOLLECTION_UPLOADING", [sPercentUploaded])); } return oProgressLabel; }; /** * @description Creates an icon or image * @param {sap.ui.core.Item} oItem Base information to generate the list items * @param {string} sItemId ID of the item being processed * @param {string} sFileNameLong file name * @param {object} that Context * @return {sap.m.Image | sap.ui.core.Icon} oItemIcon * @private */ UploadCollection.prototype._createIcon = function(oItem, sItemId, sFileNameLong, that) { var sThumbnailUrl, sThumbnail, oItemIcon; sThumbnailUrl = oItem.getThumbnailUrl(); if (sThumbnailUrl) { oItemIcon = new sap.m.Image(sItemId + "-ia_imageHL", { src : sap.m.UploadCollection.prototype._getThumbnail(sThumbnailUrl, sFileNameLong), decorative : false, alt: this._getAriaLabelForPicture(oItem) }).addStyleClass("sapMUCItemImage"); } else { sThumbnail = sap.m.UploadCollection.prototype._getThumbnail(undefined, sFileNameLong); oItemIcon = new sap.ui.core.Icon(sItemId + "-ia_iconHL", { src : sThumbnail, decorative : false, useIconTooltip : false, alt: this._getAriaLabelForPicture(oItem) }).addStyleClass("sapMUCItemIcon"); if (sThumbnail === UploadCollection._placeholderCamera) { oItemIcon.addStyleClass("sapMUCItemPlaceholder"); } } if (this.sErrorState !== "Error" && jQuery.trim(oItem.getProperty("url"))) { oItemIcon.attachPress(function(oEvent) { sap.m.UploadCollection.prototype._triggerLink(oEvent, that); }); } return oItemIcon; }; /** * @description Gets Edit and Delete Buttons * @param {sap.ui.core.Item} oItem Base information to generate the list items * @param {string} sStatus status of the item: edit, display, uploading * @param {string} sItemId ID of the item being processed * @param {object} that Context * @return {array} aButtons an Array with buttons * @private */ UploadCollection.prototype._getButtons = function(oItem, sStatus, sItemId, that) { var aButtons, oOkButton, oCancelButton, sButton, oDeleteButton, bEnabled, oEditButton; aButtons = []; if (!this.getInstantUpload()) { // in case of pending upload we always have only "delete" button (no "edit" button) sButton = "deleteButton"; oDeleteButton = this._createDeleteButton(sItemId, sButton, oItem, this.sErrorState, that); aButtons.push(oDeleteButton); return aButtons; } if (sStatus === "Edit") { oOkButton = sap.ui.getCore().byId(sItemId + "-okButton"); if (!oOkButton) { oOkButton = new sap.m.Button({ id : sItemId + "-okButton", text : this._oRb.getText("UPLOADCOLLECTION_OKBUTTON_TEXT"), type : sap.m.ButtonType.Transparent }).addStyleClass("sapMUCOkBtn"); } oCancelButton = sap.ui.getCore().byId(sItemId + "-cancelButton"); if (!oCancelButton) { oCancelButton = new sap.m.Button({ id : sItemId + "-cancelButton", text : this._oRb.getText("UPLOADCOLLECTION_CANCELBUTTON_TEXT"), type : sap.m.ButtonType.Transparent }).addStyleClass("sapMUCCancelBtn"); } aButtons.push(oOkButton); aButtons.push(oCancelButton); return aButtons; } else if (sStatus === UploadCollection._uploadingStatus && !(sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9)) { sButton = "terminateButton"; oDeleteButton = this._createDeleteButton(sItemId, sButton, oItem, this.sErrorState, that); aButtons.push(oDeleteButton); return aButtons; } else { bEnabled = oItem.getEnableEdit(); if (this.sErrorState === "Error"){ bEnabled = false; } oEditButton = sap.ui.getCore().byId(sItemId + "-editButton"); if (!oEditButton) { if (oItem.getVisibleEdit()) { // if the Edit button is invisible we do not need to render it oEditButton = new sap.m.Button({ id : sItemId + "-editButton", icon : "sap-icon://edit", type : sap.m.ButtonType.Standard, enabled : bEnabled, visible : oItem.getVisibleEdit(), tooltip : this._oRb.getText("UPLOADCOLLECTION_EDITBUTTON_TEXT"), press : [oItem, this._handleEdit, this] }).addStyleClass("sapMUCEditBtn"); aButtons.push(oEditButton); } } else if (!oItem.getVisibleEdit()) { // If oEditButton exists and it is invisible, delete it. oEditButton.destroy(); oEditButton = null; } else { // oEditButton exists and is visible -> update oEditButton.setEnabled(bEnabled); oEditButton.setVisible(oItem.getVisibleEdit()); aButtons.push(oEditButton); } sButton = "deleteButton"; if (oItem.getVisibleDelete()) { // if a delete button is invisible we do not need to render it oDeleteButton = this._createDeleteButton(sItemId, sButton, oItem, this.sErrorState, that); aButtons.push(oDeleteButton); } else { // the button is not visible oDeleteButton = sap.ui.getCore().byId(sItemId + "-" + sButton); if (!!oDeleteButton) { // if a button already exists and it is for this item invisible it should be deleted oDeleteButton.destroy(); oDeleteButton = null; } } return aButtons; } }; /** * @description Creates a Delete button * @param {string} [sItemId] Id of the oItem * @param {string} [sButton] * if sButton == "deleteButton" it is a Delete button for the already uploaded file * if sButton == "terminateButton" it is a button to terminate the upload of the file being uploaded * @param {sap.m.UploadCollectionItem} oItem Item in scope * @param {string} sErrorState Internal error status * @param {object} that Context * @return {sap.m.Button} oDeleteButton * @private */ UploadCollection.prototype._createDeleteButton = function(sItemId, sButton, oItem, sErrorState, that) { var bEnabled, oDeleteButton; bEnabled = oItem.getEnableDelete(); if (sErrorState === "Error"){ bEnabled = false; } oDeleteButton = sap.ui.getCore().byId(sItemId + "-" + sButton); if (!oDeleteButton) { oDeleteButton = new sap.m.Button({ id : sItemId + "-" + sButton, icon : "sap-icon://sys-cancel", type : sap.m.ButtonType.Standard, enabled : bEnabled, tooltip : this._oRb.getText("UPLOADCOLLECTION_TERMINATEBUTTON_TEXT"), visible : oItem.getVisibleDelete() }).addStyleClass("sapMUCDeleteBtn"); if (sButton === "deleteButton") { oDeleteButton.setTooltip(this._oRb.getText("UPLOADCOLLECTION_DELETEBUTTON_TEXT")); oDeleteButton.attachPress(function(oEvent) { this._handleDelete(oEvent, that); }.bind(that)); } else if (sButton === "terminateButton") { oDeleteButton.attachPress(function(oEvent) { this._handleTerminate.bind(this)(oEvent, oItem); }.bind(that)); } } else { // delete button exists already oDeleteButton.setEnabled(bEnabled); oDeleteButton.setVisible(oItem.getVisibleDelete()); } return oDeleteButton; }; /** * @description Fill the list with items. * @param {array} aItems An array with items of type of sap.ui.core.Item. * @private */ UploadCollection.prototype._fillList = function(aItems) { var that = this; var iMaxIndex = aItems.length - 1; jQuery.each(aItems, function (iIndex, oItem) { if (!oItem._status) { //set default status value -> UploadCollection._displayStatus oItem._status = UploadCollection._displayStatus; } if (!oItem._percentUploaded && oItem._status === UploadCollection._uploadingStatus) { //set default percent uploaded oItem._percentUploaded = 0; } // add a private property to the added item containing a reference // to the corresponding mapped item var oListItem = that._mapItemToListItem(oItem); if (iIndex === 0 && iMaxIndex === 0){ oListItem.addStyleClass("sapMUCListSingleItem"); } else if (iIndex === 0) { oListItem.addStyleClass("sapMUCListFirstItem"); } else if (iIndex === iMaxIndex) { oListItem.addStyleClass("sapMUCListLastItem"); } else { oListItem.addStyleClass("sapMUCListItem"); } // add the mapped item to the List that._oList.addAggregation("items", oListItem, true); // note: suppress re-rendering // Handles item selected event oItem.attachEvent("selected", that._handleItemSetSelected, that); }); // Handles Upload Collection selection change event that._oList.attachSelectionChange(that._handleSelectionChange, that); }; /** * @description Destroy the items in the List. * @private */ UploadCollection.prototype._clearList = function() { if (this._oList) { this._oList.destroyAggregation("items", true); // note: suppress re-rendering } }; /** * @description Access and initialization for title number of attachments. Sets internal value. * @param {array} items Number of attachments * @private */ UploadCollection.prototype._setNumberOfAttachmentsTitle = function(items) { var nItems = items || 0; var sText; if (this.getNumberOfAttachmentsText()) { sText = this.getNumberOfAttachmentsText(); } else { sText = this._oRb.getText("UPLOADCOLLECTION_ATTACHMENTS", [nItems]); } if (!this._oNumberOfAttachmentsTitle) { this._oNumberOfAttachmentsTitle = new sap.m.Title(this.getId() + "-numberOfAttachmentsTitle", { text : sText }); } else { this._oNumberOfAttachmentsTitle.setText(sText); } }; /* =========================================================== */ /* Handle UploadCollection events */ /* =========================================================== */ /** * @description Handling of the deletion of an uploaded file * @param {object} oEvent Event of the deletion * @param {object} oContext Context of the deleted file * @returns {void} * @private */ UploadCollection.prototype._handleDelete = function(oEvent, oContext) { var oParams = oEvent.getParameters(); var aItems = oContext.getAggregation("items"); var sItemId = oParams.id.split("-deleteButton")[0]; var index = null; var sCompact = ""; var sFileName; var sMessageText; oContext.sDeletedItemId = sItemId; for (var i = 0; i < aItems.length; i++) { if (aItems[i].sId === sItemId) { index = i; break; } } if (jQuery.sap.byId(oContext.sId).hasClass("sapUiSizeCompact")) { sCompact = "sapUiSizeCompact"; } if (oContext.editModeItem) { //In case there is a list item in edit mode, the edit mode has to be finished first. sap.m.UploadCollection.prototype._handleOk(oEvent, oContext, oContext.editModeItem, true); if (oContext.sErrorState === "Error") { //If there is an error, the deletion must not be triggered return this; } } if (!!aItems[index] && aItems[index].getEnableDelete()) { // popup delete file sFileName = aItems[index].getFileName(); if (!sFileName) { sMessageText = this._oRb.getText("UPLOADCOLLECTION_DELETE_WITHOUT_FILENAME_TEXT"); } else { sMessageText = this._oRb.getText("UPLOADCOLLECTION_DELETE_TEXT", sFileName); } oContext._oItemForDelete = aItems[index]; oContext._oItemForDelete._iLineNumber = index; sap.m.MessageBox.show(sMessageText, { title : this._oRb.getText("UPLOADCOLLECTION_DELETE_TITLE"), actions : [sap.m.MessageBox.Action.OK, sap.m.MessageBox.Action.CANCEL], onClose : oContext._onCloseMessageBoxDeleteItem.bind(oContext), dialogId : "messageBoxDeleteFile", styleClass : sCompact }); } }; /** * @description Handling of the termination of an uploading file * @param {sap.m.MessageBox.Action} oAction Action to be executed at closing the message box * @private */ UploadCollection.prototype._onCloseMessageBoxDeleteItem = function (oAction) { this._oItemForDelete._status = UploadCollection._toBeDeletedStatus; if (oAction === sap.m.MessageBox.Action.OK) { if (this.getInstantUpload()) { // fire event this.fireFileDeleted({ // deprecated documentId : this._oItemForDelete.getDocumentId(), // new item : this._oItemForDelete }); } else { if (this.aItems.length === 1) { this.sFocusId = this._oFileUploader.$().find(":button")[0].id; } else { if (this._oItemForDelete._iLineNumber < this.aItems.length - 1) { this.sFocusId = this.aItems[this._oItemForDelete._iLineNumber + 1].getId() + "-cli"; } else { this.sFocusId = this.aItems[0].getId() + "-cli"; } } this._aDeletedItemForPendingUpload.push(this._oItemForDelete); this.aItems.splice(this._oItemForDelete._iLineNumber, 1); this.removeAggregation("items", this._oItemForDelete, false); } } }; /** * @description Handling of termination of an uploading process * @param {object} oEvent Event of the upload termination * @param {object} oContext Context of the upload termination * @private */ UploadCollection.prototype._handleTerminate = function(oEvent, oItem) { var oFileList, oDialog; oFileList = new sap.m.List({ items : [ new sap.m.StandardListItem({ title : oItem.getFileName(), icon : this._getIconFromFilename(oItem.getFileName()) })] }); oDialog = new sap.m.Dialog({ id : this.getId() + "deleteDialog", title: this._oRb.getText("UPLOADCOLLECTION_TERMINATE_TITLE"), content : [ new sap.m.Text({ text : this._oRb.getText("UPLOADCOLLECTION_TERMINATE_TEXT") }), oFileList], buttons:[ new sap.m.Button({ text: this._oRb.getText("UPLOADCOLLECTION_OKBUTTON_TEXT"), press: [onPressOk, this] }), new sap.m.Button({ text: this._oRb.getText("UPLOADCOLLECTION_CANCELBUTTON_TEXT"), press: function() { oDialog.close(); } })], afterClose: function() { oDialog.destroy(); } }).open(); function onPressOk () { var bAbort = false; // if the file is already loaded send a delete request to the application for (var i = 0; i < this.aItems.length; i++) { if (this.aItems[i]._status === UploadCollection._uploadingStatus && this.aItems[i]._requestIdName === oItem._requestIdName) { bAbort = true; break; } else if (oItem.getFileName() === this.aItems[i].getFileName() && this.aItems[i]._status === UploadCollection._displayStatus) { this.aItems[i]._status = UploadCollection._toBeDeletedStatus; this.fireFileDeleted({ documentId : this.aItems[i].getDocumentId(), item : this.aItems[i] }); break; } } // call FileUploader if abort is possible. Otherwise fireDelete should be called. if (bAbort) { this._getFileUploader().abort(this._headerParamConst.fileNameRequestIdName, this._encodeToAscii(oItem.getFileName()) + this.aItems[i]._requestIdName); } oDialog.close(); this.invalidate(); } }; /** * @description Handling of event of the edit button * @param {object} oEvent Event of the edit button * @param {object} oItem The Item in context of the edit button * @private */ UploadCollection.prototype._handleEdit = function(oEvent, oItem) { var i, sItemId = oItem.getId(), cItems = this.aItems.length; if (this.editModeItem) { sap.m.UploadCollection.prototype._handleOk(oEvent, this, this.editModeItem, false); } if (this.sErrorState !== "Error") { for (i = 0; i < cItems ; i++) { if (this.aItems[i].getId() === sItemId) { this.aItems[i]._status = "Edit"; break; } } oItem._status = "Edit"; this.editModeItem = oEvent.getSource().getId().split("-editButton")[0]; this.invalidate(); } }; /** * @description Handling of 'click' of the list (items + header) * @param {object} oEvent Event of the 'click' * @param {object} oContext Context of the list item where 'click' was triggered * @param {string} sSourceId List item id/identifier were the click was triggered * @private */ UploadCollection.prototype._handleClick = function(oEvent, oContext, sSourceId) { // if the target of the click event is an editButton, than this case has already been processed // in the _handleEdit (in particular, by executing the _handleOk function). // Therefore only the remaining cases of click event targets are handled. if (oEvent.target.id.lastIndexOf("editButton") < 0) { if (oEvent.target.id.lastIndexOf("cancelButton") > 0) { sap.m.UploadCollection.prototype._handleCancel(oEvent, oContext, sSourceId); } else if (oEvent.target.id.lastIndexOf("ia_imageHL") < 0 && oEvent.target.id.lastIndexOf("ia_iconHL") < 0 && oEvent.target.id.lastIndexOf("deleteButton") < 0 && oEvent.target.id.lastIndexOf("ta_editFileName-inner") < 0) { if (oEvent.target.id.lastIndexOf("cli") > 0) { oContext.sFocusId = oEvent.target.id; } sap.m.UploadCollection.prototype._handleOk(oEvent, oContext, sSourceId, true); } } }; /** * @description Handling of 'OK' of the list item (status = 'Edit') * @param {object} oEvent Event of the 'OK' activity * @param {object} oContext Context of the list item where 'ok' was triggered * @param {string} sSourceId List item ID * @param {boolean} bTriggerRenderer Switch for to trigger the renderer * @private */ UploadCollection.prototype._handleOk = function(oEvent, oContext, sSourceId, bTriggerRenderer) { var bTriggerOk = true; var oEditbox = document.getElementById(sSourceId + "-ta_editFileName-inner"); var sNewFileName; var iSourceLine = sSourceId.split("-").pop(); var sOrigFullFileName = oContext.aItems[iSourceLine].getProperty("fileName"); var oFile = UploadCollection.prototype._splitFilename(sOrigFullFileName); var oInput = sap.ui.getCore().byId(sSourceId + "-ta_editFileName"); var sErrorStateBefore = oContext.aItems[iSourceLine].errorState; var sChangedNameBefore = oContext.aItems[iSourceLine].changedFileName; // get new/changed file name and remove potential leading spaces if (oEditbox !== null) { sNewFileName = oEditbox.value.replace(/^\s+/,""); } //prepare the Id of the UI element which will get the focus var aSrcIdElements = oEvent.srcControl ? oEvent.srcControl.getId().split("-") : oEvent.oSource.getId().split("-"); aSrcIdElements = aSrcIdElements.slice(0, 5); oContext.sFocusId = aSrcIdElements.join("-") + "-cli"; if ( sNewFileName && (sNewFileName.length > 0)) { oContext.aItems[iSourceLine]._status = UploadCollection._displayStatus; // in case there is a difference, additional activities are necessary if (oFile.name !== sNewFileName) { // here we have to check possible double items if it's necessary if (!oContext.getSameFilenameAllowed()) { // Check double file name if (sap.m.UploadCollection.prototype._checkDoubleFileName(sNewFileName + oFile.extension, oContext.aItems)) { oInput.setProperty("valueState", "Error", true); oContext.aItems[iSourceLine]._status = "Edit"; oContext.aItems[iSourceLine].errorState = "Error"; oContext.aItems[iSourceLine].changedFileName = sNewFileName; oContext.sErrorState = "Error"; bTriggerOk = false; if (sErrorStateBefore !== "Error" || sChangedNameBefore !== sNewFileName){ oContext.invalidate(); } } else { oInput.setProperty("valueState", "None", true); oContext.aItems[iSourceLine].errorState = null; oContext.aItems[iSourceLine].changedFileName = null; oContext.sErrorState = null; oContext.editModeItem = null; if (bTriggerRenderer) { oContext.invalidate(); } } } if (bTriggerOk) { oContext._oItemForRename = oContext.aItems[iSourceLine]; oContext._onEditItemOk.bind(oContext)(sNewFileName + oFile.extension); } } else { oContext.sErrorState = null; oContext.aItems[iSourceLine].errorState = null; // nothing changed -> nothing to do! oContext.editModeItem = null; if (bTriggerRenderer) { oContext.invalidate(); } } } else if (oEditbox !== null) { // no new file name provided oContext.aItems[iSourceLine]._status = "Edit"; oContext.aItems[iSourceLine].errorState = "Error"; oContext.aItems[iSourceLine].changedFileName = sNewFileName; oContext.sErrorState = "Error"; if (sErrorStateBefore !== "Error" || sChangedNameBefore !== sNewFileName){ oContext.aItems[iSourceLine].invalidate(); } } }; /** * @description Handling of edit item * @param {string} sNewFileName New file name * @private */ UploadCollection.prototype._onEditItemOk = function (sNewFileName) { if (this._oItemForRename) { this._oItemForRename.setFileName(sNewFileName); // fire event this.fireFileRenamed({ // deprecated documentId : this._oItemForRename.getProperty("documentId"), fileName : sNewFileName, // new item : this._oItemForRename }); } delete this._oItemForRename; }; /** * @description Handling of 'cancel' of the list item (status = 'Edit') * @param {object} oEvent Event of the 'cancel' activity * @param {object} oContext Context of the list item where 'cancel' was triggered * @param {string} sSourceId List item id * @private */ UploadCollection.prototype._handleCancel = function(oEvent, oContext, sSourceId) { var iSourceLine = sSourceId.split("-").pop(); oContext.aItems[iSourceLine]._status = UploadCollection._displayStatus; oContext.aItems[iSourceLine].errorState = null; oContext.aItems[iSourceLine].changedFileName = sap.ui.getCore().byId(sSourceId + "-ta_editFileName").getProperty("value"); oContext.sFocusId = oContext.editModeItem + "-cli"; oContext.sErrorState = null; oContext.editModeItem = null; oContext.invalidate(); }; /* =========================================================== */ /* Handle FileUploader events */ /* =========================================================== */ /** * @description Handling of the Event change of the fileUploader * @param {object} oEvent Event of the fileUploader * @private */ UploadCollection.prototype._onChange = function(oEvent) { if (oEvent) { var that = this; var sRequestValue, iCountFiles, i, sFileName, oItem, sStatus, sFileSizeFormated, oAttr; this._cAddItems = 0; if (sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9) { // FileUploader does not support files parameter for IE9 for the time being var sNewValue = oEvent.getParameter("newValue"); if (!sNewValue) { return; } sFileName = sNewValue.split(/\" "/)[0]; //sometimes onChange is called if no data was selected if ( sFileName.length === 0 ) { return; } } else { iCountFiles = oEvent.getParameter("files").length; // FileUploader fires the change event also if no file was selected by the user // If so, do nothing. if (iCountFiles === 0) { return; } this._oFileUploader.removeAllAggregation("headerParameters", true); this.removeAllAggregation("headerParameters", true); } this._oFileUploader.removeAllAggregation("parameters", true); this.removeAllAggregation("parameters", true); // IE9 if (sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9) { var oFile = { name : oEvent.getParameter("newValue") }; var oParameters = { files : [oFile] }; this.fireChange({ // deprecated getParameter : function(sParameter) { if (sParameter === "files") { return [oFile]; } }, getParameters : function() { return oParameters; }, mParameters : oParameters, // new files : [oFile] }); } else { this.fireChange({ // deprecated getParameter : function(sParameter) { if (sParameter) { return oEvent.getParameter(sParameter); } }, getParameters : function() { return oEvent.getParameters(); }, mParameters : oEvent.getParameters(), // new files : oEvent.getParameter("files") }); } var aParametersAfter = this.getAggregation("parameters"); // parameters if (aParametersAfter) { jQuery.each(aParametersAfter, function (iIndex, parameter) { var oParameter = new sap.ui.unified.FileUploaderParameter({ name : parameter.getProperty("name"), value: parameter.getProperty("value") }); that._oFileUploader.addParameter(oParameter); }); } if (!this.getInstantUpload()) { sStatus = UploadCollection._pendingUploadStatus; } else { sStatus = UploadCollection._uploadingStatus; } if (sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9) { oItem = new sap.m.UploadCollectionItem({ fileName: sFileName }); oItem._status = sStatus; oItem._internalFileIndexWithinFileUploader = 1; if (!this.getInstantUpload()) { oItem.setAssociation("fileUploader",this._oFileUploader, true); this.insertItem(oItem); this._aFileUploadersForPendingUpload.push(this._oFileUploader); } else { oItem._percentUploaded = 0; } this.aItems.unshift(oItem); this._cAddItems++; } else { this._requestIdValue = this._requestIdValue + 1; sRequestValue = this._requestIdValue.toString(); var aHeaderParametersAfter = this.getAggregation("headerParameters"); if (!this.getInstantUpload()) { this._aFileUploadersForPendingUpload.push(this._oFileUploader); } for (i = 0; i < iCountFiles; i++) { oItem = new sap.m.UploadCollectionItem({ fileName: oEvent.getParameter("files")[i].name }); oItem._status = sStatus; oItem._internalFileIndexWithinFileUploader = i + 1; oItem._requestIdName = sRequestValue; if (!this.getInstantUpload()) { oItem.setAssociation("fileUploader",this._oFileUploader, true); sFileSizeFormated = this._oFormatDecimal.format(oEvent.getParameter("files")[i].size); oAttr = new ObjectAttribute({text: sFileSizeFormated}); oItem.insertAggregation("attributes", oAttr, true); this.insertItem(oItem); } else { oItem._percentUploaded = 0; } this.aItems.unshift(oItem); this._cAddItems++; } //headerParameters if (aHeaderParametersAfter) { jQuery.each(aHeaderParametersAfter, function (iIndex, headerParameter) { that._oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({ name : headerParameter.getProperty("name"), value: headerParameter.getProperty("value") })); }); } that._oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({ name : this._headerParamConst.requestIdName, value: sRequestValue })); } } }; /** * @description Handling of the Event filenameLengthExceed of the fileUploader * @param {object} oEvent Event of the fileUploader * @private */ UploadCollection.prototype._onFilenameLengthExceed = function(oEvent) { var oFile = {name: oEvent.getParameter("fileName")}; var aFiles = [oFile]; this.fireFilenameLengthExceed({ // deprecated getParameter : function(sParameter) { if (sParameter) { return oEvent.getParameter(sParameter); } }, getParameters : function() { return oEvent.getParameters(); }, mParameters : oEvent.getParameters(), // new files : aFiles }); }; /** * @description Handling of the Event fileSizeExceed of the fileUploader * @param {object} oEvent Event of the fileUploader * @private */ UploadCollection.prototype._onFileSizeExceed = function(oEvent){ var oFile; if (sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9) { // IE9 var sFileName = oEvent.getParameter("newValue"); oFile = { name : sFileName }; var oParameters = { newValue : sFileName, files : [oFile] }; this.fireFileSizeExceed({ // deprecated getParameter : function(sParameter) { if (sParameter === "files") { return [oFile]; } else if (sParameter === "newValue") { return sFileName; } }, getParameters : function() { return oParameters; }, mParameters : oParameters, // new files : [oFile] }); } else { // other browsers oFile = { name: oEvent.getParameter("fileName"), fileSize: oEvent.getParameter("fileSize")}; this.fireFileSizeExceed({ // deprecated getParameter : function(sParameter) { if (sParameter) { return oEvent.getParameter(sParameter); } }, getParameters : function() { return oEvent.getParameters(); }, mParameters : oEvent.getParameters(), // new files : [oFile] }); } }; /** * @description Handling of the Event typeMissmatch of the fileUploader * @param {object} oEvent Event of the fileUploader * @private */ UploadCollection.prototype._onTypeMissmatch = function(oEvent) { var oFile = {name: oEvent.getParameter("fileName"), fileType: oEvent.getParameter("fileType"), mimeType: oEvent.getParameter("mimeType")}; var aFiles = [oFile]; this.fireTypeMissmatch({ // deprecated getParameter : function(sParameter) { if (sParameter) { return oEvent.getParameter(sParameter); } }, getParameters : function() { return oEvent.getParameters(); }, mParameters : oEvent.getParameters(), // new files : aFiles }); }; /** * @description Handling of the Event uploadTerminated of the fileUploader * @param {object} oEvent Event of the fileUploader * @private */ UploadCollection.prototype._onUploadTerminated = function(oEvent) { var i; var sRequestId = this._getRequestId(oEvent); var sFileName = oEvent.getParameter("fileName"); var cItems = this.aItems.length; for (i = 0; i < cItems ; i++) { if (this.aItems[i] && this.aItems[i].getFileName() === sFileName && this.aItems[i]._requestIdName === sRequestId && this.aItems[i]._status === UploadCollection._uploadingStatus) { this.aItems.splice(i, 1); this.removeItem(i); break; } } this.fireUploadTerminated({ fileName: sFileName, getHeaderParameter: this._getHeaderParameterWithinEvent.bind(oEvent) }); }; /** * @description Handling of the Event uploadComplete of the fileUploader to forward the Event to the application * @param {object} oEvent Event of the fileUploader * @private */ UploadCollection.prototype._onUploadComplete = function(oEvent) { if (oEvent) { var i, sRequestId, sUploadedFile, cItems, bUploadSuccessful = checkRequestStatus(); sRequestId = this._getRequestId(oEvent); sUploadedFile = oEvent.getParameter("fileName"); // at the moment parameter fileName is not set in IE9 if (!sUploadedFile) { var aUploadedFile = (oEvent.getSource().getProperty("value")).split(/\" "/); sUploadedFile = aUploadedFile[0]; } cItems = this.aItems.length; for (i = 0; i < cItems; i++) { // sRequestId should be null only in case of IE9 because FileUploader does not support header parameters for it if (!sRequestId) { if (this.aItems[i].getProperty("fileName") === sUploadedFile && this.aItems[i]._status === UploadCollection._uploadingStatus && bUploadSuccessful) { this.aItems[i]._percentUploaded = 100; this.aItems[i]._status = UploadCollection._displayStatus; break; } else if (this.aItems[i].getProperty("fileName") === sUploadedFile && this.aItems[i]._status === UploadCollection._uploadingStatus) { this.aItems.splice(i, 1); } } else if (this.aItems[i].getProperty("fileName") === sUploadedFile && this.aItems[i]._requestIdName === sRequestId && this.aItems[i]._status === UploadCollection._uploadingStatus && bUploadSuccessful) { this.aItems[i]._percentUploaded = 100; this.aItems[i]._status = UploadCollection._displayStatus; break; } else if (this.aItems[i].getProperty("fileName") === sUploadedFile && this.aItems[i]._requestIdName === sRequestId && this.aItems[i]._status === UploadCollection._uploadingStatus || this.aItems[i]._status === UploadCollection._pendingUploadStatus) { this.aItems.splice(i, 1); break; } } this.fireUploadComplete({ // deprecated getParameter : oEvent.getParameter, getParameters : oEvent.getParameters, mParameters : oEvent.getParameters(), // new Stuff files : [{ fileName : oEvent.getParameter("fileName") || sUploadedFile, responseRaw : oEvent.getParameter("responseRaw"), reponse : oEvent.getParameter("response"), status : oEvent.getParameter("status"), headers : oEvent.getParameter("headers") }] }); } function checkRequestStatus () { var sRequestStatus = oEvent.getParameter("status").toString() || "200"; // In case of IE version < 10, this function will not work. if (sRequestStatus[0] === "2" || sRequestStatus[0] === "3") { return true; } else { return false; } } }; /** * @description Handling of the uploadProgress event of the fileUploader to forward the event to the application * @param {object} oEvent Event of the fileUploader * @private */ UploadCollection.prototype._onUploadProgress = function(oEvent) { if (oEvent) { var i, sUploadedFile, sPercentUploaded, iPercentUploaded, sRequestId, cItems, oProgressDomRef, sItemId, $busyIndicator; sUploadedFile = oEvent.getParameter("fileName"); sRequestId = this._getRequestId(oEvent); iPercentUploaded = Math.round(oEvent.getParameter("loaded") / oEvent.getParameter("total") * 100); if (iPercentUploaded === 100) { sPercentUploaded = this._oRb.getText("UPLOADCOLLECTION_UPLOAD_COMPLETED"); } else { sPercentUploaded = this._oRb.getText("UPLOADCOLLECTION_UPLOADING", [iPercentUploaded]); } cItems = this.aItems.length; for (i = 0; i < cItems; i++) { if (this.aItems[i].getProperty("fileName") === sUploadedFile && this.aItems[i]._requestIdName == sRequestId && this.aItems[i]._status === UploadCollection._uploadingStatus) { oProgressDomRef = sap.ui.getCore().byId(this.aItems[i].getId() + "-ta_progress"); //necessary for IE otherwise it comes to an error if onUploadProgress happens before the new item is added to the list if (!!oProgressDomRef) { oProgressDomRef.setText(sPercentUploaded); this.aItems[i]._percentUploaded = iPercentUploaded; // add ARIA attribute for screen reader support sItemId = this.aItems[i].getId(); $busyIndicator = jQuery.sap.byId(sItemId + "-ia_indicator"); if (iPercentUploaded === 100) { $busyIndicator.attr("aria-label", sPercentUploaded); } else { $busyIndicator.attr("aria-valuenow", iPercentUploaded); } break; } } } } }; /** * @description Get the Request ID from the header parameters of a fileUploader event * @param {object} oEvent Event of the fileUploader * @returns {string} Request ID * @private */ UploadCollection.prototype._getRequestId = function(oEvent) { var oHeaderParams; oHeaderParams = oEvent.getParameter("requestHeaders"); if (!oHeaderParams) { return null; } for (var j = 0; j < oHeaderParams.length; j++) { if (oHeaderParams[j].name === this._headerParamConst.requestIdName) { return oHeaderParams[j].value; } } }; /** * @description Access and initialization for the FileUploader * @returns {sap.ui.unified.FileUploader} Instance of the FileUploader * @private */ UploadCollection.prototype._getFileUploader = function() { var that = this, bUploadOnChange = this.getInstantUpload(); if (!bUploadOnChange || !this._oFileUploader) { // In case of instantUpload = false always create a new FU instance. In case of instantUpload = true only create a new FU instance if no FU instance exists yet var bSendXHR = (sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9) ? false : true; this._iFUCounter = this._iFUCounter + 1; // counter for FileUploader instances this._oFileUploader = new sap.ui.unified.FileUploader(this.getId() + "-" + this._iFUCounter + "-uploader",{ buttonOnly : true, iconOnly : true, enabled : this.getUploadEnabled(), fileType : this.getFileType(), icon : "sap-icon://add", iconFirst : false, style : "Transparent", maximumFilenameLength : this.getMaximumFilenameLength(), maximumFileSize : this.getMaximumFileSize(), mimeType : this.getMimeType(), multiple : this.getMultiple(), name : "uploadCollection", uploadOnChange : bUploadOnChange, sameFilenameAllowed : true, uploadUrl : this.getUploadUrl(), useMultipart : false, sendXHR : bSendXHR, // false for IE8, IE9 change : function(oEvent) { that._onChange(oEvent); }, filenameLengthExceed : function(oEvent) { that._onFilenameLengthExceed(oEvent); }, fileSizeExceed : function(oEvent) { that._onFileSizeExceed(oEvent); }, typeMissmatch : function(oEvent) { that._onTypeMissmatch(oEvent); }, uploadAborted : function(oEvent) { // only supported with property sendXHR set to true that._onUploadTerminated(oEvent); }, uploadComplete : function(oEvent) { that._onUploadComplete(oEvent); }, uploadProgress : function(oEvent) { // only supported with property sendXHR set to true if (that.getInstantUpload()) { that._onUploadProgress(oEvent); } }, uploadStart : function(oEvent) { that._onUploadStart(oEvent); } }); var sTooltip = this._oFileUploader.getTooltip(); if (!sTooltip && !sap.ui.Device.browser.msie) { this._oFileUploader.setTooltip(" "); } } return this._oFileUploader; }; /** * @description Creates the unique key for a file by concatenating the fileName with its requestId and puts it into the requestHeaders parameter of the FileUploader. * It triggers the beforeUploadStarts event for applications to add the header parameters for each file. * @param {jQuery.Event} oEvent * @private */ UploadCollection.prototype._onUploadStart = function(oEvent) { var oRequestHeaders = {}, i, sRequestIdValue, iParamCounter, sFileName, oGetHeaderParameterResult; this._iUploadStartCallCounter++; iParamCounter = oEvent.getParameter("requestHeaders").length; for (i = 0; i < iParamCounter; i++ ) { if (oEvent.getParameter("requestHeaders")[i].name === this._headerParamConst.requestIdName) { sRequestIdValue = oEvent.getParameter("requestHeaders")[i].value; break; } } sFileName = oEvent.getParameter("fileName"); oRequestHeaders = { name: this._headerParamConst.fileNameRequestIdName, value: this._encodeToAscii(sFileName) + sRequestIdValue }; oEvent.getParameter("requestHeaders").push(oRequestHeaders); for ( i = 0; i < this._aDeletedItemForPendingUpload.length; i++ ) { if (this._aDeletedItemForPendingUpload[i].getAssociation("fileUploader") === oEvent.oSource.sId && this._aDeletedItemForPendingUpload[i].getFileName() === sFileName && this._aDeletedItemForPendingUpload[i]._internalFileIndexWithinFileUploader === this._iUploadStartCallCounter){ oEvent.getSource().abort(this._headerParamConst.fileNameRequestIdName, this._encodeToAscii(sFileName) + sRequestIdValue); return; } } this.fireBeforeUploadStarts({ fileName: sFileName, addHeaderParameter: addHeaderParameter, getHeaderParameter: getHeaderParameter.bind(this) }); // ensure that the HeaderParameterValues are updated if (jQuery.isArray(oGetHeaderParameterResult)) { for (i = 0; i < oGetHeaderParameterResult.length; i++) { if (oEvent.getParameter("requestHeaders")[i].name === oGetHeaderParameterResult[i].getName()) { oEvent.getParameter("requestHeaders")[i].value = oGetHeaderParameterResult[i].getValue(); } } } else if (oGetHeaderParameterResult instanceof sap.m.UploadCollectionParameter) { for (i = 0; i < oEvent.getParameter("requestHeaders").length; i++) { if (oEvent.getParameter("requestHeaders")[i].name === oGetHeaderParameterResult.getName()) { oEvent.getParameter("requestHeaders")[i].value = oGetHeaderParameterResult.getValue(); break; } } } function addHeaderParameter(oUploadCollectionParameter) { var oRequestHeaders = { name: oUploadCollectionParameter.getName(), value: oUploadCollectionParameter.getValue() }; oEvent.getParameter("requestHeaders").push(oRequestHeaders); } function getHeaderParameter(sHeaderParameterName) { oGetHeaderParameterResult = this._getHeaderParameterWithinEvent.bind(oEvent)(sHeaderParameterName); return oGetHeaderParameterResult; } }; /** * @description Determines the icon from the filename. * @param {string} sFilename Name of the file inclusive extension(e.g. .txt, .pdf, ...). * @returns {string} Icon related to the file extension. * @private */ UploadCollection.prototype._getIconFromFilename = function(sFilename) { var sFileExtension = this._splitFilename(sFilename).extension; if (jQuery.type(sFileExtension) === "string") { sFileExtension = sFileExtension.toLowerCase(); } switch (sFileExtension) { case '.bmp' : case '.jpg' : case '.jpeg' : case '.png' : return UploadCollection._placeholderCamera; // if no image is provided a standard placeholder camera is displayed case '.csv' : case '.xls' : case '.xlsx' : return 'sap-icon://excel-attachment'; case '.doc' : case '.docx' : case '.odt' : return 'sap-icon://doc-attachment'; case '.pdf' : return 'sap-icon://pdf-attachment'; case '.ppt' : case '.pptx' : return 'sap-icon://ppt-attachment'; case '.txt' : return 'sap-icon://document-text'; default : return 'sap-icon://document'; } }; /** * @description Determines the thumbnail of an item. * @param {string} sThumbnailUrl Url of the thumbnail-image of the UC list item * @param {string} sFilename Name of the file to determine if there could be a thumbnail * @returns {string} ThumbnailUrl or icon * @private */ UploadCollection.prototype._getThumbnail = function(sThumbnailUrl, sFilename) { if (sThumbnailUrl) { return sThumbnailUrl; } else { return this._getIconFromFilename(sFilename); } }; /** * @description Trigger of the link which will be executed when the icon or image was clicked * @param {object} oEvent when clicking or pressing of the icon or image * @param {object} oContext Context of the link * @returns {void} * @private */ UploadCollection.prototype._triggerLink = function(oEvent, oContext) { var iLine = null; var aId; if (oContext.editModeItem) { //In case there is a list item in edit mode, the edit mode has to be finished first. sap.m.UploadCollection.prototype._handleOk(oEvent, oContext, oContext.editModeItem, true); if (oContext.sErrorState === "Error") { //If there is an error, the link of the list item must not be triggered. return this; } oContext.sFocusId = oEvent.getParameter("id"); } aId = oEvent.oSource.getId().split("-"); iLine = aId[aId.length - 2]; sap.m.URLHelper.redirect(oContext.aItems[iLine].getProperty("url"), true); }; // ================================================================================ // Keyboard activities // ================================================================================ /** * @description Keyboard support: Handling of different key activities * @param {Object} oEvent Event of the key activity * @returns {void} * @private */ UploadCollection.prototype.onkeydown = function(oEvent) { switch (oEvent.keyCode) { case jQuery.sap.KeyCodes.F2 : sap.m.UploadCollection.prototype._handleF2(oEvent, this); break; case jQuery.sap.KeyCodes.ESCAPE : sap.m.UploadCollection.prototype._handleESC(oEvent, this); break; case jQuery.sap.KeyCodes.DELETE : sap.m.UploadCollection.prototype._handleDEL(oEvent, this); break; case jQuery.sap.KeyCodes.ENTER : sap.m.UploadCollection.prototype._handleENTER(oEvent, this); break; default : return; } oEvent.setMarked(); }; // ================================================================================ // helpers // ================================================================================ /** * @description Set the focus after the list item was deleted. * @param {Object} DeletedItemId ListItem id which was deleted * @param {Object} oContext Context of the ListItem which was deleted * @returns {void} * @private */ UploadCollection.prototype._setFocusAfterDeletion = function(DeletedItemId, oContext) { if (!DeletedItemId) { return; } var iLength = oContext.aItems.length; var sLineId = null; if (iLength === 0){ var oFileUploader = jQuery.sap.byId(oContext._oFileUploader.sId); var oFocusObj = oFileUploader.find(":button"); jQuery.sap.focus(oFocusObj); } else { var iLineNumber = DeletedItemId.split("-").pop(); //Deleted item is not the last one of the list if ((iLength - 1) >= iLineNumber) { sLineId = DeletedItemId + "-cli"; } else { sLineId = oContext.aItems.pop().sId + "-cli"; } sap.m.UploadCollection.prototype._setFocus2LineItem(sLineId); this.sDeletedItemId = null; } }; /** * @description Set the focus to the list item. * @param {string} sFocusId ListItem which should get the focus * @returns {void} * @private */ UploadCollection.prototype._setFocus2LineItem = function(sFocusId) { jQuery.sap.byId(sFocusId).focus(); }; /** * @description Handle of keyboard activity ENTER. * @param {Object} oEvent ListItem of the keyboard activity ENTER * @param {Object} oContext Context of the keyboard activity ENTER * @returns {void} * @private */ UploadCollection.prototype._handleENTER = function (oEvent, oContext) { var sTarget; var sLinkId; var oLink; if (oContext.editModeItem) { sTarget = oEvent.target.id.split(oContext.editModeItem).pop(); } else { sTarget = oEvent.target.id.split("-").pop(); } switch (sTarget) { case "-ta_editFileName-inner" : case "-okButton" : sap.m.UploadCollection.prototype._handleOk(oEvent, oContext, oContext.editModeItem, true); break; case "-cancelButton" : oEvent.preventDefault(); sap.m.UploadCollection.prototype._handleCancel(oEvent, oContext, oContext.editModeItem); break; case "-ia_iconHL" : case "-ia_imageHL" : //Edit mode var iLine = oContext.editModeItem.split("-").pop(); sap.m.URLHelper.redirect(oContext.aItems[iLine].getProperty("url"), true); break; case "ia_iconHL" : case "ia_imageHL" : case "cli": //Display mode sLinkId = oEvent.target.id.split(sTarget)[0] + "ta_filenameHL"; oLink = sap.ui.getCore().byId(sLinkId); if (oLink.getEnabled()) { iLine = oEvent.target.id.split("-")[2]; sap.m.URLHelper.redirect(oContext.aItems[iLine].getProperty("url"), true); } break; default : return; } }; /** * @description Handle of keyboard activity DEL. * @param {Object} oEvent ListItem of the keyboard activity DEL * @param {Object} oContext Context of the keyboard activity DEL * @private */ UploadCollection.prototype._handleDEL = function(oEvent, oContext) { if (!oContext.editModeItem) { var o$Obj = jQuery.sap.byId(oEvent.target.id); var o$DeleteButton = o$Obj.find("[id$='-deleteButton']"); var oDeleteButton = sap.ui.getCore().byId(o$DeleteButton[0].id); oDeleteButton.firePress(); } }; /** * @description Handle of keyboard activity ESC. * @param {Object} oEvent ListItem of the keyboard activity ESC * @param {Object} oContext Context of the keyboard activity ESC * @private */ UploadCollection.prototype._handleESC = function(oEvent, oContext) { if (oContext.editModeItem){ oContext.sFocusId = oContext.editModeItem + "-cli"; oContext.aItems[oContext.editModeItem.split("-").pop()]._status = UploadCollection._displayStatus; sap.m.UploadCollection.prototype._handleCancel(oEvent, oContext, oContext.editModeItem); } }; /** * @description Handle of keyboard activity F2. * @param {Object} oEvent Event of the keyboard activity F2 * @param {Object} oContext Context of the keyboard activity F2 * @private */ UploadCollection.prototype._handleF2 = function(oEvent, oContext) { var oObj = sap.ui.getCore().byId(oEvent.target.id); if (oObj !== undefined) { if (oObj._status === UploadCollection._displayStatus) { //focus at list line (status = "display") and F2 pressed --> status = "Edit" var o$Obj = jQuery.sap.byId(oEvent.target.id); var o$EditButton = o$Obj.find("[id$='-editButton']"); var oEditButton = sap.ui.getCore().byId(o$EditButton[0].id); if (oEditButton.getEnabled()) { if (oContext.editModeItem){ sap.m.UploadCollection.prototype._handleClick(oEvent, oContext, oContext.editModeItem); } if (oContext.sErrorState !== "Error") { oEditButton.firePress(); } } } else { //focus at list line(status= "Edit") and F2 is pressed --> status = "display", changes will be saved and //if the focus is at any other object of the list item sap.m.UploadCollection.prototype._handleClick(oEvent, oContext, oContext.editModeItem); } } else if (oEvent.target.id.search(oContext.editModeItem) === 0) { //focus at Inputpield (status = "Edit"), F2 pressed --> status = "display" changes will be saved sap.m.UploadCollection.prototype._handleOk(oEvent, oContext, oContext.editModeItem, true); } }; /** * @description Delivers an array of Filenames from a string of the FileUploader event. * @param {string} sFilenames * @returns {array} Array of files which are selected to be uploaded. * @private */ UploadCollection.prototype._getFileNames = function(sFilenames) { if (this.getMultiple() && !(sap.ui.Device.browser.msie && sap.ui.Device.browser.version <= 9)) { return sFilenames.substring(1, sFilenames.length - 2).split(/\" "/); } else { return sFilenames.split(/\" "/); } }; /** * @description Determines if the fileName is already in usage. * @param {string} sFilename inclusive file extension * @param {array} aItems Collection of uploaded files * @returns {boolean} true for an already existing item with the same file name(independent of the path) * @private */ UploadCollection.prototype._checkDoubleFileName = function(sFilename, aItems) { if (aItems.length === 0 || !sFilename) { return false; } var iLength = aItems.length; sFilename = sFilename.replace(/^\s+/,""); for (var i = 0; i < iLength; i++) { if (sFilename === aItems[i].getProperty("fileName")){ return true; } } return false; }; /** * @description Split file name into name and extension. * @param {string} sFilename Full file name inclusive the extension * @returns {object} oResult Filename and Extension * @deprecated UploadCollectionItem._splitFileName method should be used instead * @private */ UploadCollection.prototype._splitFilename = function(sFilename) { var oResult = {}; var aNameSplit = sFilename.split("."); if (aNameSplit.length == 1) { oResult.extension = ""; oResult.name = aNameSplit.pop(); return oResult; } oResult.extension = "." + aNameSplit.pop(); oResult.name = aNameSplit.join("."); return oResult; }; /** * @description Getter of aria label for the icon or image. * @param {object} oItem An item of the list to which the text is to be retrieved * @returns {string} sText Text of the icon (or image) * @private */ UploadCollection.prototype._getAriaLabelForPicture = function(oItem) { var sText; // prerequisite: the items have field names or the app provides explicite texts for pictures sText = (oItem.getAriaLabelForPicture() || oItem.getFileName()); return sText; }; /** * @description Helper function for better Event API. This reference points to the oEvent comming from the FileUploader * @param {string} Header parameter name (optional) * @returns {UploadCollectionParameter} || {UploadCollectionParameter[]} * @private */ UploadCollection.prototype._getHeaderParameterWithinEvent = function (sHeaderParameterName) { var aUcpRequestHeaders = []; var aRequestHeaders = this.getParameter("requestHeaders"); var iParamCounter = aRequestHeaders.length; var i; if (aRequestHeaders && sHeaderParameterName) { for (i = 0; i < iParamCounter; i++ ) { if (aRequestHeaders[i].name === sHeaderParameterName) { return new sap.m.UploadCollectionParameter({ name: aRequestHeaders[i].name, value: aRequestHeaders[i].value }); } } } else { if (aRequestHeaders) { for (i = 0; i < iParamCounter; i++) { aUcpRequestHeaders.push(new sap.m.UploadCollectionParameter({ name: aRequestHeaders[i].name, value: aRequestHeaders[i].value })); } } return aUcpRequestHeaders; } }; /** * @description Helper function for ascii encoding within header paramters * @param {string} * @returns {string} * @private */ UploadCollection.prototype._encodeToAscii = function (value) { var sEncodedValue = ""; for (var i = 0; i < value.length; i++) { sEncodedValue = sEncodedValue + value.charCodeAt(i); } return sEncodedValue; }; /** * @description Returns UploadCollectionItem based on the items aggregation * @param {sap.m.ListItemBase} listItem used to find the UploadCollectionItem * @returns {sap.m.UploadCollectionItem} The matching UploadCollectionItem * @private */ UploadCollection.prototype._getUploadCollectionItemByListItem = function(listItem) { var aAllItems = this.getItems(); for (var i = 0; i < aAllItems.length; i++) { if (aAllItems[i].getId() === listItem.getId().replace("-cli", "")) { return aAllItems[i]; } } return null; }; /** * @description Returns UploadCollectionItem based on the items aggregation * @param {string} uploadCollectionItemId used to find the UploadCollectionItem * @returns {sap.m.UploadCollectionItem} The matching UploadCollectionItem * @private */ UploadCollection.prototype._getUploadCollectionItemById = function(uploadCollectionItemId) { var aAllItems = this.getItems(); for (var i = 0; i < aAllItems.length; i++) { if (aAllItems[i].getId() === uploadCollectionItemId) { return aAllItems[i]; } } return null; }; /** * @description Returns an array of UploadCollection items based on the items aggregation * @param {sap.m.ListItemBase[]} listItems used to find the UploadCollectionItems * @returns {sap.m.UploadCollectionItem[]} The matching UploadCollectionItems * @private */ UploadCollection.prototype._getUploadCollectionItemsByListItems = function(listItems) { var aUploadCollectionItems = []; var aLocalUploadCollectionItems = this.getItems(); if (listItems) { for (var i = 0; i < listItems.length; i++) { for (var j = 0; j < aLocalUploadCollectionItems.length; j++) { if (listItems[i].getId().replace("-cli", "") === aLocalUploadCollectionItems[j].getId()) { aUploadCollectionItems.push(aLocalUploadCollectionItems[j]); break; } } } return aUploadCollectionItems; } return null; }; /** * @description Sets the selected value for elements in given array to state of given bSelected. Also handles List specific rules * @param {sap.m.ListItemBase[]} uploadCollectionItemsToUpdate to set selected value for * @param {boolean} selected value to set items to * @private */ UploadCollection.prototype._setSelectedForItems = function(uploadCollectionItemsToUpdate, selected) { //Reset all 'selected' values in UploadCollectionItems if (this.getMode() !== sap.m.ListMode.MultiSelect && selected) { var aUploadCollectionItems = this.getItems(); for (var j = 0; j < aUploadCollectionItems.length; j++) { aUploadCollectionItems[j].setSelected(false); } } for (var i = 0; i < uploadCollectionItemsToUpdate.length; i++) { uploadCollectionItemsToUpdate[i].setSelected(selected); } }; /** * Handles the selected event of UploadCollectionItem. * Used to synchronize the internal list with the given item. The ListItem has to be set to selected value too. * Otherwise the internal sap.m.List and the UploadCollectionItem aggregation are not in sync. * @param {object} oEvent Event for a selected item * @private */ UploadCollection.prototype._handleItemSetSelected = function(oEvent) { var oItem = oEvent.getSource(); if (oItem instanceof sap.m.UploadCollectionItem) { var oListItem = this._getListItemById(oItem.getId() + "-cli"); if (oListItem) { oListItem.setSelected(oItem.getSelected()); } } }; UploadCollection.prototype._handleSelectionChange = function(oEvent){ var oListItem = oEvent.getParameter("listItem"); var bSelected = oEvent.getParameter("selected"); var aUploadCollectionListItems = this._getUploadCollectionItemsByListItems(oEvent.getParameter("listItems")); var oUploadCollectionItem = this._getUploadCollectionItemByListItem(oListItem); if (oUploadCollectionItem && oListItem && aUploadCollectionListItems) { this.fireSelectionChange({ selectedItem : oUploadCollectionItem, selectedItems : aUploadCollectionListItems, selected : bSelected }); oUploadCollectionItem.setSelected(oListItem.getSelected()); } }; /** * @description Returns the sap.m.ListItem from the internal sap.m.List based on the id * @param {string} listItemId used to find the UploadCollectionItems * @returns {sap.m.ListItemBase} The matching UploadCollectionItems * @private */ UploadCollection.prototype._getListItemById = function(listItemId) { var aListItems = this._oList.getItems(); for (var i = 0; i < aListItems.length; i++) { if (aListItems[i].getId() === listItemId) { return aListItems[i]; } } return null; }; return UploadCollection; }, /* bExport= */ true);
/* * This file is part of the EcoLearnia platform. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * EcoLearnia v0.0.1 * * @fileoverview * This file includes definition of HapiResource. * * @author Young Suk Ahn Park * @date 2/15/15 */ var uuid = require('node-uuid'); var async = require('async'); var utils = require('../utils/utils'); var promiseutils = require('../utils/promiseutils'); var logger = require('../utils/logger'); var ContentHelper = require('./contenthelper').ContentHelper; var ContentKind = require('./contenthelper').Kind; var defaultProvider = require('./defaultprovider'); var contentitemmanager = require('./contentitemmanager'); // Declaration of namespace for internal module use var internals = {}; internals.managerInstance = null; internals.ContentNodeManager = function() { this.logger_ = logger.Logger.getLogger('ContentNodeManager'); this.contentNodeProvider = defaultProvider.createProvider('ContentNode', 'contentnode', { primaryKey: 'uuid'} ); this.contentItemManager = null; }; /** * Gets the contentItemManager */ internals.ContentNodeManager.prototype.getItemManager = function() { if (this.contentItemManager == null) { this.contentItemManager = contentitemmanager.getManager(); } return this.contentItemManager; } /** * Add a content node * @param contentItem * @param options * @returns {*} */ internals.ContentNodeManager.prototype.add = function(contentNode, options) { var self = this; var promise = promiseutils.createPromise(function(resolve, reject) { var promiseParent = function() { if (contentNode.parentUuid) { // Retrieve parent var parentNodeCriteria = { uuid: contentNode.parentUuid } return self.contentNodeProvider.find(parentNodeCriteria); } else { // Nothing to do, just return a proise and resolve it return promiseutils.createPromise( function(resolve, reject) { resolve(null); }); } }(); promiseParent.then(function(parentContentNodeModel) { var kind = ContentKind.ROOT; if (parentContentNodeModel) { kind = ContentKind.CONTAINER; // Reset items (just in case) contentNode.items = []; } ContentHelper.initForCreate(contentNode, null, parentContentNodeModel, kind); // Add the the new node as child return self.contentNodeProvider.add(contentNode) }) .then(function(newContentNodeModel) { resolve(newContentNodeModel); }) .catch(function(error) { reject(error); }); }.bind(this)); return promise; }; internals.ContentNodeManager.prototype.find = function(criteria, options) { //options.depth = 0; //options.fetchItems = false; //options.fetchAncestors = false; if (options) { return this.retrieve(criteria, options); } else { return this.contentNodeProvider.find(criteria); } }; internals.ContentNodeManager.prototype.findByPK = function(pk, options) { return this.contentNodeProvider.findByPK(pk, options); }; /** * @param {Map.<String, Object>} criteria - A map of criteria */ internals.ContentNodeManager.prototype.query = function(criteria, options) { return this.contentNodeProvider.query(criteria, options); }; internals.ContentNodeManager.prototype.update = function(criteria, resource, options) { return this.contentNodeProvider.update(criteria, resource, options); }; internals.ContentNodeManager.prototype.updateModel = function(model) { return this.contentNodeProvider.updateModel(model); }; /** * */ internals.ContentNodeManager.prototype.remove = function(criteria, options) { // @todo - Remove in the parent's return this.contentNodeProvider.remove(criteria, options); }; /** * Moves a node to another parent * PENDING * @param {string} uuid - the uuid of the node to move * @param {Object} to - {parent, position} */ internals.ContentNodeManager.prototype.changeLocation = function(uuid, to, options) { var self = this; var promise = promiseutils.createPromise(function(resolve, reject) { if (!to.parentUuid) { reject('BadRequest'); // REturn 400 } self.findByPK(uuid, {fetchAncestors: true}) .then(function(content) { var origParentModel; // Find the original parent self..findByPK(content.parentUuid) .then(function(parentNodeModel) { origParentModel = parentNodeModel; // @todo - change it's position within it's parent if (content.parentUuid === to.parentUuid) { resolve(content); } else { return self.findByPK(to.parentUuid); } }) .then(function(newParentNodeModel) { // Attach to the new parent //internals.ContentNodeManager.insertSubnodeEntry(newParentNodeModel, content); return self.getNodeManager().updateModel(newParentNodeModel); }) .then(function(updatedNewParentNodeModel) { // Update content's parent reference content.parent = updatedNewParentNodeModel._id; content.parentUuid = updatedNewParentNodeModel.uuid; delete content._id;; // otherwise MongoDB will complain return self.update({uuid: content.uuid}, content); }) .then(function(updatedContentModel) { // Detach from original parent //internals.ContentNodeManager.deleteItemEntry(origParentModel, content.uuid); return self.updateModel(origParentModel); }) .then(function(updatedOrigParentModel) { // Retrieve new ancestors return self.retrieveAncestors(content, {}, 0); }) .then(function(updatedContent) { // Return the content with new ancestors resolve(updatedContent); }); /* Is this necessary? .catch(function (error) { });*/ }) .catch(function (error) { reject(error); }); }.bind(this)); return promise; }; /** * retrieve * Retrieves a node with it's descendants * * @param {Object} criteria - Criteria * @param {Object} options - * options.depth - Fetch depth * options.fetchItems - Whether or not to fetch items * options.fetchAncestors - Whether or not to fetch ancestors * * @return {models.ContentNode} - The found node with it's descendants */ internals.ContentNodeManager.prototype.retrieve = function(criteria, options) { var promise = promiseutils.createPromise(function(resolve, reject) { this.contentNodeProvider.find(criteria) .then(function(contentNodeModel) { // Recursive retrieval if (contentNodeModel) { var contentNode = contentNodeModel.toJSON(); // @todo synch both calls // Retrieve descendants this.retrieveRecursive_(contentNode, options, 0) .then(function(result){ // Retrieve ancestors if applicable if (options && options.fetchAncestors) { this.retrieveAncestors(result, options, 0) .then(function(result){ resolve(result); }) .catch(function(error) { reject(error); }); } else { resolve(result); } }.bind(this)) .catch(function(error) { reject(error); }); } else { // @todo - change to Exception object resolve(null); } }.bind(this)) .catch(function(error) { reject(error); }); }.bind(this)); return promise; }; /** * retrieveAncestors * Recursively retrieves a node's ancestors. * The parent property is replaced with the actual parent object. * * @param {Object} contentNode - contentNode to retrieve the ancestors * @param {Object} options - * options.depth - Fetch depth * options.fetchItems - Whether or not to fetch items * * @return {Promise} - The found node with it's descendants * success: {ContentNode} - same contentNode reference with ancestors */ internals.ContentNodeManager.prototype.retrieveAncestors = function(contentNode, options, level) { var promise = promiseutils.createPromise(function(resolve, reject) { if (contentNode && contentNode.parentUuid) { this.contentNodeProvider.findByPK(contentNode.parentUuid) .then(function(parentContentNodeModel) { // Recursive retrieval if (parentContentNodeModel) { // Replace the parent (originally uuid) to the actual object var parentContentNode = parentContentNodeModel.toJSON(); contentNode.__parentObject = parentContentNode; this.retrieveAncestors(parentContentNode, options, level + 1) .then(function(result){ resolve(contentNode); }) .catch(function(error) { reject(error); }); } else { // @todo - change to Exception object reject("Parent NotFound"); } }.bind(this)) .catch(function(error) { reject(error); }); } else { resolve(contentNode); } }.bind(this)); return promise; }; /** * retrieveRecursive_ * Recursively retrieves a node's descendants * * @param {Object} contentNode - contentNode to retrieve the decendants * @param {Object} options - * options.depth - Fetch depth * options.fetchItems - Whether or not to fetch items * @param {Object} level - The current level * * @return {models.ContentNode} - The found node with it's descendants */ internals.ContentNodeManager.prototype.retrieveRecursive_ = function(contentNode, options, level) { var self = this; contentNode.body.subnodes = []; // Populate items var promise = promiseutils.createPromise(function(resolve, reject) { // Serialise the processing of child items and child contentNodeSchema // using async.series var operationsToSerialize = []; // Optionally include items if (options && options.fetchItems) { operationsToSerialize.push( // First serial function: load items function processItems(seriesCallback) { if (contentNode.body.items && contentNode.body.items.length > 0) { function processEachItem(contentItemEntry, eachCallback) { // 1. Retrieve the item (without the ancestor) self.getItemManager().findByPK(contentItemEntry.itemUuid, {fetchAncestors: false} ) .then(function(contentItemModel){ if (contentItemModel) { contentItemEntry.item = contentItemModel; eachCallback(); } else { //throw new Error('NotFound'); // Removing item from node // @todo - update the node? internals.ContentNodeManager.deleteItemEntry(contentNode, contentItemEntry.itemUuid); eachCallback(); } }) .catch(function(error) { eachCallback(error); }); }; // add items to assignmentNodeModel async.each(contentNode.body.items, processEachItem, function(err) { if (err) { seriesCallback(err, null); } else { // All items retrieved, callback to async.series seriesCallback(null, contentNode); } }); } else { // No items registered, callback to async.series seriesCallback(null, contentNode); } } ); } if (options.depth && options.depth > level) { // Serial function: load subNodes operationsToSerialize.push( function processSubNodes(seriesCallback) { var subNodesCriteria = { parent: contentNode._id }; self.query(subNodesCriteria) .then(function(subNodeModels){ if (subNodeModels) { function processEachNode(contentSubNodeModel, eachCallback) { var contentSubNode = contentSubNodeModel.toJSON(); contentNode.body.subnodes.push(contentSubNode); // 4. Recurse self.retrieveRecursive_(contentSubNode, options, level + 1) .then(function(){ eachCallback(); }) .catch(function(error) { eachCallback(error); }); }; // add items to assignmentNode async.each(subNodeModels, processEachNode, function(err) { if (err) { seriesCallback(err, null); } else { // All subnodes retrieved, callback to async.series seriesCallback(null, contentNode); } }); } else { // No subnodes found, callback to async.series seriesCallback(null, contentNode); } }) // contentNodeProvider.query .catch(function(error) { reject(error); }); } ); } async.series(operationsToSerialize, // Async.series result function(err, results){ if (err) { reject(err); } else { resolve(contentNode); } }); }.bind(this)); return promise; }; /** * Insert an item to the node * @param {number} position - 0-based index for the postion to insert */ internals.ContentNodeManager.insertItemEntry = function(node, itemModel, position) { // Check for duplicate // @todo use some() for(var i=0; i < node.body.items.length; i++) { if (node.body.items[i].itemUuid === itemModel.uuid) { return node } } var newChild = { type: 'item', itemUuid: itemModel.uuid, item: itemModel._id, difficulty: 0.5 // @todo } if (position) { node.body.items.splice(position, 0, newChild); } else { node.body.items.push(newChild); } return node; } /** * Deletes an item from node * @static * * @param {string} itemUuidToDelete - The uuid of the item to delete * * @returns {boolean} - True if found and deleted, false otherwise */ internals.ContentNodeManager.deleteItemEntry = function(node, itemUuidToDelete) { for(var i=0; i < node.body.items.length; i++) { if (node.body.items[i].itemUuid === itemUuidToDelete) { node.body.items.splice(i, 1); return true; } } return false; } /** * Factory method */ internals.getManager = function() { if (!internals.managerInstance) { internals.managerInstance = new internals.ContentNodeManager(); } return internals.managerInstance; } module.exports.ContentNodeManager = internals.ContentNodeManager; module.exports.getManager = internals.getManager;
/* * mongo-edu * * Copyright (c) 2014 Przemyslaw Pluta * Licensed under the MIT license. * https://github.com/przemyslawpluta/mongo-edu/blob/master/LICENSE */ var request = require('request'), cheerio = require('cheerio'), ProgressBar = require('progress'), _ = require('lodash'), videoHandler = require('./videos'), coursewareHandler = require('./courseware'); var jar = request.jar(), host = 'https://university.mongodb.com'; function addCookies(cookies, url) { 'use strict'; _.each(cookies, function cookies(cookie) { jar.setCookie(cookie, url + '/login'); }); } module.exports = { init: function init(opt, argv, callback) { 'use strict'; var url = host, bar = new ProgressBar('>'.magenta + ' Searching [:bar] :percent', { complete: '=', incomplete: ' ', width: 20, total: 5 }), CSRFTokenCookie = '', login = function login(token) { request({ uri: url + '/login', method: 'POST', jar: jar, headers: { 'X-CSRFToken': token[0].split('=')[1] }, form: { 'email': opt.user, 'password': opt.password } }, function post(err, res, body) { if (err !== null) { return callback(err, null); } if (res.statusCode === 200) { var status = JSON.parse(body); if (status.success !== true) { return callback(new Error(status.value)); } bar.tick(); return checkCourses(bar); } callback(new Error(res.statusCode)); }); }, checkCourses = function checkCourses(bar) { bar.tick(); request({ url: url + '/dashboard', jar: jar }, function get(err, res, body) { if (err !== null) { return callback(err, null); } bar.tick(); if (res.statusCode === 200) { var list = [], $ = cheerio.load(body), current = $('section.my-courses-courses').children(), link = $(current).filter('.media').children().find('h3').children(); bar.tick(); $(link).each(function each(i, item) { list.push({ name: $(item).text(), value: url + $(item).attr('href').replace(/about|info|syllabus/g, '') + ((!argv.h) ? (argv.cw || argv.cwd) ? 'courseware' : 'course_wiki' : 'syllabus') }); }); bar.tick(); callback(null, list); } }); }; request(url, function (err, res) { if (err !== null) { return callback(err, null); } if (res.statusCode === 200) { addCookies(res.headers['set-cookie'], url); CSRFTokenCookie = res.headers['set-cookie'][0].split(';'); return login(CSRFTokenCookie); } callback(new Error(res.statusCode)); }); }, getList: function getList(opt, argv, callback) { 'use strict'; request({ url: opt.url, jar: jar, headers: { 'Referer' : opt.url.replace('course_wiki', 'syllabus'), }}, function get(err, res, body) { if (err !== null) { return callback(err, null); } if (res.statusCode === 404) { return callback(null, [], true); } if (res.statusCode === 200) { var list = [], getCourses = [], $ = cheerio.load(body), options = (!argv.h)? 'Video|playlist' : 'Handout'; if (!argv.h) { if (argv.cw || argv.cwd) { return coursewareHandler.findDetails($, callback); } $('div.wiki-article p').children().filter('a').map(function map(i, item) { var current = $(item); if (current.text().match(options)) { list.push({ href: current.attr('href'), text: current.text() }); } }); getCourses = _.filter(list, function map(item) { if (item.href.match(/(wiki\/M101|wiki\/M102|wiki\/C100|wiki\/M202|wiki\/list-youtube-links|playlist\?list|view_play_list)/)) { return item; } }); return callback(null, _.map(getCourses, function map(item) { return { name: item.text, value: item.href }; })); } else { $('tbody tr').map(function map(i, item) { var current = $(item), text = current.children().first().text(), href = $(current.find('a')).attr('href'); if (href) { list.push({ name: text, value: host + $(current.find('a')).attr('href') }); } }); if (list.length) { list.unshift({name: 'All', value: 'all', checked: true}, {name: 'Cancel', value: 'cancel'}); } return callback(null, list, true); } } }); }, listVideos: function listVideos(opt, argv, callback) { 'use strict'; var videos = [], list, $, current; if (argv.cw || argv.cwd) { return coursewareHandler.filterVideos(opt, host, jar, argv, callback); } if (opt.url.match(/playlist\?list|view_play_list/)) { return videoHandler.listVideosFromPlaylist(opt, argv, callback); } request({ url: opt.url, jar: jar }, function get(err, res, body) { if (err !== null) { return callback(err, null); } if (res.statusCode === 200) { $ = cheerio.load(body); list = $('div.wiki-article'); current = list.find('code').text(); if (current.match(/http:\/\/|https:\/\//)) { videos = _.compact(current.split('\n')); } if (!videos.length) { list.children('p').children().each(function each(i, item) { var current = $(item), href = current.attr('href'); if (href && href.match(/http:\/\/|https:\/\//)) { videos.push(href); } }); } return callback(null, videos); } callback(new Error(res.statusCode)); }); }, checkProxy: function checkProxy(target, callback) { 'use strict'; request(target, function get(err, response) { if (err !== null) { return callback(err); } if (response.statusCode === 200) { var stack = ''; if (response.headers.server) { stack = 'Proxy Server: '.bold + response.headers.server.cyan + ' '; } if (response.headers['x-powered-by']) { stack += 'Powered-by: '.bold + response.headers['x-powered-by'].cyan + ' '; } stack.trim(); if (stack === '') { stack = target; } return callback(null, stack); } callback(new Error('Server Response: '.red + response.statusCode)); }); } };
import test from 'tape'; import { and, or, not } from './'; import { $lt, $mod } from './'; test('Logic', t => { t.plan(1); const predicate = and($lt(15), not($lt(5)), or($mod(2), $mod(3))); const values = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]; const matches = values.filter(predicate); t.deepLooseEqual(matches, [ 6, 8, 9, 10, 12, 14 ], 'filter: less than 15, and not less than 5, and divisible by either 2 or 3') });
$(document).ready( function() { document.getElementById('headerText').innerHTML = '<h1>Live</h1>'; var line = 0; var outF = false; var liveAgainToggle = true; $('#story').click ( function() { if(outF) { $('.lineOne').textillate('out'); } else { if(line < story.length) { $('.lineOne').find('.texts li:first').text(story[line]); $('.lineOne').textillate('start'); } else { $('.lineOne').find('.texts li:first').text(""); $('.lineOne').textillate('start'); } } if(line > 0) { if(outF) { $('.lineTwo').textillate('out'); } else { if(line < story.length) { $('.lineTwo').find('.texts li:first').text(story[line-1]); $('.lineTwo').textillate('start'); } else { $('.lineTwo').find('.texts li:first').text(""); $('.lineTwo').textillate('start'); } } if(line > 1){ if(outF) { $('.lineThree').textillate('out'); } else { if(line < story.length) { $('.lineThree').find('.texts li:first').text(story[line-2]); $('.lineThree').textillate('start'); } else { $('.lineThree').find('.texts li:first').text(""); $('.lineThree').textillate('start'); } } if(line > 2) { if(outF) { $('.lineFour').textillate('out'); } else { if(line < story.length) { $('.lineFour').find('.texts li:first').text(story[line-3]); $('.lineFour').textillate('start'); } else { $('.lineFour').find('.texts li:first').text(""); $('.lineFour').textillate('start'); } } } } } if(outF) { outF = false; line = line + 1; } else { outF = true; } if(line === story.length) { $('.titleText').textillate('out'); if(liveAgainToggle) { $('#liveAgain').toggle(); $('.reload').find('.texts li:first').text('Live Again'); $('.reload').textillate('start'); liveAgainToggle = false; } } if(line >= story.length) { document.getElementById('liveAgain').innerHTML = '<a href="#" onclick="location.reload()"><h2 class="reload">Live Again</h2></a>' } }); }); // For Textillate.JS $(function () { $('.titleText').textillate({ in: { effect: 'fadeInLeft', delayScale: 5, delay: 100, sync: false, reverse: true}, out: {effect: 'fadeOutLeft', delayScale: 5, delay: 100, sync: false, reverse: true}, type: 'char' }); $('.lineOne').textillate({ in: { effect: 'fadeInDown', delayScale: 5, delay: 100, sync: true, reverse: false}, out: {effect: 'fadeOutDown', delayScale: 5, delay: 100, sync: true, reverse: false}, type: 'word' }); $('.lineTwo').textillate({ in: { effect: 'fadeInDown', delayScale: 5, delay: 100, sync: true, reverse: false}, out: {effect: 'fadeOutDown', delayScale: 5, delay: 100, sync: true, reverse: false}, type: 'word' }); $('.lineThree').textillate({ in: { effect: 'fadeInDown', delayScale: 5, delay: 100, sync: true, reverse: false}, out: {effect: 'fadeOutDown', delayScale: 5, delay: 100, sync: true, reverse: false}, type: 'word' }); $('.lineFour').textillate({ in: { effect: 'fadeInDown', delayScale: 5, delay: 100, sync: true, reverse: false}, out: {effect: 'fadeOutDown', delayScale: 5, delay: 100, sync: true, reverse: false}, type: 'word' }); $('.reload').textillate({ in: { effect: 'fadeIn', delayScale: 5, delay: 100, sync: true, reverse: false}, type: 'word' }); });
(function(w, Raphael){ 'use strict'; var wW = window.innerWidth, wH = window.innerHeight, paper, shots; // set of shots function _initDemo(){ paper = Raphael(document.getElementById('paper'), wW, wH); //Create Paper _createRandomShots(300); // Create shots } function _createRandomShots(nbOfShots){ paper.setStart(); for (var i = 0; i < nbOfShots; i++) { var randomX = Math.random()*wW >> 0, randomY = Math.random()*wH >> 0, randomSucces = Math.round(Math.random()*1) === 1, shot; if( randomSucces ){ shot = paper.circle(randomX, randomY, 50); } else{ shot = paper.path('M-22,-6h16v-16h12v16h16v12h-16v16h-12v-16h-16z'); shot.attr({ transform: 't'+randomX+','+randomY }); } } shots = paper.setFinish(); // Get all element added to paper since last 'setStart' } // Wait loading w.onload = function(){ _initDemo(); }; })(window, Raphael);
import Remarkable from 'remarkable'; import hljs from 'highlight.js'; const remarkableInstance = new Remarkable({ highlight: (str) => { try { return hljs.highlight('javascript', str).value; } catch(err) { console.log(err); } } }); function decorateString(str) { return '```\n' + str + '```'; } function renderFromMarkdown(md) { return remarkableInstance.render(md); } export default function parser(str) { return renderFromMarkdown(decorateString(str)).trim(); }
require('./helper') module.exports = PageObject /** * PageObject * @param driver * @param repoUrl * @constructor */ function PageObject(driver, repoUrl) { this.driver = driver this.one = driver.findElement.bind(driver) this.all = driver.findElements.bind(driver) this.repoUrl = repoUrl } PageObject.prototype = { getUrl: function *() { return yield this.driver.getCurrentUrl() }, setUrl: function *(url) { var driver = this.driver driver.get(url) yield driver.wait(function () { return driver.getCurrentUrl().then(function (_url) { return url === _url }) }, 5000) yield sleep(1000) // since 1.7.2, Octotree uses longer timeout for loc change }, close: function *() { yield this.driver.quit() }, reset: function *() { yield this.setUrl(this.repoUrl) }, refresh: function *() { yield this.driver.navigate().refresh() yield sleep(100) }, toggleSidebar: function *() { yield this.toggleButton.click() yield sleep(200) // transition }, toggleOptsView: function *() { yield this.optsButton.click() }, isSidebarShown: function *() { var hasCssClass = yield this.driver.isElementPresent($css('html.octotree')) var btnRight = yield this.toggleButton.getCssValue('right') return hasCssClass && btnRight === '5px' }, isSidebarHidden: function *() { var hasCssClass = yield this.driver.isElementPresent($css('html.octotree')) var btnRight = yield this.toggleButton.getCssValue('right') return !hasCssClass && btnRight === '-35px' }, saveSettings: function *() { yield this.saveButton.click() yield sleep(500) // transition + async storage }, nodeFor: function (path) { return this.one($id('octotree' + path)) }, clickNode: function (node) { // Firefox driver can't click li, has to click li a instead. return node.findElement($css('a')).click() }, childrenOfNode: function (node) { return node.findElements($css('.jstree-children li')) }, isNodeSelected: function (node) { return node.findElement($css('.jstree-wholerow-clicked')).isDisplayed() }, isNodeOpen: function *(node) { var classes = yield node.getAttribute('class') return ~classes.indexOf('jstree-open') } } // UI elements var controls = { ghBreadcrumb : '.breadcrumb .final-path', ghSearch : '.js-site-search-field', helpPopup : '.popup', toggleButton : '.octotree_toggle', sidebar : '.octotree_sidebar', branchLabel : '.octotree_header_branch', treeView : '.octotree_treeview', treeHeaderLinks : '.octotree_header_repo a', treeNodes : '.jstree .jstree-node', optsButton : '.octotree_opts', optsView : '.octotree_optsview', tokenInput : '//input[@data-store="TOKEN"]', hotkeysInput : '//input[@data-store="HOTKEYS"]', rememberCheck : '//input[@data-store="REMEMBER"]', nonCodeCheck : '//input[@data-store="NONCODE"]', saveButton : '.octotree_optsview .btn', errorView : '.octotree_errorview', errorViewHeader : '.octotree_errorview .octotree_view_header' } Object.keys(controls).forEach(function (name) { var selector = controls[name] , met = name.indexOf('s') === name.length - 1 ? 'all' : 'one' , sel = selector.indexOf('//') === 0 ? $xpath : $css , cond = sel(selector) Object.defineProperty(PageObject.prototype, name, { get: function () { return new WebElementPromiseWrapper(this.driver, this[met](cond), cond) } }) }) /** * WebElementPromiseWrapper * @param driver * @param wep * @param cond * @constructor */ function WebElementPromiseWrapper(driver, wep, cond) { this.driver = driver this.wep = wep this.cond = cond } WebElementPromiseWrapper.prototype.then = function () { return this.wep.then.apply(this.wep, arguments) } Object.keys(webdriver.WebElement.prototype).forEach(function (prop) { if (_.isFunction(webdriver.WebElement.prototype[prop])) { WebElementPromiseWrapper.prototype[prop] = function *() { var driver = this.driver , wep = this.wep , cond = this.cond yield driver.wait(function () { return driver.isElementPresent(cond) // TODO: vary condition per action }, 5000) var elm = yield wep return yield elm[prop].apply(elm, arguments) } } })
function Require(resolve, modules, requiringModules, initializedModules, modulePath) { this.resolve = resolve; return function require(path) { var resolved = resolve(path); if(requiringModules[resolved] && !initializedModules[resolved] && console && console.warn) { console.error('node2browser error: circular dependency detected.\n' + 'module ' + modulePath + ' is requiring ' + resolved + ' and vice versa.'); return undefined; } requiringModules[modulePath] = true; initModule(resolved); delete requiringModules[modulePath]; return modules[resolved]; }; } module.exports = Require;
import React from 'react'; import PropTypes from 'prop-types' import links from 'app/utils/Links' import {browserHistory} from 'react-router' import shouldComponentUpdate from 'app/utils/shouldComponentUpdate' export default class Link extends React.Component { static propTypes = { // HTML properties href: PropTypes.string, title:PropTypes.string } constructor(props) { super() const {href} = props this.shouldComponentUpdate = shouldComponentUpdate(this, 'Link') this.localLink = href && links.local.test(href) this.onLocalClick = e => { e.preventDefault() browserHistory.push(this.props.href) } } render() { const {props: {href, children, title}, onLocalClick} = this if(this.localLink) return <a onClick={onLocalClick}>{children}</a> return <a target="_blank" href={href} title={title}>{children}</a> } }
import { triggerAnims } from '@bolt/components-animate/utils'; /** * Event handler for click on block region, only fires * on icon or title click. Expands the block content. * Only works on mobile. To configure this, adjust mediaQuery. * * @param e {Event} */ const handleBlockTitleMobileAccordionClick = async e => { // @TODO replace with theme token. const mediaQuery = '(max-width: 1200px)'; const expandedClass = 'c-pega-wwo__block-expanded'; const animateClass = 'c-pega-wwo__block-contents'; const targetIsIcon = e.target.nodeName === 'BOLT-ICON'; const targetIsTitle = e.target.classList.contains('c-pega-wwo__block-title'); const targetIsToggler = targetIsIcon || targetIsTitle; const isMobile = window.matchMedia(mediaQuery).matches; if (!targetIsToggler || !isMobile) { return; } // @TODO `closest()` may not be polyfilled/transpiled on IE. const parentBlock = e.target.closest('.c-pega-wwo__block'); const targetIsExpanded = parentBlock.classList.contains(expandedClass); if (targetIsExpanded) { parentBlock.classList.remove(expandedClass); parentBlock.querySelector(`.${animateClass}`).triggerAnimOut(); return; } const parentRegion = parentBlock.parentElement; const otherPreviouslyExpanded = parentRegion.querySelector( `.${expandedClass}`, ); if (otherPreviouslyExpanded) { otherPreviouslyExpanded.classList.remove(expandedClass); await triggerAnims({ animEls: [otherPreviouslyExpanded.querySelector(`.${animateClass}`)], stage: 'OUT', }); } parentBlock.classList.add(expandedClass); parentBlock.querySelector(`.${animateClass}`).triggerAnimIn(); }; export default handleBlockTitleMobileAccordionClick;
module.exports = [ 'weekday', 'summer', 'winter', 'autumn', 'some day', 'one day', 'all day', 'some point', 'eod', 'eom', 'standard time', 'daylight time', ]
import Humps from 'humps'; import { ApiUrls } from './api-urls'; const getActionTypes = (actions, payload) => ( actions instanceof Array ? actions.map((action) => ({ type: action, ...payload })) : { type: actions, ...payload } ); export const fetchDispatcher = (beforeAction, afterAction, url) => (dispatch) => { const beforeActionTypes = getActionTypes(beforeAction); dispatch(beforeActionTypes); return $.ajax({ url, type: 'GET', contentType: 'application/json', }).then((response) => { if (response.status === 'OK') { const afterActionTypes = getActionTypes(afterAction, { response }); dispatch(afterActionTypes); } }); }; export const putDispatcher = (beforeAction, afterAction, url, params) => (dispatch) => { const beforeActionTypes = getActionTypes(beforeAction); dispatch(beforeActionTypes); return $.ajax({ url, type: 'PUT', contentType: 'application/json', data: JSON.stringify(params), }).then((response) => { if (response.status === 'OK') { const afterActionTypes = getActionTypes(afterAction, { response }); dispatch(afterActionTypes); } }); }; export const createMessage = () => ( $.ajax({ url: ApiUrls.Messages, type: 'POST', contentType: 'application/json', }) ); export const getMessages = () => ( $.ajax({ url: ApiUrls.Messages, type: 'GET', contentType: 'application/json', }) ); export const getMessage = (id) => ( $.ajax({ url: ApiUrls.ShowMessage.getUrl({ id }), type: 'GET', contentType: 'application/json', }) ); export const createWidget = (messageId, widget) => ( $.ajax({ url: ApiUrls.Widgets, type: 'POST', contentType: 'application/json', data: JSON.stringify({ message_id: messageId, widget, }), }) ); export const updateWidgetAjax = (widgetId, payload) => ( $.ajax({ url: ApiUrls.UpdateWidgets.getUrl({ id: widgetId }), type: 'PUT', contentType: 'application/json', data: JSON.stringify({ payload, }), }) ); export const removeWidgetAjax = (widgetId) => ( $.ajax({ url: ApiUrls.UpdateWidgets.getUrl({ id: widgetId }), type: 'DELETE', contentType: 'application/json', }) ); export const createSharedMessage = (messageId) => ( $.ajax({ url: ApiUrls.SharedMessages, type: 'POST', contentType: 'application/json', data: JSON.stringify(Humps.decamelizeKeys({ messageId, })), }) );
'use strict'; // MODULES // var partial = require( './partial.js' ); // PMF // /** * FUNCTION: pmf( out, arr, m, n, k ) * Evaluates the probability mass function (PMF) for a Hypergeometric distribution with number of white balls in urn `m` and number of black balls in urn `n` and number of draws `k` for each array element. * * @param {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} out - output array * @param {Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} arr - input array * @param {Number} m - number of white balls in urn * @param {Number} n - number of black balls in urn * @param {Number} k - number of draws * @returns {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} output array */ function pmf( y, x, m, n, k ) { var len = x.length, fcn, i; fcn = partial ( m, n, k ); for ( i = 0; i < len; i++ ) { y[ i ] = fcn( x[ i ] ); } return y; } // end FUNCTION pmf() // EXPORTS // module.exports = pmf;
var formbuilder = new function() { this.buildCommandForm = function(obj, commandDefinition) { var props = commandDefinition.commandModel.commandProperties; for(var a = 0; a < props.length; a++) { var prop = props[a]; switch(prop.propertyType) { case "SELECT": break; case "SLIDER": break; } } } }
import { Selector } from 'testcafe'; class ProjectsPage { constructor() { this.pageId = '#projects-page'; this.pageSelector = Selector(this.pageId); } /** Checks that this page is currently displayed. */ async isDisplayed(testController) { await testController.expect(this.pageSelector.exists).ok(); } /** Checks that the current page has at least nine interests on it. */ async hasDefaultProjects(testController) { const cardCount = Selector('.ui .card').count; await testController.expect(cardCount).gte(4); } } export const projectsPage = new ProjectsPage();
var request = require('supertest'); var assert = require('assert'); var should = require('should'); describe('Validate', function() { request = request(process.env.HOST || 'http://localhost:5000'); describe('combo', function() { it('should return true for a valid type and size', function(done) { request.get('/validate?image=http%3A%2F%2Florempixel.com%2F40%2F20%2F&mimetype=image/jpeg&min-height=10').end(function(err, res) { if (err) { throw err; } res.body.valid.should.eql(true); res.body.info.should.have.property('size'); res.body.info.should.have.property('type'); done(); }); }); it('should return false for an invalid size and a valid type', function(done) { request.get('/validate?image=http%3A%2F%2Florempixel.com%2F40%2F20%2F&mimetype=image/jpeg&max-height=10').end(function(err, res) { if (err) { throw err; } res.body.valid.should.eql(false); res.body.invalid.should.have.property('size'); done(); }); }); it('should return false for an invalid size and an invalid type', function(done) { request.get('/validate?image=http%3A%2F%2Florempixel.com%2F40%2F20%2F&mimetype=image/png&max-height=10').end(function(err, res) { if (err) { throw err; } res.body.valid.should.eql(false); res.body.invalid.should.have.property('size'); res.body.invalid.should.have.property('type'); done(); }); }); }); });
import * as path from "path"; const electronConfig = { node: { __filename: false, __dirname: false }, target: "electron-renderer", // important entry: { electron: ["babel-polyfill", "./src/main/index.js"] }, output: { filename: "[name].js", chunkFilename: "[id].js", path: path.resolve(__dirname, "../app/dist"), publicPath: "./", libraryTarget: "commonjs" }, resolve: { extensions: [".js"] }, externals: ["keytar"], module: { rules: [ { test: /\.js$/, use: [ { loader: "babel-loader", options: { presets: [["env", { targets: "node" }]] } } ], exclude: /node_modules/ } ] } }; export default electronConfig;
/* Import project dependencies if ( importing via node_modules ) { import thing from 'thing' } else if ( importing es5 ) { import * as thing from 'thing' } The webpack.ProvidePlugin (webpack.config.js) allows us to declare ['jquery', '$'] as global variables. Essentially, jQuery is built in. */ // Common helper scripts for projects import * as deviceCheck from './scripts/app_helpers/deviceCheck'; import * as jumpLinkFix from './scripts/app_helpers/jump-link-fix'; // // From here down are test scripts for testing this task runner. // Delete everything from here down to customize your own project. // // example of importing a npm installed script // import * as selectize from 'selectize'; const es6 = 'ES6 is working.'; const isJqueryWorking = 'With global access to jQuery.'; console.log(es6); $('.js-yo').text(isJqueryWorking); // example of calling the selectize script // that was imported above // $('.selectize').selectize();
//index.js import dian from '../../dian/index'; //获取应用实例 var app = getApp(); Page( { data: { userInfo: {}, haveMsg : false }, //设置处理函数 setting: function() { wx.navigateTo( { url: '../settingdetail/settingdetail' }) }, toMoney: function () { wx.navigateTo({ url: '../myfile/money/money' }) }, toBuyList: function () { wx.navigateTo({ url: '../myfile/buycodelist/buycodelist' }) }, toPubMarket: function () { wx.navigateTo({ url: '../myfile/pubmarketlist/pubmarketlist' }) }, toPubCode: function () { wx.navigateTo({ url: '../myfile/pubcodelist/pubcodelist' }) }, toMsgList: function () { wx.navigateTo({ url: '../myfile/msglist/msglist' }) }, toAbout: function () { wx.navigateTo({ url: '../myfile/about/about' }) }, checkNewMsg: function () { var that = this; dian.request({ loading: true, url: '/xcx/front/msg/checkNewMsg', method: 'POST', success: function (res) { console.log("data:" + res.data.data) if (res.data.data == '1') { //存在未读消息 that.setData({ haveMsg: true }) } else if (res.data.data == '0') { //不存在未读消息 that.setData({ haveMsg: false }) } } }); }, onShareAppMessage: function (res) { if (res.from === 'button') { // 来自页面内转发按钮 console.log(res.target) } return { title: '最专业的小程序外包市场!', path: '/pages/main/main', success: function (res) { // 转发成功 wx.showToast({ title: '分享成功', icon: 'success', duration: 2000 }) }, fail: function (res) { // 转发失败 wx.showToast({ title: '取消分享', icon: 'success', duration: 2000 }) } } }, goToShare: function() { Page.onShareAppMessage() }, settingBack: function () { wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function() { var that = this this.setData({ userInfo: app.globalData.userInfo }) }, onShow: function () { // 页面显示 console.log("onShow..."); this.checkNewMsg() }, onReady: function () { wx.setNavigationBarTitle({ title: '我的' }) } })
var React = require('react'); var ReactNative = React; ReactNative.StyleSheet = { create: function(styles) { return styles; } }; module.exports = ReactNative;
'use strict'; var Button = require('streamhub-ui/button'); var inherits = require('inherits'); var ShareCommand = require('streamhub-share/share-command'); /** * * [opts] {Object=} * [opts.command] {Command=} Command in place of the default. * [opts.content] {Content=} Content to share. Can be set later. */ var ShareButton = function (opts) { opts = opts || {}; opts.className = opts.className || 'content-share'; opts.label = opts.label || 'Share'; var cmd = opts.command; if (!cmd) { cmd = new ShareCommand(opts); } Button.call(this, cmd, opts); cmd.setPositionView(this); } inherits(ShareButton, Button); ShareButton.prototype.elClassPrefix = 'lf'; ShareButton.prototype.elTag = 'button'; ShareButton.prototype.template = function () { return '<button>' + this._label + '</button>'; }; ShareButton.prototype.setContent = function (content) { this._command.setContent && this._command.setContent(content); }; module.exports = ShareButton;
/*jslint indent: 2, maxlen: 120, browser: true, todo: true*/ /*global requirejs, require, define, console*/ requirejs.config({ paths: { 'bootstrap': '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min', 'bootstrap-datepicker': '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.2.0/js/bootstrap-datepicker.min', 'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min', 'jquery-ui': '//code.jquery.com/ui/1.10.3/jquery-ui' }, shim: { 'bootstrap': ['jquery'], 'boostrap-datepicker': ['bootstrap'], 'jquery-ui': ['jquery'] } }); define(function (require) { 'use strict'; require('bootstrap'); require('jquery-ui'); var show_msg = function (status, msg) { $('#flash') .removeClass('alert-danger alert-success') .addClass('alert-' + status) .find('.msg') .text(msg) .end() .removeClass('hidden').show(); }; $('#flash .close').click(function () { $(this).closest('.alert').fadeOut(); }); $('#appt-date') .datepicker({ defaultDate: 1, minDate: 1, maxDate: '+7d' }); $('.modal').on('show.bs.modal', function () { $(this).find('form')[0].reset(); }).on('shown.bs.modal', function () { $(this).find('.form-control:eq(0)').focus().end(); }); $('#make-appointment').on('show.bs.modal', function () { $('#appt-date') .datepicker('setDate', '+1d'); }).find('input').blur(function () { var $this = $(this), $item = $this.closest('.form-group'); $item.removeClass('has-error'); if ('' === $this.val()) { $item.addClass('has-error'); } }).end().find('form').submit(function (e) { e.preventDefault(); // don't actually submit the form var $this = $(this); $this.find('.form-group').removeClass('has-error'); $this.find('input').each(function () { if ('' === $(this).val().trim()) { $(this) .closest('.form-group') .addClass('has-error') .end(); }//end if });//end .each if ($this.find('.has-error').length) { $this.find('.has-error input:eq(0)').focus(); return false; }//end if: did not continue $.post($this.attr('action'), $this.serialize()).fail(function () { show_msg('danger', 'There was a problem. Please send an email.'); $this.closest('.modal').modal('hide'); }).done(function (result) { if ('ok' === result.status) { show_msg('success', 'Your request has been submitted.'); } else { show_msg('danger', 'There was a problem. Please send an email.'); }//end if: updated message $this.closest('.modal').modal('hide'); }); return false; }).end(); $('#get-directions .btn-primary').click(function () { var $this = $(this); $this.closest('.modal').modal('hide'); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _without2 = require('lodash/without'); var _without3 = _interopRequireDefault(_without2); var _each2 = require('lodash/each'); var _each3 = _interopRequireDefault(_each2); var _isNil2 = require('lodash/isNil'); var _isNil3 = _interopRequireDefault(_isNil2); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _lib = require('../../lib'); var _BreadcrumbDivider = require('./BreadcrumbDivider'); var _BreadcrumbDivider2 = _interopRequireDefault(_BreadcrumbDivider); var _BreadcrumbSection = require('./BreadcrumbSection'); var _BreadcrumbSection2 = _interopRequireDefault(_BreadcrumbSection); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * A breadcrumb is used to show hierarchy between content. */ function Breadcrumb(props) { var children = props.children, className = props.className, divider = props.divider, icon = props.icon, sections = props.sections, size = props.size; var classes = (0, _classnames2.default)('ui', size, 'breadcrumb', className); var rest = (0, _lib.getUnhandledProps)(Breadcrumb, props); var ElementType = (0, _lib.getElementType)(Breadcrumb, props); if (!(0, _isNil3.default)(children)) return _react2.default.createElement( ElementType, (0, _extends3.default)({}, rest, { className: classes }), children ); var childElements = []; (0, _each3.default)(sections, function (section, index) { // section var breadcrumbElement = _BreadcrumbSection2.default.create(section); childElements.push(breadcrumbElement); // divider if (index !== sections.length - 1) { var key = breadcrumbElement.key + '_divider' || JSON.stringify(section); childElements.push(_BreadcrumbDivider2.default.create({ content: divider, icon: icon, key: key })); } }); return _react2.default.createElement( ElementType, (0, _extends3.default)({}, rest, { className: classes }), childElements ); } Breadcrumb.handledProps = ['as', 'children', 'className', 'divider', 'icon', 'sections', 'size']; Breadcrumb._meta = { name: 'Breadcrumb', type: _lib.META.TYPES.COLLECTION }; process.env.NODE_ENV !== "production" ? Breadcrumb.propTypes = { /** An element type to render as (string or function). */ as: _lib.customPropTypes.as, /** Primary content. */ children: _propTypes2.default.node, /** Additional classes. */ className: _propTypes2.default.string, /** Shorthand for primary content of the Breadcrumb.Divider. */ divider: _lib.customPropTypes.every([_lib.customPropTypes.disallow(['icon']), _lib.customPropTypes.contentShorthand]), /** For use with the sections prop. Render as an `Icon` component with `divider` class instead of a `div` in * Breadcrumb.Divider. */ icon: _lib.customPropTypes.every([_lib.customPropTypes.disallow(['divider']), _lib.customPropTypes.itemShorthand]), /** Shorthand array of props for Breadcrumb.Section. */ sections: _lib.customPropTypes.collectionShorthand, /** Size of Breadcrumb. */ size: _propTypes2.default.oneOf((0, _without3.default)(_lib.SUI.SIZES, 'medium')) } : void 0; Breadcrumb.Divider = _BreadcrumbDivider2.default; Breadcrumb.Section = _BreadcrumbSection2.default; exports.default = Breadcrumb;
var pageCommon = require("ui/page/page-common"); var viewModule = require("ui/core/view"); var trace = require("trace"); var utils = require("utils/utils"); global.moduleMerge(pageCommon, exports); var UIViewControllerImpl = (function (_super) { __extends(UIViewControllerImpl, _super); function UIViewControllerImpl() { _super.apply(this, arguments); } UIViewControllerImpl.new = function () { return _super.new.call(this); }; UIViewControllerImpl.prototype.initWithOwner = function (owner) { this._owner = owner; this.automaticallyAdjustsScrollViewInsets = false; return this; }; UIViewControllerImpl.prototype.didRotateFromInterfaceOrientation = function (fromInterfaceOrientation) { trace.write(this._owner + " didRotateFromInterfaceOrientation(" + fromInterfaceOrientation + ")", trace.categories.ViewHierarchy); if (this._owner._isModal) { var parentBounds = this._owner._UIModalPresentationFormSheet ? this._owner._nativeView.superview.bounds : UIScreen.mainScreen().bounds; utils.ios._layoutRootView(this._owner, parentBounds); } }; UIViewControllerImpl.prototype.viewDidLoad = function () { trace.write(this._owner + " viewDidLoad", trace.categories.ViewHierarchy); this.view.autoresizesSubviews = false; this.view.autoresizingMask = UIViewAutoresizing.UIViewAutoresizingNone; }; UIViewControllerImpl.prototype.viewDidLayoutSubviews = function () { trace.write(this._owner + " viewDidLayoutSubviews, isLoaded = " + this._owner.isLoaded, trace.categories.ViewHierarchy); if (this._owner._isModal) { var parentBounds = this._owner._UIModalPresentationFormSheet ? this._owner._nativeView.superview.bounds : UIScreen.mainScreen().bounds; utils.ios._layoutRootView(this._owner, parentBounds); } else { this._owner._updateLayout(); } }; UIViewControllerImpl.prototype.viewWillAppear = function () { trace.write(this._owner + " viewWillAppear", trace.categories.Navigation); this._owner._enableLoadedEvents = true; this._owner.onLoaded(); this._owner._enableLoadedEvents = false; }; UIViewControllerImpl.prototype.viewDidDisappear = function () { trace.write(this._owner + " viewDidDisappear", trace.categories.Navigation); this._owner._enableLoadedEvents = true; this._owner.onUnloaded(); this._owner._enableLoadedEvents = false; }; return UIViewControllerImpl; })(UIViewController); var Page = (function (_super) { __extends(Page, _super); function Page(options) { _super.call(this, options); this._isModal = false; this._ios = UIViewControllerImpl.new().initWithOwner(this); } Page.prototype.requestLayout = function () { _super.prototype.requestLayout.call(this); if (!this.parent && this.ios && this._nativeView) { this._nativeView.setNeedsLayout(); } }; Page.prototype._onContentChanged = function (oldView, newView) { _super.prototype._onContentChanged.call(this, oldView, newView); this._removeNativeView(oldView); this._addNativeView(newView); }; Page.prototype.onLoaded = function () { if (this._enableLoadedEvents) { _super.prototype.onLoaded.call(this); } }; Page.prototype.onUnloaded = function () { if (this._enableLoadedEvents) { _super.prototype.onUnloaded.call(this); } }; Page.prototype._addNativeView = function (view) { if (view) { trace.write("Native: Adding " + view + " to " + this, trace.categories.ViewHierarchy); if (view.ios instanceof UIView) { this._ios.view.addSubview(view.ios); } else if (view.ios instanceof UIViewController) { this._ios.addChildViewController(view.ios); this._ios.view.addSubview(view.ios.view); } } }; Page.prototype._removeNativeView = function (view) { if (view) { trace.write("Native: Removing " + view + " from " + this, trace.categories.ViewHierarchy); if (view.ios instanceof UIView) { view.ios.removeFromSuperview(); } else if (view.ios instanceof UIViewController) { view.ios.removeFromParentViewController(); view.ios.view.removeFromSuperview(); } } }; Object.defineProperty(Page.prototype, "ios", { get: function () { return this._ios; }, enumerable: true, configurable: true }); Object.defineProperty(Page.prototype, "_nativeView", { get: function () { return this.ios.view; }, enumerable: true, configurable: true }); Page.prototype._showNativeModalView = function (parent, context, closeCallback, fullscreen) { this._isModal = true; if (!parent.ios.view.window) { throw new Error("Parent page is not part of the window hierarchy. Close the current modal page before showing another one!"); } if (fullscreen) { this._ios.modalPresentationStyle = UIModalPresentationStyle.UIModalPresentationFullScreen; utils.ios._layoutRootView(this, UIScreen.mainScreen().bounds); } else { this._ios.modalPresentationStyle = UIModalPresentationStyle.UIModalPresentationFormSheet; this._UIModalPresentationFormSheet = true; } var that = this; parent.ios.presentViewControllerAnimatedCompletion(this._ios, false, function completion() { if (!fullscreen) { utils.ios._layoutRootView(that, that._nativeView.superview.bounds); } that._raiseShownModallyEvent(parent, context, closeCallback); }); }; Page.prototype._hideNativeModalView = function (parent) { parent._ios.dismissModalViewControllerAnimated(false); this._isModal = false; this._UIModalPresentationFormSheet = false; }; Page.prototype._updateActionBar = function (hidden) { var frame = this.frame; if (frame) { frame._updateActionBar(this); } }; Page.prototype.onMeasure = function (widthMeasureSpec, heightMeasureSpec) { viewModule.View.measureChild(this, this.actionBar, widthMeasureSpec, heightMeasureSpec); _super.prototype.onMeasure.call(this, widthMeasureSpec, heightMeasureSpec); }; Page.prototype.onLayout = function (left, top, right, bottom) { viewModule.View.layoutChild(this, this.actionBar, 0, 0, right - left, bottom - top); _super.prototype.onLayout.call(this, left, top, right, bottom); }; Page.prototype._addViewToNativeVisualTree = function (view) { if (view === this.actionBar) { return true; } return _super.prototype._addViewToNativeVisualTree.call(this, view); }; return Page; })(pageCommon.Page); exports.Page = Page;
(function($){ $(document).ready(function(){ $('.nospace').keypress(function(e){ if (e.charCode === 32) { e.preventDefault(); } }); }); })(jQuery); function defer_init() { var imgDefer = document.getElementsByClassName('lazy-img'); for (var i=0; i<imgDefer.length; i++) { if(imgDefer[i].getAttribute('data-src')) { imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src')); } } } window.onload = defer_init;
'use strict'; const path = require('path'); const fs = require('fs'); const config = { name: 'default', numCPUs: 4, port: 8001, mongodb: 'mongodb://localhost:27017/iot', brokerPort: 1883 }; var customConfig = path.join(__dirname, 'config.js'); if (fs.existsSync(customConfig)) { var options = require(customConfig); Object.assign(config, options); } module.exports = config;
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); const DebugClient_1 = require("./DebugClient"); const localDebugClientV2_1 = require("./localDebugClientV2"); class NonDebugClientV2 extends localDebugClientV2_1.LocalDebugClientV2 { constructor(args, debugSession, canLaunchTerminal, launcherScriptProvider) { super(args, debugSession, canLaunchTerminal, launcherScriptProvider); } get DebugType() { return DebugClient_1.DebugType.RunLocal; } Stop() { super.Stop(); if (this.pyProc) { try { this.pyProc.kill(); // tslint:disable-next-line:no-empty } catch (_a) { } this.pyProc = undefined; } } handleProcessOutput(proc, _failedToLaunch) { // Do nothing } } exports.NonDebugClientV2 = NonDebugClientV2; //# sourceMappingURL=nonDebugClientV2.js.map
'use strict'; var path = process.cwd(); var ClickHandler = require(path + '/app/controllers/clickHandler.server.js'); var BookmarkHandler = require(path + '/app/controllers/bookmarkHandler.server.js'); var UpvoteHandler = require(path + '/app/controllers/upvoteHandler.server.js'); var ArticleHandler = require(path + '/app/controllers/artikelHandler.server.js'); var TanamanHandler = require(path + '/app/controllers/tanamanHandler.server.js'); var PenyakitHandler = require(path + '/app/controllers/penyakitHandler.server.js'); var DetailTanamanHandler = require(path + '/app/controllers/detailtanamanHandler.server.js'); var DetailPenyakitHandler = require(path + '/app/controllers/detailpenyakitHandler.server.js'); module.exports = function (app, passport) { function isLoggedIn (req, res, next) { if (req.isAuthenticated()) { return next(); } else { res.redirect('/login'); } } var clickHandler = new ClickHandler(); var bookmarkHandler = new BookmarkHandler(); var upvoteHandler = new UpvoteHandler(); var articleHandler = new ArticleHandler(); var tanamanHandler = new TanamanHandler(); var penyakitHandler = new PenyakitHandler(); var detailtanamanHandler = new DetailTanamanHandler(); var detailpenyakitHandler = new DetailPenyakitHandler(); app.route('/').get(isLoggedIn, function (req, res) { res.sendFile(path + '/public/index.html'); }); app.route('/login').get(function (req, res) { res.sendFile(path + '/public/homepage.html'); }); app.route('/logout').get(function (req, res) { req.logout(); res.redirect('/login'); }); app.route('/profile').get(isLoggedIn, function (req, res) { res.sendFile(path + '/public/profile.html'); }); app.route('/artikel').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/kumpulanartikel.html'); }); app.route('/tanaman').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/daftartanaman.html'); }); app.route('/detailtanaman/:tanamanid').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/detailtanaman.html'); //console.log(req.query.tanamanid); }); app.route('/detailpenyakit/:penyakitid').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/detailpenyakit.html'); //console.log(req.query.penyakitid); }); /* app.route('/detailtanaman/:tanamanid').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/detailtanaman.html'); }); */ app.route('/penyakit').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/daftarpenyakit.html'); }); app.route('/about').get(function(req, res) { res.sendFile(path + '/public/about.html'); }); app.route('/bookmarked').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/bookmarked.html'); }) app.route('/kenalipenyakit').get(isLoggedIn, function(req, res) { res.sendFile(path + '/public/sibatobataAI.html'); }) // API API API API API API API app.route('/api/:id').get(isLoggedIn, function (req, res) { res.json(req.user.twitter); }); app.route('/auth/twitter').get(passport.authenticate('twitter')); app.route('/auth/twitter/callback').get(passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' })); app.route('/api/:id/tanaman') .get(isLoggedIn, tanamanHandler.getTanaman); app.route('/api/detailtanaman/:tanamanid') .get(isLoggedIn, detailtanamanHandler.getDetailtanaman) .post(isLoggedIn, detailtanamanHandler.addUpvote) .delete(isLoggedIn, detailtanamanHandler.removeUpvote); app.route('/api/detailpenyakit/:penyakitid') .get(isLoggedIn, detailpenyakitHandler.getDetailpenyakit) .post(isLoggedIn, detailpenyakitHandler.addUpvote) .delete(isLoggedIn, detailpenyakitHandler.removeUpvote); app.route('/api/upvote/:tanamanid') .get(isLoggedIn, upvoteHandler.getUpvotes) .post(isLoggedIn, upvoteHandler.addUpvote) .delete(isLoggedIn, upvoteHandler.removeUpvote); app.route('/api/:id/penyakit') .get(isLoggedIn, penyakitHandler.getPenyakit); app.route('/api/:id/artikel') .get(isLoggedIn, articleHandler.getArticles); app.route('/api/:id/clicks') .get(isLoggedIn, clickHandler.getClicks) .post(isLoggedIn, clickHandler.addClick) .delete(isLoggedIn, clickHandler.resetClicks); app.route('/api/:id/bookmark') .get(isLoggedIn, bookmarkHandler.getBookmarks); app.route('/api/bookmark/:articleid') .post(isLoggedIn, bookmarkHandler.addBookmark) .delete(isLoggedIn, bookmarkHandler.removeBookmark); // ===================================== // FACEBOOK ROUTES ===================== // ===================================== // route for facebook authentication and login /* app.route('/auth/facebook') .get(passport.authenticate('facebook')); // handle the callback after facebook has authenticated the user app.route('/auth/facebook/callback') .get(passport.authenticate('facebook', { failureRedirect : '/login' }), function(req, res) { res.redirect('/'); } ); */ // ===================================== // TWITTER ROUTES ====================== // ===================================== // route for twitter authentication and login /* app.get('/auth/twitter', passport.authenticate('twitter')); // handle the callback after twitter has authenticated the user app.get('/auth/twitter/callback', passport.authenticate('twitter', { successRedirect : '/', failureRedirect : '/login' })); */ };
var extName = require('../vendor/ext-name'); function isAsset(filename) { var info = extName(filename); return ( info && info.mime && (/^((image)|(audio)|(video)|(font))\//.test(info.mime) || /application\/((x[-]font[-])|(font[-]woff(\d?))|(vnd[.]ms[-]fontobject))/.test( info.mime )) ); } module.exports = isAsset;
const assert = require('chai').assert const app = require('../index') const request = require('supertest')(app) const mongoose = require('mongoose') const User = require('../models/User').User const Student = require('../models/Student').Student const Teacher = require('../models/Teacher').Teacher const { Map } = require('immutable') const async = require('async') const TokenReset = require('../models/TokenReset').TokenReset let student = Map({ username: 'teacherUsername4', password: 'studentPassword', email: 'student@email.com', firstName: 'studentFisrtName', secondName: 'studentSecondName', lastName: 'studentLastName', phoneNumber: '+380968995375', dateBirthday: new Date(1997, 10, 5), type: 'student', avatar: '/testPath' }) let teacher1 = Map({ username: 'teacherUsername1', password: 'teacherPassword', email: 'teacher1@email.com', firstName: 'teacherFisrtName', secondName: 'teacherSecondName', lastName: 'teacherLastName', phoneNumber: '+380968995375', dateBirthday: new Date(1997, 10, 5), type: 'teacher', avatar: '/testPath' }) let teacher2 = Map({ username: 'teacherUsername2', password: 'teacherPassword', email: 'teacher2@email.com', firstName: 'teacherFisrtName', secondName: 'teacherSecondName', lastName: 'teacherLastName', phoneNumber: '+380968995375', dateBirthday: new Date(1997, 10, 5), type: 'teacher', avatar: '/testPath' }) let teacher3 = Map({ username: 'teacherUsername3', password: 'teacherPassword', email: 'teacher3 @email.com', firstName: 'teacherFisrtName', secondName: 'teacherSecondName', lastName: 'teacherLastName', phoneNumber: '+380968995375', dateBirthday: new Date(1997, 10, 5), type: 'teacher', avatar: '/testPath' }) let email = 'kostyazgara2@gmail.com' describe('Users', function () { before('add users to DB', function (done) { let user1 = new User(teacher1.toObject()) let user2 = new User(teacher2.toObject()) let user3 = new User(teacher3.toObject()) async.parallel({ task1: function (cb) { user1.save((err) => { if (err) { return cb(err) } cb(null, true) }) }, task2: function (cb) { user2.save((err) => { if (err) { return cb(err) } cb(null, true) }) }, task3: function (cb) { user3.save((err, doc) => { if (err) { return cb(err) } cb(null, doc._id) }) } }, (err, result) => { if (err) { done(err) } if (result.task1 && result.task2) { //set teacher as approved User.findOne({ username: 'teacherUsername1' }, (err, teacher) => { if (err) { return done(err) } teacher.approved = true teacher.save(err => { if (err) { return done(err) } }) }) //create student let user4 = new Student(student.set('idTeacher', result.task3).toObject()) user4.save(err => { if (err) { return done(err) } return done() }) } else { done(new Error('some task finished with error')) } }) }) after('delete users from DB', function (done) { Teacher.remove({ username: /^teacherUsername/ }, (err, aff) => { if (err) { return done(err) } done() }) }) describe('get users', function () { it('should return all users', function (done) { request .get('/users/') .expect(200) .then(res => { if (res.body.length === 0) { return done('expected what array will b greater than 0') } done() }) .catch(err => { done(err) }) }) it('should return only students', function (done) { request .get('/users/') .query({ type: 'student' }) .expect(200) .then(res => { for (let i = 0; i < res.body.length; i++) { assert.equal(res.body[i].type, 'student', 'expected that type will be student') } done() }) }) it('should return only teachers', function (done) { request .get('/users/') .query({ type: 'teacher' }) .expect(200) .then(res => { for (let i = 0; i < res.body.length; i++) { assert.equal(res.body[i].type, 'teacher', 'expected that type will be teacher') } done() }) }) it('should return not approved teachers', function (done) { request .get('/users/') .query({ approved: false }) .expect(200) .then(res => { for (let i = 0; i < res.body.length; i++) { assert.equal(res.body[i].approved, false, 'expected that aproved will be false') } done() }) }) it('should return approved teachers', function (done) { request .get('/users/') .query({ approved: true }) .expect(200) .then(res => { for (let i = 0; i < res.body.length; i++) { assert.equal(res.body[i].approved, true, 'expected that approved will be true') } done() }) }) }) describe('reset password', function () { after('set default password', function (done) { User.findOne({ email: email }) .then(user => { user.password = 'Rjcnz_Pufhf97' return user.save() }) .then(() => { done() }) .catch(err => { done(err) }) }) describe('invalid request', function () { it('should return 400 when email not found', function (done) { request .post('/forgot') .send({ email: 'asdasdas@adasd.ru' }) .expect(400) .then(() => User.findOne({ email: email })) .then(user => { assert.ok(!user.checkPassword('123456')) done() }) .catch(err => { done(err) }) }) }) describe('valid request', function () { it('should reset password', function (done) { request .post('/forgot') .send({ email: email }) .expect(200) .then(() => TokenReset.findOne({ email: email })) .then(tokenreset => { return request .post('/reset/' + tokenreset.token) .send({ newPassword: '123456' }) .expect(200) }) .then(() => User.findOne({ email: email })) .then(user => { assert.ok(user.checkPassword('123456')) done() }) .catch(err => { done(err) }) }) }) }) })
export const GET_TODOS = 'GET_TODOS'; export const TOGGLE_TODO = 'TOGGLE_TODO'; export const ADD_TODO = 'ADD_TODO'; export const HYDRATE = 'HYDRATE_TODOS'; export const UPDATE_TODOS = 'UPDATE_TODOS'; export const DELETE_TODO = 'DELETE_TODO';
require("babel-register"); var path = require('path'); var compareMethod = require('../helper/compareMethod'); exports.config = { specs: [ path.join(__dirname, '*.test.js') ], capabilities: [ { browserName: 'phantomjs', 'phantomjs.binary.path': require('phantomjs').path, } ], sync: false, logLevel: 'silent', coloredLogs: true, baseUrl: 'http://webdriver.io', waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, framework: 'mocha', mochaOpts: { ui: 'bdd', timeout: 60000, compilers: [ 'js:babel-register' ], }, services: [ 'selenium-standalone', require('../../src') ], visualRegression: { compare: compareMethod, viewportChangePause: 250, viewports: [{ width: 600, height: 1000 }], }, // Options for selenium-standalone // Path where all logs from the Selenium server should be stored. seleniumLogs: './logs/', }
/* * json-template-replace * https://github.com/domsob/json-template-replace * * Copyright (c) 2016 Dominik Sobania * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'] }, // Configuration to be run (and then tested). 'json-template-replace': { default_options: { files: { 'tmp/default_options.html': ['test/fixtures/header_comment.html', 'test/fixtures/template.html'] } }, custom_options: { options: { replace: { 'title': 'This is the title', 'navigation': { 'snippet': 'test/fixtures/include_template.html', 'isFile': true, 'items': [{'naviitem': 'Item 1'}, {'naviitem': 'Item 2'}, {'naviitem': 'Item 3'}] }, 'content': 'Lorem ipsum dolor sit amet.', 'list': { 'snippet': '<li>###listitem###</li>', 'isFile': false, 'items': [{'listitem': 'Item 1'}, {'listitem': 'Item 2'}, {'listitem': 'Item 3'}, {'listitem': 'Item 4'}] }, 'footer': 'Copyright (c)', 'year': 2016 } }, files: { 'tmp/custom_options.html': ['test/fixtures/header_comment.html', 'test/fixtures/template.html'] } } }, // Unit tests. nodeunit: { tests: ['test/*_test.js'] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'json-template-replace', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
/** TODO: rtl support Styling templates: <style> .listview[data-listview-orientation="vertical"] > .listview-inner { width: 100%; } .listview[data-listview-orientation="horizontal"] > .listview-inner { height: 100%; } .listview > .listview-inner > * { padding: 0.5em 1em; } .listview[data-listview-orientation="vertical"] > .listview-inner > * { border-bottom: #eee 1px solid; } .listview[data-listview-orientation="vertical"] > .listview-inner > :last-child { border-bottom: none; } .listview[data-listview-orientation="horizontal"] > .listview-inner > * { border-right: #eee 1px solid; } .listview[data-listview-orientation="horizontal"] > .listview-inner > :last-child { border-bottom: none; } </style> */ function ListView(container, adapter, orientation) { /** * CustomEvent polyfill * @see https://developer.mozilla.org/ru/docs/Web/API/CustomEvent/CustomEvent */ var CustomEvent = window.CustomEvent; if (typeof CustomEvent !== 'function') { CustomEvent = function (event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; } CustomEvent.prototype = window.Event.prototype; } // use default adapter for arrays: if (adapter instanceof Array && typeof adapter.getView != 'function') { adapter = new ListView.ArrayAdapter(adapter); } if (!(container instanceof HTMLElement)) { throw new Error("First argument 'container' should be an HTMLElement"); } var _this = this; orientation = orientation || container.getAttribute('data-listview-orientation') || 'vertical'; var vertical = orientation != 'horizontal'; orientation = vertical ? 'vertical' : 'horizontal'; container.classList.add('listview'); container.style.overflow = 'hidden'; container.setAttribute('data-listview-orientation', orientation); container.setAttribute('data-listview-adapter', adapter.constructor.name); Object.defineProperty(this, 'container', { enumerable: true, configurable: false, writable: false, value: container }); // inner container definition and helpers: var inner = document.createElement('div'); inner.style.position = 'relative'; inner.style.display = 'inline-flex'; inner.style.flexDirection = vertical ? 'column' : 'row'; inner.className = 'listview-inner'; container.appendChild(inner); inner.getOffsetStart = function () { return parseFloat(inner.style[vertical ? 'top' : 'left']) || 0; }; inner.setOffsetStart = function (value) { inner.style[vertical ? 'top' : 'left'] = value + 'px'; return value; }; inner.incOffsetStart = function (add) { return this.setOffsetStart(this.getOffsetStart() + add); }; // basics: this.getStartItemVisibility = function () { var v = inner.getOffsetStart(); var s = getViewSize(inner.children[0]); return !inner.children[0] ? null : (!v ? 1 : 1 - (-v / s)); } this.getStartIndex = function () { return !inner.children.length ? false : +inner.children[0].getAttribute('data-listview-index'); }; this.getEndIndex = function () { return !inner.children.length ? false : +inner.children[inner.children.length - 1].getAttribute('data-listview-index'); }; this.getOffsetStart = function () { return inner.getOffsetStart(); }; this.getAdapter = function () { return adapter; }; this.getListItemSize = function (index) { return !inner.children[index] ? false : getViewSize(inner.children[index]); }; // drawing: function getView(index, container, inner) { var res = adapter.getView(index, container, inner); if (res === true || !res) return res; res.setAttribute('data-listview-index', index); inner.dispatchEvent(new CustomEvent('lv-get-view', { bubbles: true, cancelable: false, detail: { vertical: vertical, orientation: orientation, view: res, }, })); return res; } function getViewSize(view) { return view[vertical ? 'clientHeight' : 'clientWidth']; } this.redraw = function (forceStartIndex) { var containerSize = getViewSize(container); if (!containerSize) { throw new Error("Container size isn't set. Please define " + (vertical ? 'height' : 'width') + " of container"); } var i; var clear = false; if (forceStartIndex === true) { i = this.getStartIndex() - 1; // just force redraw existing elements clear = true; } else if (typeof forceStartIndex == 'number') { i = forceStartIndex - 1; // scroll to index and redraw inner.setOffsetStart(0); clear = true; } else { i = this.getEndIndex(); // just add lacking items to the end } if (clear) { while (inner.children[0]) inner.removeChild(inner.children[0]); } if (i === false) i = -1; // append items: var offsetStart = inner.getOffsetStart(); while (getViewSize(inner) + offsetStart < containerSize) { i++; var el = getView(i, container, inner); if (el === true) continue; else if (!el) { inner.incOffsetStart(getViewSize(container) - getViewSize(inner) - offsetStart); break; } inner.appendChild(el); } // prepend items: var i = this.getStartIndex(); while (inner.getOffsetStart() > 0) { i--; var el = getView(i, container, inner); if (el === true) continue; else if (!el) { inner.setOffsetStart(0); break; } inner.insertBefore(el, inner.children[0]); var size = getViewSize(el); inner.incOffsetStart(-size); } // remove excessive starting items: while (1) { offsetStart = inner.getOffsetStart(); var el = inner.children[0]; if (!el) { inner.setOffsetStart(0); break; } var size = getViewSize(el); if (offsetStart + size > 0) break; inner.incOffsetStart(size); inner.removeChild(el); } // remove excessive ending items: offsetStart = inner.getOffsetStart(); while (1) { var el = inner.children[inner.children.length - 1]; if (!el) break; var size = getViewSize(el); if (getViewSize(inner) + offsetStart - size <= getViewSize(container)) break; inner.removeChild(el); } inner.dispatchEvent(new CustomEvent('lv-draw', { bubbles: true, cancelable: false, detail: { offsetStart: offsetStart, vertical: vertical, orientation: orientation, }, })); }; // scrolling: var scrollByAnim = 0; function animateScrollBy() { var v = scrollByAnim; var av = Math.abs(scrollByAnim); var sv = scrollByAnim < 0 ? -1 : +1; var scrollByStep = av > 1 ? Math.pow(av, 1/1.7)*sv : scrollByAnim; inner.incOffsetStart(scrollByStep); scrollByAnim -= scrollByStep; _this.redraw(); if (scrollByAnim) { dispatchScrollAnimation(); requestAnimationFrame(animateScrollBy); } else { dispatchScrollStop(); } } function dispatchScrollStop() { inner.dispatchEvent(new CustomEvent('lv-scroll-stop', { bubbles: true, cancelable: false, detail: { vertical: vertical, orientation: orientation, }, })); } function dispatchScrollAnimation() { inner.dispatchEvent(new CustomEvent('lv-scroll-animation', { bubbles: true, cancelable: false, detail: { vertical: vertical, orientation: orientation, animateScrollBy: animateScrollBy, }, })); } this.scrollBy = function (dOffsetStart, fix, continuous) { if (fix) { scrollByAnim = 0; inner.incOffsetStart(dOffsetStart); this.redraw(); if (!continuous) dispatchScrollStop(); else dispatchScrollAnimation(); } else { scrollByAnim += dOffsetStart; if (scrollByAnim - dOffsetStart == 0) animateScrollBy(); } return this; }; this.scrollToIndex = function (index) { scrollByAnim = 0; this.redraw(index); dispatchScrollStop(); return this; }; this.scrollSnapStart = function () { var offsetStart = this.getOffsetStart(); if (offsetStart != 0) { var itemVisibility = this.getStartItemVisibility(); // if (itemVisibility < 0.001 || itemVisibility > 0.999) // return; scrollByAnim = 0; if (itemVisibility > 0.5) { this.scrollBy(-offsetStart); } else { this.scrollBy(-this.getListItemSize(0) - offsetStart); } } return this; }; // user interaction: container.addEventListener('mousewheel', function (event) { if (event.ctrlKey || event.shiftKey || event.altKey) return; _this.scrollBy(-event.deltaY); event.preventDefault(); return false; }); var prevPoint = null; container.addEventListener('touchstart', function (event) { if (event.touches.length == 1) { prevPoint = event.touches[0]; prevPoint.dps = []; _this.scrollBy(0, true); } else { prevPoint = null; } }); container.addEventListener('touchmove', function (event) { if (event.touches.length != 1) { return; } var point = event.touches[0]; point.dps = prevPoint.dps; var dp = vertical ? point.pageY - prevPoint.pageY : point.pageX - prevPoint.pageX; point.dps.push([event.timeStamp, dp]); if (point.dps.length > 10) point.dps.shift(); if (dp) _this.scrollBy(dp, true, true); prevPoint = point; event.preventDefault(); return false; }); document.body.addEventListener('touchend', function (event) { if (prevPoint && prevPoint.dps.length && event.changedTouches.length == 1) { var point = event.changedTouches[0]; point.timeStamp = event.timeStamp; var dpc = 0; var dp = prevPoint.dps.reduce(function (a, b) { if (b[1] == 0) { dpc = 0; return 0; } else if (point.timeStamp - b[0] > 50) return a; else { dpc++; return a + b[1]; } }, 0); if (dpc > 0) { var dir = dp < 0 ? -1 : +1; var offset = Math.pow(Math.abs(dp) / dpc, 1.2); _this.scrollBy(dir * offset * (getViewSize(container) / 50)); } else { _this.scrollBy(0, true, false); } } prevPoint = null; }); container.addEventListener('keydown', function (event) { if (event.altKey || event.ctrlKey || event.shiftKey) return; var up = 38; var down = 40; var left = 37; var right = 39; var pgup = 33; var pgdn = 34; var key = event.keyCode || event.which; var containerSize = getViewSize(container); if ((vertical && key == up) || (!vertical && key == left)) { _this.scrollBy(+containerSize / 10); } else if ((vertical && key == down) || (!vertical && key == right)) { _this.scrollBy(-containerSize / 10); } else if (key == pgup) { _this.scrollBy(+containerSize); } else if (key == pgdn) { _this.scrollBy(-containerSize); } else { return; } event.preventDefault(); return false; }); this.redraw(); } ListView.ArrayAdapter = function (items) { this.getView = function (index, container, inner) { if (index < 0 || index >= items.length) return null; var view = document.createElement('div'); view.textContent = items[index]; return view; }; }; ListView.PrimesAdapter = function () { function isPrime(n) { if (n < 2) return false; if (n != 2 && n % 2 == 0) return false; for (var i = Math.sqrt(n) | 0; i > 1; i--) { if (n % i == 0) return false; } return true; } this.getView = function (i) { if (i < 0) return false; // do not show and stop else if (!isPrime(i)) return true; // do not show and continue var res = document.createElement('div'); res.textContent = i; return res; // show view if the i is prime }; };
/* eslint-disable */ const CONFIG = { log: { useLogger: true } }; export default CONFIG;
'use strict'; exports.__esModule = true; var _class, _temp; var _react = require('react'); var _react2 = _interopRequireDefault(_react); require('trix'); 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 ReactTrixEditor = (_temp = _class = function (_Component) { _inherits(ReactTrixEditor, _Component); function ReactTrixEditor() { _classCallCheck(this, ReactTrixEditor); var _this = _possibleConstructorReturn(this, _Component.call(this)); _this.id = Math.random().toString(36); _this.updateStateValue = _this.updateStateValue.bind(_this); return _this; } ReactTrixEditor.prototype.componentDidMount = function componentDidMount() { var _this2 = this; // Provide editor to callback on initialisation document.getElementById(this.id).addEventListener('trix-initialize', function () { _this2.editor = document.getElementById(_this2.id).editor; if (_this2.props.onEditor) { // Pass the editor & node _this2.props.onEditor(_this2.editor, document.getElementById(_this2.id)); } }); document.getElementById(this.id).addEventListener('trix-change', function (e) { return _this2.updateStateValue(e); }); }; ReactTrixEditor.prototype.updateStateValue = function updateStateValue(e) { var value = e.target.value; this.props.onChange(value); }; ReactTrixEditor.prototype.render = function render() { var _props = this.props; var input = _props.input; var initialValue = _props.initialValue; var placeholder = _props.placeholder; var autofocus = _props.autofocus; return _react2.default.createElement( 'div', null, _react2.default.createElement('input', { id: input, value: initialValue, type: 'hidden', name: 'content' }), _react2.default.createElement('trix-editor', { id: this.id, input: input, placeholder: placeholder, autofocus: autofocus }) ); }; return ReactTrixEditor; }(_react.Component), _class.defaultProps = { autofocus: false, input: 'react-trix-editor', placeholder: 'Enter text here...' }, _temp); process.env.NODE_ENV !== "production" ? ReactTrixEditor.propTypes = { onChange: _react.PropTypes.func.isRequired, onEditor: _react.PropTypes.func, autofocus: _react.PropTypes.bool, input: _react.PropTypes.string, placeholder: _react.PropTypes.string, initialValue: _react.PropTypes.string } : void 0; exports.default = ReactTrixEditor; module.exports = exports['default'];
'use strict' var rkck = require('../lib') var evaluations = 0 var deriv = function(dydt, y, t) { evaluations ++ dydt[0] = 1/t * Math.cos(1/t) } var ta = 0.01 var tb = 1 var i = rkck( [-1], deriv, ta, 1e-8, { tol: 5e-8, maxIncreaseFactor: 2 }) var rkck_y0 = i.y[0] i.steps( Infinity, tb ) var rkck_y1 = i.y[0] var actual = -0.34255274804359265 console.log('Absolute error:',Math.abs( actual - (rkck_y1-rkck_y0) )) console.log('Derivative evaluations:', evaluations )
'use strict'; require('mocha'); var assert = require('assert'); var File = require('vinyl'); var utils = require('../lib/utils'); var loader = require('..'); describe('utils', function () { describe('toFile', function () { it('should create a vinyl file', function() { var file = utils.toFile('abc', 'abc', {}); assert(file); assert(File.isVinyl(file)); }); it('should work when no options object is passed', function() { var file = utils.toFile('abc', 'abc'); assert(file); assert(File.isVinyl(file)); }); it('should add a cwd property', function() { var file = utils.toFile('abc', 'abc'); assert(file); assert(file.cwd); }); it('should use the cwd on the options', function() { var file = utils.toFile('abc', 'abc', {cwd: 'xyz'}); assert(file); assert(file.cwd); assert(file.cwd === 'xyz'); }); it('should use process.cwd if no cwd is passed', function() { var file = utils.toFile('abc', 'abc'); assert(file); assert(file.cwd); assert(file.cwd === process.cwd()); }); it('should add a base property', function() { var file = utils.toFile('abc', 'abc'); assert(file); assert(file.base); }); it('should use base passed on options', function() { var file = utils.toFile('abc', 'abc', {base: 'xyz'}); assert(file); assert(file.base); assert(file.base === 'xyz'); }); it('should use glob parent if no base is passed', function() { var file = utils.toFile('abc', 'a/b/c/*.js'); assert(file); assert(file.base); assert(file.base === 'a/b/c'); }); it('should use the glob parent of the first pattern in an array', function() { var file = utils.toFile('abc', ['x/y/z/*.md', 'a/b/c/*.js']); assert(file); assert(file.base); assert(file.base === 'x/y/z'); }); it('should use the glob parent of the first pattern in an array', function(done) { try { utils.toFile('abc', new Date()); done(new Error('expected an error.')); } catch(err) { assert(err); assert(err.message); assert(err.message === 'expected pattern to be a string or array'); done(); } }); }); });
console.log('index.js called'); var HeavensAboveClient = require('./lib/client.es6'); var client = new HeavensAboveClient('http://heavens-above.com/');
angular .module('material.components.autocomplete') .directive('mdAutocomplete', MdAutocomplete); /** * @ngdoc directive * @name mdAutocomplete * @module material.components.autocomplete * * @description * `<md-autocomplete>` is a special input component with a drop-down of all possible matches to a * custom query. This component allows you to provide real-time suggestions as the user types * in the input area. * * To start, you will need to specify the required parameters and provide a template for your * results. The content inside `md-autocomplete` will be treated as a template. * * In more complex cases, you may want to include other content such as a message to display when * no matches were found. You can do this by wrapping your template in `md-item-template` and * adding a tag for `md-not-found`. An example of this is shown below. * * ### Validation * * You can use `ng-messages` to include validation the same way that you would normally validate; * however, if you want to replicate a standard input with a floating label, you will have to * do the following: * * - Make sure that your template is wrapped in `md-item-template` * - Add your `ng-messages` code inside of `md-autocomplete` * - Add your validation properties to `md-autocomplete` (ie. `required`) * - Add a `name` to `md-autocomplete` (to be used on the generated `input`) * * There is an example below of how this should look. * * * @param {expression} md-items An expression in the format of `item in items` to iterate over * matches for your search. * @param {expression=} md-selected-item-change An expression to be run each time a new item is * selected * @param {expression=} md-search-text-change An expression to be run each time the search text * updates * @param {expression=} md-search-text A model to bind the search query text to * @param {object=} md-selected-item A model to bind the selected item to * @param {expression=} md-item-text An expression that will convert your object to a single string. * @param {string=} placeholder Placeholder text that will be forwarded to the input. * @param {boolean=} md-no-cache Disables the internal caching that happens in autocomplete * @param {boolean=} ng-disabled Determines whether or not to disable the input field * @param {number=} md-min-length Specifies the minimum length of text before autocomplete will * make suggestions * @param {number=} md-delay Specifies the amount of time (in milliseconds) to wait before looking * for results * @param {boolean=} md-autofocus If true, the autocomplete will be automatically focused when a `$mdDialog`, * `$mdBottomsheet` or `$mdSidenav`, which contains the autocomplete, is opening. <br/><br/> * Also the autocomplete will immediately focus the input element. * @param {boolean=} md-no-asterisk When present, asterisk will not be appended to the floating label * @param {boolean=} md-autoselect If true, the first item will be selected by default * @param {string=} md-menu-class This will be applied to the dropdown menu for styling * @param {string=} md-floating-label This will add a floating label to autocomplete and wrap it in * `md-input-container` * @param {string=} md-input-name The name attribute given to the input element to be used with * FormController * @param {string=} md-select-on-focus When present the inputs text will be automatically selected * on focus. * @param {string=} md-input-id An ID to be added to the input element * @param {number=} md-input-minlength The minimum length for the input's value for validation * @param {number=} md-input-maxlength The maximum length for the input's value for validation * @param {boolean=} md-select-on-match When set, autocomplete will automatically select exact * the item if the search text is an exact match * @param {boolean=} md-match-case-insensitive When set and using `md-select-on-match`, autocomplete * will select on case-insensitive match * * @usage * ### Basic Example * <hljs lang="html"> * <md-autocomplete * md-selected-item="selectedItem" * md-search-text="searchText" * md-items="item in getMatches(searchText)" * md-item-text="item.display"> * <span md-highlight-text="searchText">{{item.display}}</span> * </md-autocomplete> * </hljs> * * ### Example with "not found" message * <hljs lang="html"> * <md-autocomplete * md-selected-item="selectedItem" * md-search-text="searchText" * md-items="item in getMatches(searchText)" * md-item-text="item.display"> * <md-item-template> * <span md-highlight-text="searchText">{{item.display}}</span> * </md-item-template> * <md-not-found> * No matches found. * </md-not-found> * </md-autocomplete> * </hljs> * * In this example, our code utilizes `md-item-template` and `md-not-found` to specify the * different parts that make up our component. * * ### Example with validation * <hljs lang="html"> * <form name="autocompleteForm"> * <md-autocomplete * required * md-input-name="autocomplete" * md-selected-item="selectedItem" * md-search-text="searchText" * md-items="item in getMatches(searchText)" * md-item-text="item.display"> * <md-item-template> * <span md-highlight-text="searchText">{{item.display}}</span> * </md-item-template> * <div ng-messages="autocompleteForm.autocomplete.$error"> * <div ng-message="required">This field is required</div> * </div> * </md-autocomplete> * </form> * </hljs> * * In this example, our code utilizes `md-item-template` and `ng-messages` to specify * input validation for the field. */ function MdAutocomplete ($$mdSvgRegistry) { return { controller: 'MdAutocompleteCtrl', controllerAs: '$mdAutocompleteCtrl', scope: { inputName: '@mdInputName', inputMinlength: '@mdInputMinlength', inputMaxlength: '@mdInputMaxlength', searchText: '=?mdSearchText', selectedItem: '=?mdSelectedItem', itemsExpr: '@mdItems', itemText: '&mdItemText', placeholder: '@placeholder', noCache: '=?mdNoCache', selectOnMatch: '=?mdSelectOnMatch', matchInsensitive: '=?mdMatchCaseInsensitive', itemChange: '&?mdSelectedItemChange', textChange: '&?mdSearchTextChange', minLength: '=?mdMinLength', delay: '=?mdDelay', autofocus: '=?mdAutofocus', floatingLabel: '@?mdFloatingLabel', autoselect: '=?mdAutoselect', menuClass: '@?mdMenuClass', inputId: '@?mdInputId' }, link: function(scope, element, attrs, controller) { // Retrieve the state of using a md-not-found template by using our attribute, which will // be added to the element in the template function. controller.hasNotFound = !!element.attr('md-has-not-found'); }, template: function (element, attr) { var noItemsTemplate = getNoItemsTemplate(), itemTemplate = getItemTemplate(), leftover = element.html(), tabindex = attr.tabindex; // Set our attribute for the link function above which runs later. // We will set an attribute, because otherwise the stored variables will be trashed when // removing the element is hidden while retrieving the template. For example when using ngIf. if (noItemsTemplate) element.attr('md-has-not-found', true); // Always set our tabindex of the autocomplete directive to -1, because our input // will hold the actual tabindex. element.attr('tabindex', '-1'); return '\ <md-autocomplete-wrap\ layout="row"\ ng-class="{ \'md-whiteframe-z1\': !floatingLabel, \'md-menu-showing\': !$mdAutocompleteCtrl.hidden }">\ ' + getInputElement() + '\ <md-progress-linear\ class="' + (attr.mdFloatingLabel ? 'md-inline' : '') + '"\ ng-if="$mdAutocompleteCtrl.loadingIsVisible()"\ md-mode="indeterminate"></md-progress-linear>\ <md-virtual-repeat-container\ md-auto-shrink\ md-auto-shrink-min="1"\ ng-mouseenter="$mdAutocompleteCtrl.listEnter()"\ ng-mouseleave="$mdAutocompleteCtrl.listLeave()"\ ng-mouseup="$mdAutocompleteCtrl.mouseUp()"\ ng-hide="$mdAutocompleteCtrl.hidden"\ class="md-autocomplete-suggestions-container md-whiteframe-z1"\ ng-class="{ \'md-not-found\': $mdAutocompleteCtrl.notFoundVisible() }"\ role="presentation">\ <ul class="md-autocomplete-suggestions"\ ng-class="::menuClass"\ id="ul-{{$mdAutocompleteCtrl.id}}">\ <li md-virtual-repeat="item in $mdAutocompleteCtrl.matches"\ ng-class="{ selected: $index === $mdAutocompleteCtrl.index }"\ ng-click="$mdAutocompleteCtrl.select($index)"\ md-extra-name="$mdAutocompleteCtrl.itemName">\ ' + itemTemplate + '\ </li>' + noItemsTemplate + '\ </ul>\ </md-virtual-repeat-container>\ </md-autocomplete-wrap>\ <aria-status\ class="_md-visually-hidden"\ role="status"\ aria-live="assertive">\ <p ng-repeat="message in $mdAutocompleteCtrl.messages track by $index" ng-if="message">{{message}}</p>\ </aria-status>'; function getItemTemplate() { var templateTag = element.find('md-item-template').detach(), html = templateTag.length ? templateTag.html() : element.html(); if (!templateTag.length) element.empty(); return '<md-autocomplete-parent-scope md-autocomplete-replace>' + html + '</md-autocomplete-parent-scope>'; } function getNoItemsTemplate() { var templateTag = element.find('md-not-found').detach(), template = templateTag.length ? templateTag.html() : ''; return template ? '<li ng-if="$mdAutocompleteCtrl.notFoundVisible()"\ md-autocomplete-parent-scope>' + template + '</li>' : ''; } function getInputElement () { if (attr.mdFloatingLabel) { return '\ <md-input-container flex ng-if="floatingLabel">\ <label>{{floatingLabel}}</label>\ <input type="search"\ ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\ id="{{ inputId || \'fl-input-\' + $mdAutocompleteCtrl.id }}"\ name="{{inputName}}"\ autocomplete="off"\ ng-required="$mdAutocompleteCtrl.isRequired"\ ng-readonly="$mdAutocompleteCtrl.isReadonly"\ ng-minlength="inputMinlength"\ ng-maxlength="inputMaxlength"\ ng-disabled="$mdAutocompleteCtrl.isDisabled"\ ng-model="$mdAutocompleteCtrl.scope.searchText"\ ng-keydown="$mdAutocompleteCtrl.keydown($event)"\ ng-blur="$mdAutocompleteCtrl.blur()"\ ' + (attr.mdNoAsterisk != null ? 'md-no-asterisk="' + attr.mdNoAsterisk + '"' : '') + '\ ng-focus="$mdAutocompleteCtrl.focus($event)"\ aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\ ' + (attr.mdSelectOnFocus != null ? 'md-select-on-focus=""' : '') + '\ aria-label="{{floatingLabel}}"\ aria-autocomplete="list"\ role="combobox"\ aria-haspopup="true"\ aria-activedescendant=""\ aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\ <div md-autocomplete-parent-scope md-autocomplete-replace>' + leftover + '</div>\ </md-input-container>'; } else { return '\ <input flex type="search"\ ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\ id="{{ inputId || \'input-\' + $mdAutocompleteCtrl.id }}"\ name="{{inputName}}"\ ng-if="!floatingLabel"\ autocomplete="off"\ ng-required="$mdAutocompleteCtrl.isRequired"\ ng-disabled="$mdAutocompleteCtrl.isDisabled"\ ng-readonly="$mdAutocompleteCtrl.isReadonly"\ ng-model="$mdAutocompleteCtrl.scope.searchText"\ ng-keydown="$mdAutocompleteCtrl.keydown($event)"\ ng-blur="$mdAutocompleteCtrl.blur()"\ ng-focus="$mdAutocompleteCtrl.focus($event)"\ placeholder="{{placeholder}}"\ aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\ ' + (attr.mdSelectOnFocus != null ? 'md-select-on-focus=""' : '') + '\ aria-label="{{placeholder}}"\ aria-autocomplete="list"\ role="combobox"\ aria-haspopup="true"\ aria-activedescendant=""\ aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\ <button\ type="button"\ tabindex="-1"\ ng-if="$mdAutocompleteCtrl.scope.searchText && !$mdAutocompleteCtrl.isDisabled"\ ng-click="$mdAutocompleteCtrl.clear($event)">\ <md-icon md-svg-src="' + $$mdSvgRegistry.mdClose + '"></md-icon>\ <span class="_md-visually-hidden">Clear</span>\ </button>\ '; } } } }; }
'use strict'; var Benchmark = require('benchmark'), PubSub = require('../upubsub'), EventEmitter = require('events').EventEmitter, EventEmitter2 = require('eventemitter2').EventEmitter2; var pubsub = PubSub(); pubsub.subscribe('test', function () {}); var pubsubProduction = PubSub.Production(); pubsubProduction.subscribe('test', function () {}); var emitter = new EventEmitter(); emitter.on('test', function () {}); var emitter2 = new EventEmitter2(); emitter2.on('test', function () {}); new Benchmark.Suite() .add('uPubSub Production', function() { pubsubProduction.publish('test', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); }) .add('EventEmitter', function() { emitter.emit('test', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); }) .add('EventEmitter2', function() { emitter2.emit('test', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); }) .add('uPubSub', function() { pubsub.publish('test', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); }) .on('cycle', function(event, bench) { console.log(String(event.target)); }) .on('complete', function() { console.log('\nFastest is ' + this.filter('fastest').pluck('name')); }) .run(true);
describe('Text Field directives', function() { beforeEach(module('material.components.textField')); describe('- mdInputGroup', function() { var scope; beforeEach(function() { scope = { user : { firstName: 'Thomas', lastName: 'Burleson', email: 'ThomasBurleson@gmail.com', password: 'your password is incorrect' } }; }); it('should set input class for focus & blur', function() { var expressions = {label:"Firstname", model:"user.firstName"}, el = setupInputGroup( expressions, scope), input = el.find('input'); input.triggerHandler('focus'); expect(el.hasClass('md-input-focused')).toBe(true); input.triggerHandler('blur'); expect(el.hasClass('md-input-focused')).toBe(false); }); it('should set input class for input event', function() { var expressions = {label:"email", model:"user.email", type:"email"}, el = setupInputGroup( expressions, scope), input = el.find('input'); expect(el.hasClass('md-input-has-value')).toBe(true); input.val(''); input.triggerHandler('input'); expect(el.hasClass('md-input-has-value')).toBe(false); input.val('ThomasBurleson@gmail.com'); input.triggerHandler('input'); expect(el.hasClass('md-input-has-value')).toBe(true); }); it('should set input class for ngModel render', function() { var expressions = {label:"Firstname", model:"user.firstName"}, el = setupInputGroup( expressions, scope), input = el.find('input'); expect(el.hasClass('md-input-has-value')).toBe(true); input.scope().$apply('user.firstName = ""'); expect(el.hasClass('md-input-has-value')).toBe(false); input.scope().$apply('user.firstName = "Thomas"'); expect(el.hasClass('md-input-has-value')).toBe(true); }); }); describe(' - mdTextFloat', function() { var model; beforeEach(function() { model = { labels : { firstName: 'FirstName', lastName: 'LastName', email: 'eMail', password: 'Password' }, user : { firstName: 'Andrew', lastName: 'Joslin', email: 'AndrewJoslin@drifty.com', password: 'public' } }; }); it('should set input type `password` properly', function() { var el = setupTextFloat( { type:"password" }, model); expect( el.find('input').attr('type')).toBe("password"); expect( el.find('input').val()).toBe(""); }); it('should set input type `email` properly', function() { var el = setupTextFloat( { type:"email" }, model); expect( el.find('input').attr('type')).toBe("email"); expect( el.find('input').val()).toBe(""); }); it('should set a static label properly', function() { var el = setupTextFloat( { label:"motto" }, model); expect( el.find('label').text() ).toBe("motto"); expect( el.find('input').attr('type')).toBe("text"); expect( el.find('input').val()).toBe(""); }); it('should update a label from model changes.', function() { var markup ='<md-text-float ' + ' label="{{labels.firstName}}" ' + ' ng-model="user.firstName" >' + '</md-text-float>'; var el = buildElement( markup, model); expect( el.find('input').val() ).toBe("Andrew"); expect( el.find('label').text() ).toBe("FirstName"); // Change model value of the `firstName` [field] label // then check if the dom is updated var val2 = "Corporate Title:"; el.find('label').scope().$apply(function(){ model.labels.firstName = val2; }); expect( el.find('label').text() ).toBe( val2 ); }); it('should update an input value from model changes.', function() { var markup ='<md-text-float ' + ' label="{{labels.firstName}}" ' + ' ng-model="user.firstName" >' + '</md-text-float>'; var el = buildElement( markup, model); var input = el.find('input'); expect( input.val() ).toBe("Andrew"); var name = "AngularJS"; input.scope().$apply(function(){ model.user.firstName = name; }); expect( input.val() ).toBe( name ); }); // Breaks on IE xit('should update a model value from input changes.', function() { var markup ='<md-text-float ' + ' label="{{labels.firstName}}" ' + ' ng-model="user.firstName" >' + '</md-text-float>'; var el = buildElement( markup, model); var input = el.find('input'); expect( input.val() ).toBe( model.user.firstName ); input.val( "AngularJS" ); input.triggerHandler('input'); expect( model.user.firstName ).toBe( "AngularJS" ); }); it('should set input class for focus & blur', function() { var expressions = {label:"Firstname", model:"user.firstName"}, el = setupTextFloat( expressions, model), input = el.find('input'); input.triggerHandler('focus'); expect(el.hasClass('md-input-focused')).toBe(true); input.triggerHandler('blur'); expect(el.hasClass('md-input-focused')).toBe(false); }); it('should set input class for input event', function() { var expressions = {label:"password", model:"user.password", type:"password"}, el = setupTextFloat( expressions, model), input = el.find('input'); expect(el.hasClass('md-input-has-value')).toBe(true); input.val(''); input.triggerHandler('input'); expect(el.hasClass('md-input-has-value')).toBe(false); input.val('ThomasBurleson@gmail.com'); input.triggerHandler('input'); expect(el.hasClass('md-input-has-value')).toBe(true); }); it('should set input class for ngModel changes', function() { var expressions = {label:"Password", model:"user.password", type:"password"}, el = setupTextFloat( expressions, model), input = el.find('input'); expect(el.hasClass('md-input-has-value')).toBe(true); input.scope().$apply(function(){ model.user.password = ""; }); expect(el.hasClass('md-input-has-value')).toBe(false); input.scope().$apply(function() { model.user.password = "hiddenValley"; }); expect(el.hasClass('md-input-has-value')).toBe(true); }); it('should pair input and label for accessibility.', function() { var markup ='<md-text-float ' + ' md-fid="093" ' + ' label="{{labels.firstName}}" ' + ' ng-model="user.firstName" >' + '</md-text-float>'; var el = buildElement( markup, model); var input = el.find('input'); var label = el.find('label'); expect( label.attr('for') ).toBe( "093" ); expect( input.attr('id') ).toBe( label.attr('for') ); }); it('should auto-pair input and label for accessibility.', function() { var markup ='<md-text-float ' + ' label="{{labels.firstName}}" ' + ' ng-model="user.firstName" >' + '</md-text-float>'; var el = buildElement( markup, model); var input = el.find('input'); var label = el.find('label'); expect( label.attr('for') == "" ).toBe( false ); expect( input.attr('id') ).toBe( label.attr('for') ); }); it('should add an ARIA attribute for disabled inputs', function() { var markup ='<md-text-float ng-disabled="true" ' + ' label="{{labels.firstName}}" ' + ' ng-model="user.firstName" >' + '</md-text-float>'; var el = buildElement( markup, model); var input = el.find('input'); expect( input.attr('aria-disabled') ).toBe( 'true' ); }); }); // **************************************************************** // Utility `setup` methods // **************************************************************** var templates = { md_text_float : '<md-text-float ' + ' type="{{type}}" ' + ' label="{{label}}" ' + ' ng-model="{{model}}" >' + '</md-text-float>', md_input_group: '<div class="md-input-group" tabindex="-1">' + ' <label>{{label}}</label>' + ' <md-input id="{{id}}" type="{{type}}" ng-model="{{model}}"></md-input>' + '</div>' }; /** * Build a text float group using the `<md-input-group />` markup template */ function setupInputGroup(expressions, values) { values = angular.extend({},{type:"text", id:''},values||{}); return buildElement( templates.md_input_group, values, angular.extend({}, expressions||{})); } /** * Build a text float group using the `<md-text-float />` markup template */ function setupTextFloat(expressions, values) { values = angular.extend({ modelValue:"",type:'text' }, values || {}); var defaults = {model:"modelValue", label:""}; var tokens = angular.extend({}, defaults, expressions||{} ); return buildElement( templates.md_text_float, values, tokens ); } /** * Use the specified template markup, $compile to the DOM build * and link both the bindings and attribute assignments. * @returns {*} DOM Element */ function buildElement( template, scope, interpolationScope ) { var el; inject(function($compile, $interpolate, $rootScope) { scope = angular.extend( $rootScope.$new(), scope || {}); // First substitute interpolation values into the template... if any if ( interpolationScope ) { template = $interpolate( template )( interpolationScope ); } // Compile the template using the scope model(s) el = $compile( template )( scope ); $rootScope.$apply(); }); return el; } });
var Frame = require('./frame') , Hand = require('./hand') , Pointable = require('./pointable') , CircularBuffer = require("./circular_buffer") , Pipeline = require("./pipeline") , EventEmitter = require('events').EventEmitter , gestureListener = require('./gesture').gestureListener , _ = require('underscore'); /** * Constructs a Controller object. * * When creating a Controller object, you may optionally pass in options * to set the host , set the port, enable gestures, or select the frame event type. * * ```javascript * var controller = new Leap.Controller({ * host: '127.0.0.1', * port: 6437, * enableGestures: true, * frameEventName: 'animationFrame' * }); * ``` * * @class Controller * @memberof Leap * @classdesc * The Controller class is your main interface to the Leap Motion Controller. * * Create an instance of this Controller class to access frames of tracking data * and configuration information. Frame data can be polled at any time using the * [Controller.frame]{@link Leap.Controller#frame}() function. Call frame() or frame(0) to get the most recent * frame. Set the history parameter to a positive integer to access previous frames. * A controller stores up to 60 frames in its frame history. * * Polling is an appropriate strategy for applications which already have an * intrinsic update loop, such as a game. */ var Controller = module.exports = function(opts) { var inNode = (typeof(process) !== 'undefined' && process.versions && process.versions.node), controller = this; opts = _.defaults(opts || {}, { inNode: inNode }); this.inNode = opts.inNode; opts = _.defaults(opts || {}, { frameEventName: this.useAnimationLoop() ? 'animationFrame' : 'deviceFrame', suppressAnimationLoop: !this.useAnimationLoop(), loopWhileDisconnected: false, useAllPlugins: false }); this.animationFrameRequested = false; this.onAnimationFrame = function() { controller.emit('animationFrame', controller.lastConnectionFrame); if (controller.loopWhileDisconnected && (controller.connection.focusedState || controller.connection.opts.background) ){ window.requestAnimationFrame(controller.onAnimationFrame); }else{ controller.animationFrameRequested = false; } } this.suppressAnimationLoop = opts.suppressAnimationLoop; this.loopWhileDisconnected = opts.loopWhileDisconnected; this.frameEventName = opts.frameEventName; this.useAllPlugins = opts.useAllPlugins; this.history = new CircularBuffer(200); this.lastFrame = Frame.Invalid; this.lastValidFrame = Frame.Invalid; this.lastConnectionFrame = Frame.Invalid; this.accumulatedGestures = []; if (opts.connectionType === undefined) { this.connectionType = (this.inBrowser() ? require('./connection/browser') : require('./connection/node')); } else { this.connectionType = opts.connectionType; } this.connection = new this.connectionType(opts); this.plugins = {}; this._pluginPipelineSteps = {}; this._pluginExtendedMethods = {}; if (opts.useAllPlugins) this.useRegisteredPlugins(); this.setupConnectionEvents(); } Controller.prototype.gesture = function(type, cb) { var creator = gestureListener(this, type); if (cb !== undefined) { creator.stop(cb); } return creator; } /* * @returns the controller */ Controller.prototype.setBackground = function(state) { this.connection.setBackground(state); return this; } Controller.prototype.inBrowser = function() { return !this.inNode; } Controller.prototype.useAnimationLoop = function() { return this.inBrowser() && !this.inBackgroundPage(); } Controller.prototype.inBackgroundPage = function(){ // http://developer.chrome.com/extensions/extension#method-getBackgroundPage return (typeof(chrome) !== "undefined") && chrome.extension && chrome.extension.getBackgroundPage && (chrome.extension.getBackgroundPage() === window) } /* * @returns the controller */ Controller.prototype.connect = function() { this.connection.connect(); return this; } Controller.prototype.runAnimationLoop = function(){ if (!this.suppressAnimationLoop && !this.animationFrameRequested) { this.animationFrameRequested = true; window.requestAnimationFrame(this.onAnimationFrame); } } /* * @returns the controller */ Controller.prototype.disconnect = function() { this.connection.disconnect(); return this; } /** * Returns a frame of tracking data from the Leap. * * Use the optional history parameter to specify which frame to retrieve. * Call frame() or frame(0) to access the most recent frame; call frame(1) to * access the previous frame, and so on. If you use a history value greater * than the number of stored frames, then the controller returns an invalid frame. * * @method frame * @memberof Leap.Controller.prototype * @param {number} history The age of the frame to return, counting backwards from * the most recent frame (0) into the past and up to the maximum age (59). * @returns {Leap.Frame} The specified frame; or, if no history * parameter is specified, the newest frame. If a frame is not available at * the specified history position, an invalid Frame is returned. */ Controller.prototype.frame = function(num) { return this.history.get(num) || Frame.Invalid; } Controller.prototype.loop = function(callback) { switch (callback.length) { case 1: this.on(this.frameEventName, callback); break; case 2: var controller = this; var scheduler = null; var immediateRunnerCallback = function(frame) { callback(frame, function() { if (controller.lastFrame != frame) { immediateRunnerCallback(controller.lastFrame); } else { controller.once(controller.frameEventName, immediateRunnerCallback); } }); } this.once(this.frameEventName, immediateRunnerCallback); break; } return this.connect(); } Controller.prototype.addStep = function(step) { if (!this.pipeline) this.pipeline = new Pipeline(this); this.pipeline.addStep(step); } // this is run on every deviceFrame Controller.prototype.processFrame = function(frame) { if (frame.gestures) { this.accumulatedGestures = this.accumulatedGestures.concat(frame.gestures); } // lastConnectionFrame is used by the animation loop this.lastConnectionFrame = frame; this.runAnimationLoop(); this.emit('deviceFrame', frame); } // on a this.deviceEventName (usually 'animationFrame' in browsers), this emits a 'frame' Controller.prototype.processFinishedFrame = function(frame) { this.lastFrame = frame; if (frame.valid) { this.lastValidFrame = frame; } frame.controller = this; frame.historyIdx = this.history.push(frame); if (frame.gestures) { frame.gestures = this.accumulatedGestures; this.accumulatedGestures = []; for (var gestureIdx = 0; gestureIdx != frame.gestures.length; gestureIdx++) { this.emit("gesture", frame.gestures[gestureIdx], frame); } } if (this.pipeline) { frame = this.pipeline.run(frame); if (!frame) frame = Frame.Invalid; } this.emit('frame', frame); } Controller.prototype.setupConnectionEvents = function() { var controller = this; this.connection.on('frame', function(frame) { controller.processFrame(frame); }); this.on(this.frameEventName, function(frame) { controller.processFinishedFrame(frame); }); // Delegate connection events this.connection.on('disconnect', function() { controller.emit('disconnect'); }); this.connection.on('ready', function() { controller.emit('ready'); }); this.connection.on('connect', function() { controller.emit('connect'); }); this.connection.on('focus', function() { controller.emit('focus'); controller.runAnimationLoop(); }); this.connection.on('blur', function() { controller.emit('blur') }); this.connection.on('protocol', function(protocol) { controller.emit('protocol', protocol); }); this.connection.on('deviceConnect', function(evt) { controller.emit(evt.state ? 'deviceConnected' : 'deviceDisconnected'); }); } Controller._pluginFactories = {}; /* * Registers a plugin, making is accessible to controller.use later on. * * @member plugin * @memberof Leap.Controller.prototype * @param {String} name The name of the plugin (usually camelCase). * @param {function} factory A factory method which will return an instance of a plugin. * The factory receives an optional hash of options, passed in via controller.use. * * Valid keys for the object include frame, hand, finger, tool, and pointable. The value * of each key can be either a function or an object. If given a function, that function * will be called once for every instance of the object, with that instance injected as an * argument. This allows decoration of objects with additional data: * * ```javascript * Leap.Controller.plugin('testPlugin', function(options){ * return { * frame: function(frame){ * frame.foo = 'bar'; * } * } * }); * ``` * * When hand is used, the callback is called for every hand in `frame.hands`. Note that * hand objects are recreated with every new frame, so that data saved on the hand will not * persist. * * ```javascript * Leap.Controller.plugin('testPlugin', function(){ * return { * hand: function(hand){ * console.log('testPlugin running on hand ' + hand.id); * } * } * }); * ``` * * A factory can return an object to add custom functionality to Frames, Hands, or Pointables. * The methods are added directly to the object's prototype. Finger and Tool cannot be used here, Pointable * must be used instead. * This is encouraged for calculations which may not be necessary on every frame. * Memoization is also encouraged, for cases where the method may be called many times per frame by the application. * * ```javascript * // This plugin allows hand.usefulData() to be called later. * Leap.Controller.plugin('testPlugin', function(){ * return { * hand: { * usefulData: function(){ * console.log('usefulData on hand', this.id); * // memoize the results on to the hand, preventing repeat work: * this.x || this.x = someExpensiveCalculation(); * return this.x; * } * } * } * }); * * Note that the factory pattern allows encapsulation for every plugin instance. * * ```javascript * Leap.Controller.plugin('testPlugin', function(options){ * options || options = {} * options.center || options.center = [0,0,0] * * privatePrintingMethod = function(){ * console.log('privatePrintingMethod - options', options); * } * * return { * pointable: { * publicPrintingMethod: function(){ * privatePrintingMethod(); * } * } * } * }); * */ Controller.plugin = function(pluginName, factory) { if (this._pluginFactories[pluginName]) { throw "Plugin \"" + pluginName + "\" already registered"; } return this._pluginFactories[pluginName] = factory; }; /* * Returns a list of registered plugins. * @returns {Array} Plugin Factories. */ Controller.plugins = function() { return _.keys(this._pluginFactories); }; /* * Begin using a registered plugin. The plugin's functionality will be added to all frames * returned by the controller (and/or added to the objects within the frame). * - The order of plugin execution inside the loop will match the order in which use is called by the application. * - The plugin be run for both deviceFrames and animationFrames. * * If called a second time, the options will be merged with those of the already instantiated plugin. * * @method use * @memberOf Leap.Controller.prototype * @param pluginName * @param {Hash} Options to be passed to the plugin's factory. * @returns the controller */ Controller.prototype.use = function(pluginName, options) { var functionOrHash, pluginFactory, key, pluginInstance, klass; pluginFactory = (typeof pluginName == 'function') ? pluginName : Controller._pluginFactories[pluginName]; if (!pluginFactory) { throw 'Leap Plugin ' + pluginName + ' not found.'; } options || (options = {}); if (this.plugins[pluginName]){ _.extend(this.plugins[pluginName], options) return this; } this.plugins[pluginName] = options; pluginInstance = pluginFactory.call(this, options); for (key in pluginInstance) { functionOrHash = pluginInstance[key]; if (typeof functionOrHash === 'function') { if (!this.pipeline) this.pipeline = new Pipeline(this); if (!this._pluginPipelineSteps[pluginName]) this._pluginPipelineSteps[pluginName] = []; this._pluginPipelineSteps[pluginName].push( this.pipeline.addWrappedStep(key, functionOrHash) ); } else { if (!this._pluginExtendedMethods[pluginName]) this._pluginExtendedMethods[pluginName] = []; switch (key) { case 'frame': klass = Frame break; case 'hand': klass = Hand break; case 'pointable': klass = Pointable break; default: throw pluginName + ' specifies invalid object type "' + key + '" for prototypical extension' } _.extend(klass.prototype, functionOrHash); _.extend(klass.Invalid, functionOrHash); this._pluginExtendedMethods[pluginName].push([klass, functionOrHash]) } } return this; }; /* * Stop using a used plugin. This will remove any of the plugin's pipeline methods (those called on every frame) * and remove any methods which extend frame-object prototypes. * * @method stopUsing * @memberOf Leap.Controller.prototype * @param pluginName * @returns the controller */ Controller.prototype.stopUsing = function (pluginName) { var steps = this._pluginPipelineSteps[pluginName], extMethodHashes = this._pluginExtendedMethods[pluginName], i = 0, klass, extMethodHash; if (!this.plugins[pluginName]) return; if (steps) { for (i = 0; i < steps.length; i++) { this.pipeline.removeStep(steps[i]); } } if (extMethodHashes){ for (i = 0; i < extMethodHashes.length; i++){ klass = extMethodHashes[i][0] extMethodHash = extMethodHashes[i][1] for (var methodName in extMethodHash) { delete klass.prototype[methodName] delete klass.Invalid[methodName] } } } delete this.plugins[pluginName] return this; } Controller.prototype.useRegisteredPlugins = function(){ for (var plugin in Controller._pluginFactories){ this.use(plugin); } } _.extend(Controller.prototype, EventEmitter.prototype);
const { CLASSES } = require("hoctable/hoc/menu"); module.exports = function(bag) { const dom = { get menu() { let { popups } = bag.dom; return popups && popups.querySelector("[data-rel=menu-body]"); }, custom: { get button() { let { container } = bag.dom; return container && container.querySelector("[data-rel=button]"); } }, default: { get button() { let { container } = bag.dom; return container && container.querySelector(`.${CLASSES.MENU_DEFAULT_BUTTON}`); } } }; return dom; };
import DomHelper from '../view/dom-helper.js'; /** * Controls all audio logic */ export default class AudioController { constructor() { this.isMuted = false; this.deathSound = new Audio('assets/death.wav'); this.killSound = new Audio('assets/kill.wav'); this.foodCollectedSound = new Audio('assets/food-consumed.wav'); this.swapSound = new Audio('assets/swap.wav'); DomHelper.getVolumeSlider().addEventListener('input', this.updateVolume.bind(this)); } playDeathSound() { if (!this.isMuted) { this.deathSound.play(); } } playFoodCollectedSound() { if (!this.isMuted) { this.foodCollectedSound.play(); } } playKillSound() { if (!this.isMuted) { this.killSound.play(); } } playSwapSound() { if (!this.isMuted) { this.swapSound.play(); } } updateVolume() { const volume = DomHelper.getVolumeSlider().value; this.deathSound.volume = volume; this.foodCollectedSound.volume = volume; this.killSound.volume = volume; this.swapSound.volume = volume; } toggleMute() { this.isMuted = !this.isMuted; } }
(function () { "use strict"; function $extend(from, fields) { function Inherit() {} Inherit.prototype = from; var proto = new Inherit(); for (var name in fields) proto[name] = fields[name]; if( fields.toString !== Object.prototype.toString ) proto.toString = fields.toString; return proto; } var Main = function() { this.sortModes = ["None","Simple","Topological"]; this.sorted = 0; this.game = new Phaser.Game(800,400,Phaser.AUTO,"test",{ preload : $bind(this,this.preload), create : $bind(this,this.create), update : $bind(this,this.update), render : $bind(this,this.render)}); }; Main.__name__ = true; Main.main = function() { new Main(); }; Main.prototype = { preload: function() { this.game.load.image("cube","assets/cube.png"); this.game.time.advancedTiming = true; this.game.plugins.add(new Phaser.Plugin.Isometric(this.game)); this.game.iso.anchor.setTo(0.5,0.2); } ,create: function() { this.isoGroup = this.game.add.group(); var cube; var xx = 256; var yy; while(xx > 0) { yy = 256; while(yy > 0) { cube = new MyIsoSprite(this.game,xx,yy,0,"cube",0); this.game.add.existing(cube); this.isoGroup.add(cube); cube.oldZ = cube.z; this.game.add.tween(cube).to({ isoX : 256 - xx + 32},2000,Phaser.Easing.Quadratic.InOut,true,0,Math.POSITIVE_INFINITY,true); yy -= 48; } xx -= 48; } this.game.input.onDown.add($bind(this,this.onDown)); } ,onDown: function() { this.sorted = (this.sorted + 1) % 3; } ,update: function() { if(this.sorted == 0) this.isoGroup.sort("oldZ"); else if(this.sorted == 1) this.game.iso.simpleSort(this.isoGroup); else this.game.iso.topologicalSort(this.isoGroup); } ,render: function() { this.game.debug.text("Click to toggle! Sort mode: " + this.sortModes[this.sorted],2,36,"#ffffff"); this.game.debug.text(Std.string(this.game.time.fps),2,14,"#a7aebe"); } }; Math.__name__ = true; var MyIsoSprite = function(game,x,y,z,key,frame) { Phaser.Plugin.Isometric.IsoSprite.call(this,game,x,y,z,key,frame); this.anchor.set(0.5); }; MyIsoSprite.__name__ = true; MyIsoSprite.__super__ = Phaser.Plugin.Isometric.IsoSprite; MyIsoSprite.prototype = $extend(Phaser.Plugin.Isometric.IsoSprite.prototype,{ }); var Std = function() { }; Std.__name__ = true; Std.string = function(s) { return js.Boot.__string_rec(s,""); }; var js = {}; js.Boot = function() { }; js.Boot.__name__ = true; js.Boot.__string_rec = function(o,s) { if(o == null) return "null"; if(s.length >= 5) return "<...>"; var t = typeof(o); if(t == "function" && (o.__name__ || o.__ename__)) t = "object"; switch(t) { case "object": if(o instanceof Array) { if(o.__enum__) { if(o.length == 2) return o[0]; var str = o[0] + "("; s += "\t"; var _g1 = 2; var _g = o.length; while(_g1 < _g) { var i = _g1++; if(i != 2) str += "," + js.Boot.__string_rec(o[i],s); else str += js.Boot.__string_rec(o[i],s); } return str + ")"; } var l = o.length; var i1; var str1 = "["; s += "\t"; var _g2 = 0; while(_g2 < l) { var i2 = _g2++; str1 += (i2 > 0?",":"") + js.Boot.__string_rec(o[i2],s); } str1 += "]"; return str1; } var tostr; try { tostr = o.toString; } catch( e ) { return "???"; } if(tostr != null && tostr != Object.toString) { var s2 = o.toString(); if(s2 != "[object Object]") return s2; } var k = null; var str2 = "{\n"; s += "\t"; var hasp = o.hasOwnProperty != null; for( var k in o ) { if(hasp && !o.hasOwnProperty(k)) { continue; } if(k == "prototype" || k == "__class__" || k == "__super__" || k == "__interfaces__" || k == "__properties__") { continue; } if(str2.length != 2) str2 += ", \n"; str2 += s + k + " : " + js.Boot.__string_rec(o[k],s); } s = s.substring(1); str2 += "\n" + s + "}"; return str2; case "function": return "<function>"; case "string": return o; default: return String(o); } }; var phaser = {}; phaser.plugin = {}; phaser.plugin.isometric = {}; phaser.plugin.isometric.IsoUtils = function() { }; phaser.plugin.isometric.IsoUtils.__name__ = true; phaser.plugin.isometric.IsoUtils.octree = function(obj,octree,color) { if(color == null) color = "rgba(255,0,0,0.3)"; return obj.octree(octree,color); }; phaser.plugin.isometric.IsoUtils.iso = function(obj) { return obj.iso; }; phaser.plugin.isometric.IsoUtils.isoArcade = function(obj) { return obj.isoArcade; }; phaser.plugin.isometric.IsoUtilsGameObjectCreator = function() { }; phaser.plugin.isometric.IsoUtilsGameObjectCreator.__name__ = true; phaser.plugin.isometric.IsoUtilsGameObjectCreator.isoSprite = function(obj,x,y,z,key,frame) { return obj.isoSprite(x,y,z,key,frame); }; phaser.plugin.isometric.IsoUtilsGameObjectFactory = function() { }; phaser.plugin.isometric.IsoUtilsGameObjectFactory.__name__ = true; phaser.plugin.isometric.IsoUtilsGameObjectFactory.isoSprite = function(obj,x,y,z,key,frame,group) { return obj.isoSprite(x,y,z,key,frame,group); }; phaser.plugin.isometric.IsoUtilsDebug = function() { }; phaser.plugin.isometric.IsoUtilsDebug.__name__ = true; phaser.plugin.isometric.IsoUtilsDebug.isoSprite = function(obj,sprite,color,filled) { if(filled == null) filled = true; if(color == null) color = "rgba(0,255,0,0.4)"; return obj.isoSprite(sprite,color,filled); }; var $_, $fid = 0; function $bind(o,m) { if( m == null ) return null; if( m.__id__ == null ) m.__id__ = $fid++; var f; if( o.hx__closures__ == null ) o.hx__closures__ = {}; else f = o.hx__closures__[m.__id__]; if( f == null ) { f = function(){ return f.method.apply(f.scope, arguments); }; f.scope = o; f.method = m; o.hx__closures__[m.__id__] = f; } return f; } Math.NaN = Number.NaN; Math.NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY; Math.POSITIVE_INFINITY = Number.POSITIVE_INFINITY; Math.isFinite = function(i) { return isFinite(i); }; Math.isNaN = function(i1) { return isNaN(i1); }; String.__name__ = true; Array.__name__ = true; Main.main(); })(); //# sourceMappingURL=IsoPhaser.js.map
"use strict"; /** * Created by Papa on 8/27/2016. */ var OracleAdaptor = (function () { function OracleAdaptor(sqlValueProvider) { this.sqlValueProvider = sqlValueProvider; } OracleAdaptor.prototype.getParameterReference = function (parameterReferences, newReference) { throw "Not implemented"; }; OracleAdaptor.prototype.dateToDbQuery = function (date) { var dateString = date.toJSON(); dateString = dateString.replace('Z', ''); return "trunc(to_timestamp_tz('" + dateString + ".GMT','YYYY-MM-DD\"T\"HH24:MI:SS.FF3.TZR'))"; }; OracleAdaptor.prototype.getResultArray = function (rawResponse) { throw "Not implemented - getResultArray"; }; OracleAdaptor.prototype.getResultCellValue = function (resultRow, columnName, index, dataType, defaultValue) { throw "Not implemented - getResultCellValue"; }; OracleAdaptor.prototype.getFunctionAdaptor = function () { throw "Not implemented getFunctionAdaptor"; }; OracleAdaptor.prototype.getOffsetFragment = function (offset) { throw "Not implemented"; }; OracleAdaptor.prototype.getLimitFragment = function (limit) { throw "Not implemented"; }; return OracleAdaptor; }()); exports.OracleAdaptor = OracleAdaptor; //# sourceMappingURL=OracleAdaptor.js.map
'use strict'; var Lab = require('lab'), Hapi = require('hapi'), Plugin = require('../../../lib/plugins/DJCordhose'); var describe = Lab.experiment; var it = Lab.test; var expect = Lab.expect; var before = Lab.before; var after = Lab.after; describe('DJCordhose', function() { var server = new Hapi.Server(); it('Plugin successfully loads', function(done) { server.pack.register(Plugin, function(err) { expect(err).to.not.exist; done(); }); }); it('Plugin registers routes', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/DJCordhose'); done(); }); it('Plugin route responses', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/DJCordhose'); var request = { method: 'GET', url: '/DJCordhose' }; server.inject(request, function(res) { expect(res.statusCode).to.equal(200); expect(res.result).to.equal('don\'t worry, be hapi!'); done(); }); }); });
/** * webpack config */ let webpack = require('webpack'); let ShakePlugin = require('webpack-common-shake').Plugin; let path = require('path'); let BannerPlugin = webpack.BannerPlugin; module.exports = function createConfig(option) { let {entry, outFilename, outLibrary, codeTreeShaking, mode} = option || {}; let plugins = [new BannerPlugin({ banner: 'Froguard(figure_wf@163.com)\nhttps://github.com/Froguard/json-toy\nlicense MIT', entryOnly: true })]; let devtool = false; if (codeTreeShaking) { plugins = plugins.concat(new ShakePlugin({ warnings: { global: true, module: false } })); } // export webpack config return { mode: mode || 'development', entry, devtool, plugins, output: { path: path.join(__dirname, '../dist'), filename: outFilename, library: outLibrary || '[name]', //['__api__','pages','[name]'] 方案二:'' libraryTarget: 'umd', // 方案二:'var' globalObject: 'this' }, module: { rules: [{ test: /\.js$/, use: [{ loader: 'babel-loader', //need:babel-loader @babel/core @babel/preset-es2015 options: { presets: [ [ '@babel/preset-env', { loose: true, // 转es5 modules: codeTreeShaking ? false : 'commonjs' // true-转换module, false-禁止babel将es6的module转化成commonjs } ] ], comments: false } }], exclude: /(node_modules|bower_components)/ }] }, resolve: { extensions: ['.js'] }, // optimization: { // minimize: minimize, // sideEffects: true, // // usedExports: false // }, }; };
if(!steal.build){ steal.build = {}; } steal('steal', 'steal/build/share', 'steal/build/js', 'steal/build/css', 'steal/build/open', function( steal, shareUtil ) { /** * @function steal.build.apps * @parent steal.build */ var apps = steal.build.apps = function( list, buildOptions ) { buildOptions = steal.opts(buildOptions || {}, { //folder to build to, defaults to the folder the page is in to: 1 }); // set the compressor globally //steal.build.compressor = steal.build.builders.scripts.compressors[options.compressor || "localClosure"](); //set defaults buildOptions.to = buildOptions.to || "packages/" // check if path exists var dest = steal.config('root').join(buildOptions.to); if(!dest.exists()){ var dir = dest.dir(); dest.mkdir(); } buildOptions.depth = buildOptions.depth || Infinity; if(buildOptions.depth < 2){ steal.print("Depth must be 2 or greater. depth=2 means every app loads its production "+ "file and a single common package shared by all."); quit() } var options = { appFiles : [], files : {}, // tells it to only do app file multipleOpens: true } // opens each app and add its dependencies to options steal.build.apps.open(list, options, function(options){ apps.makePackages(options, buildOptions); }) }; // only add files to files, but recurse through fns steal.extend(steal.build.apps, { /** * Opens se * @param {Array} appNames * @param {Object} options An object that * has an appFiles array, and a files object. * * {appFiles : [], files: {}} * * It can also have other properties like: * * - newPage - open in a new page or do not * * @param {Function} callback(options) */ open : function(appNames,options, callback){ options = options || {}; options.appFiles = options.appFiles || []; options.files = options.files || {}; var APPS = this, i = 0, // calls make for each app // then calls makePackages once done callNext = function(){ if( i< appNames.length ) { i++; APPS._open(appNames[i-1],options, callNext ); } else { callback(options); } }; callNext(); }, // opens one app, adds dependencies _open : function(appName, options, callback){ //= Configure what we are going to load from APP name // if we have html, get the app-name var html = 'steal/rhino/blank.html', data = {env: 'development'}; if(appName.indexOf('.html') > 2){ html = appName; appName = null; } else { appName = steal.id(appName); data = { startId: appName } } // use last steal to load page if(options.newPage === false && options.steal){ steal.print(" stealing " + ( data.startId ) ); // move steal back var curSteal = window.steal, newSteal = window.steal= options.steal; // listen to when this is done window.steal.one("end", function(rootSteal){ options.appFiles.push( apps.addDependencies(rootSteal.dependencies[0], options, appName ) ); // set back steal window.steal = curSteal; callback(options, { steal : newSteal, rootSteal: rootSteal, firstSteal: steal.build.open.firstSteal(rootSteal) }); }) // steal file window.steal({id: data.startId}); } else { steal.print(" opening " + ( appName || html) ); steal.build.open(html, data, function(opener){ steal.print(" adding dependencies"); if(options.multipleOpens){ var firstDependency = opener.rootSteal.dependencies[3] } else { var firstDependency = opener.rootSteal; } var appFile = apps.addDependencies(firstDependency, options, appName ); options.appFiles.push( appFile ); options.steal = opener.steal; steal.print(" ") callback(options, opener); }) } }, /** * Gets a steal instance and recursively sets up a __files__ object with * __file__ objects for each steal that represents a resource (not a function). * * A __file__ object is a recursive mapping of a steal * instances's options and dependencies. Different apps have different * steal instances for the same resource. This _should_ be merging those attributes * and maintaining a collection of the apps the file exists on. * * { * // the apps this steal is on * appNames: [], * dependencyFileNames: [ "jquery/class/class.js" ], * packaged: false, * stealOpts: steal.options * } * * A __files__ object maps each file's location to a file. * * { * "jquery/controller/controller.js" : file1, * "jquery/class/class.js" : file2 * } * * @param {steal} steel a steal instance * @param {Object} files the files mapping that gets filled out * @param {String} appName the appName * @return {file} the root dependency file for this application */ addDependencies: function( resource, options, appName ) { //print(" "+resource.options.id+":"+appName) var id = resource.options.id, buildType = resource.options.buildType, file = maker(options.files, id || appName, function(){ //clean and minifify everything right away ... var source = ''; if( id && resource.options.buildType != 'fn' ) { // some might not have source yet steal.print(" + "+id ); // convert using steal's root because that might have been configured var source = resource.options.text || readFile( steal.idToUri( resource.options.id ) ); } resource.options.text = resource.options.text || source // this becomes data return { // todo, might need to merge options // what if we should not 'steal' it? stealOpts: resource.options, appNames: [], dependencyFileNames: [], packaged: false } }); // don't add the same appName more than once // don't add a resource to itself if(id && appName && file.appNames.indexOf(appName) == -1){ file.appNames.push(appName); } resource.needsDependencies.forEach(function(dependency){ // TODO: check status if (dependency && dependency.dependencies && // don't follow functions dependency.options.buildType != 'fn' && !dependency.options.ignore) { file.dependencyFileNames.push(dependency.options.id) apps.addDependencies(dependency, options, appName); } }); resource.dependencies.forEach(function(dependency){ // TODO: check status if (dependency && dependency.dependencies && // don't follow functions dependency.options.buildType != 'fn' && !dependency.options.ignore) { file.dependencyFileNames.push(dependency.options.id) apps.addDependencies(dependency, options, appName); } }); return file; }, order: function( options ) { var order = 0 function visit( f ) { if ( f.order === undefined ) { f.dependencyFileNames.forEach(function(fileName){ visit( options.files[fileName] ) }) f.order = (order++); } } options.appFiles.forEach(function(file){ visit(file) }); }, /** * @hide * * Goes through the files, makes a __shared__ array of * __sharedSets__. Each * sharedSet is a collection of __sharings__. It then * takes the last __sharedSet__, finds the __sharing__ * with the largest totalSize, and returns that * __sharing__. * * A __sharing__ is a collection of files that are shared between some * set of applications. A 2-order sharing might look like: * * {totalSize: 1231, files: [file1, file2], appNames: ['foo','bar']} * * A sharedSet is collection of sharings that are all shared the * same number of times (order). For example, a sharedSet might have all * 4-order 'sharings', that is files that are shared between * 4 applications. A 2 order sharedSet might look like: * * { * 'foo,bar' : {totalSize: 1231, files: [], appNames: ['foo','bar']} * 'bar,car': : {totalSize: 31231, files: [], appNames: ['bar','car']} * } * * The __shared__ array is an collection of sharedSets ordered by the * order-number (the number of times a file is shared by an application). * * ## How it works * * getMostShared is designed to be called until all files have been * marked packaged. Thus, it changes the files by marking files * as packaged. * * @param {Object} files - the files object. * @return {sharing} The sharing object: * * { * // apps that need this * appNames : ['cookbook','mxui/grid','mxui/data/list'], * files : [{file1}, {file2}] * } */ getMostShared: function( files ) { // create an array of sharedSets // A shared set is // a collection of var shared = []; // count // go through each file // find the 'most' shared one // package that for ( var fileName in files ) { var file = files[fileName]; if ( file.packaged ) { continue; } // shared is like: // [ // 1: { // 'foo' : // }, // 2 : { // 'foo,bar' : {totalSize: 1231, files: [], appNames: ['foo','bar']} // 'bar,car': // } // get an object to represent combinations var sharedSet = maker(shared, file.appNames.length, {}), // a name for the combo appsName = file.appNames.sort().join(), // a pack is data for a specific appNames combo sharing = maker(sharedSet, appsName, function(){ return { totalSize: 0, files: [], appNames: file.appNames } }); sharing.files.push(file); sharing.totalSize += file.stealOpts.text.length; } if (!shared.length ) { return null; } // get the highest shared number var mostShared = shared.pop(), mostSize = 0, most; // go through each app combo, get the one that has // the bigest size for ( var apps in mostShared ) { if ( mostShared[apps].totalSize > mostSize ) { most = mostShared[apps]; mostSize = most.totalSize; } } //mark files as packaged most.files.forEach(function(f){ f.packaged = true; }); // order the files by when they should be included most.files = most.files.sort(function( f1, f2 ) { return f1.order - f2.order; }); return most; }, /** * Creates packages that can be downloaded. * * Recursively uses getMostShared to pull out * the largest __sharing__. It * makes a package of the sharing and marks * the apps that need that sharing. * * The apps that need the sharing * * packages are mostly dummy things. * * a production file might steal multiple packages. * * say package A and package B * * say package A has jQuery * * so, the production file has code like: * * steal('jquery') * * It needs to know to not load jQuery * * this is where 'has' comes into place * * steal({id: 'packageA', has: 'jquery'}) * * This wires up steal to wait until package A is finished for jQuery. * * So, we need to know all the packages and app needs, and all the things in that package. * * @param {appFiles} appFiles * @param {files} files */ makePackages: function(options, buildOptions) { steal.print("Making packages") //add an order number so we can sort them nicely apps.order(options); // will be set to the biggest group var sharing, /* * Packages that an app should have * { * 'cookbook' : ['packages/0.js'] * } */ appsPackages = {}, /* * Files a package has * { * 'packages/0.js' : ['jquery/jquery.js'] * } * this is used to mark all of these * things as loading, so steal doesn't try to load them * b/c the package is loading */ packagesFiles = {}; // make an array for each appName that will contain the packages // it needs to load options.appFiles.forEach(function(file){ appsPackages[file.appNames[0]] = []; }); // remove stealconfig.js temporarily. It will be added to every production.js var stealconfig = { stealOpts: { text: readFile('stealconfig.js'), id: steal.URI("stealconfig.js"), buildType: "js" }, appNames: [], dependencyFileNames: [], packaged: false }, shares = []; delete options.files['stealconfig.js']; while(sharing = apps.getMostShared(options.files)){ shares.push(sharing); }; shareUtil.flatten(shares, buildOptions.depth); //while there are files left to be packaged, get the most shared and largest package shares.forEach(function(sharing){ steal.print('\npackaging shared by ' + sharing.appNames.join(", ")) var appsName = sharing.appNames[0], // the name of the file we are making. // If there is only one app it's an app's production.js // If there are multiple apps, it's a package packageName = makePackageName(sharing.appNames) // if there's multiple apps (it's a package), add this to appsPackages for each app if( sharing.appNames.length > 1) { sharing.appNames.forEach(function(appName){ appsPackages[appName].push(packageName+".js") // we might need to do this // if there is css }) } // add the files to this package packagesFiles[packageName+".js"] =[]; // what we will sent to js.makePackage // the files that will actually get packaged var filesForPackaging = []; sharing.files.forEach(function(file){ // add the files to the packagesFiles packagesFiles[packageName+".js"].push(file.stealOpts.id); filesForPackaging.push(file.stealOpts) steal.print(" " + file.order + ":" + file.stealOpts.id); }); // create dependencies object var dependencies = {}; // only add dependencies for the 'root' objects if( sharing.appNames.length == 1) { packagesFiles[packageName+".js"].unshift("stealconfig.js"); filesForPackaging.unshift(stealconfig.stealOpts); // for the packages for this app appsPackages[appsName].forEach(function(packageName){ // add this as a dependency dependencies[packageName] = packagesFiles[packageName].slice(0) }); } //the source of the package var pack = steal.build.js.makePackage(filesForPackaging, dependencies,packageName+ ".css", options.exclude) //save the file steal.print("saving " + steal.config('root').join(packageName+".js")); steal.config('root').join(packageName+".js").save( pack.js ); if(pack.css){ steal.print("saving " + steal.config('root').join(packageName+".css")); steal.config('root').join(packageName+".css").save( pack.css.code ); } }) } }) // sets prop on root if it doesn't exist // root - the object // prop - the property to set some other object as // raw - the data you want to set or a function that returns the object // cb - a callback that gets called with the object var maker = function(root, prop, raw, cb){ if(!root[prop]){ root[prop] = ( typeof raw === 'object' ? steal.extend({},raw) : raw() ); } cb && cb( root[prop] ) return root[prop]; } var makePackageName = function(appModuleIds){ if( appModuleIds.length == 1 ){ // this needs to go in that app's production var filename = steal.URI(appModuleIds).filename().replace(/\.js$/,""), folder = steal.URI(appModuleIds).dir().filename(); if( filename == folder ){ return (appModuleIds[0]+"").replace(/\/[^\/]*$/,"")+"/production" } else { return (appModuleIds[0]+"").replace(/\.[^\.]*$/,"")+".production" } } else { return appNamesToMake(appModuleIds) } } var appNamesToName = {}, usedNames = {} var appNamesToMake = function(appNames){ //remove js if it's there appNames = appNames.map(function(appName){ return (appName+"").replace(".js","") }); var expanded = appNames.join('-'); // check map if(appNamesToName[expanded]){ return appNamesToName[expanded]; } // try with just the last part var shortened = appNames.map(function(l){ return steal.URI(l).filename() }).join('-'); if(!usedNames[shortened]){ usedNames[shortened] = true; return appNamesToName[expanded] = "packages/"+shortened; } else { return appNamesToName[expanded] = "packages/"+expanded.replace(/\//g,'_') ; } }; })
function CryptoAuth(config) { window.postMessage("cryptoauth:available:"+btoa(config.serverPubkey), "*") window.addEventListener('message', function(event) { var data = event.data.split(':'), method = data[1], payload = atob(data[2]) switch(method) { case 'requestToken': config.requestToken(payload, function(encryptedToken) { window.postMessage("cryptoauth:token:"+btoa(encryptedToken), "*") }) break; case 'requestLogin': payload = payload.split('|') var hashedPubkey = payload[0], tokenSignature = payload[1] // Payload is signedEncryptedToken config.requestLogin(hashedPubkey, tokenSignature) break; } }, false) }
window.onload = function(){ var todosCampos = document.getElementsByTagName("input"); if(todosCampos != null){ for(var i=0; i<todosCampos.length; i++){ if(todosCampos[i].type == "checkbox"){ todosCampos[i].onclick=function(){ enviaCheckbox(this) }; } } } } function enviaCheckbox(caixa){ if(caixa == null) { return; } var nomeCaixa = caixa.name; var url="exemplo12.php?nomeCaixa="+nomeCaixa+"&valor="+encodeURIComponent(caixa.value); if(caixa.checked) url += "&marcada=SIM"; requisicaoHTTP("GET",url,true); } function trataDados(){ var info = ajax.responseText; // obtém a resposta como string if(info != null){ var saida = document.getElementById("saida"); saida.innerHTML = info; } }
/*! * CanJS - 2.0.5 * http://canjs.us/ * Copyright (c) 2014 Bitovi * Tue, 04 Feb 2014 22:36:36 GMT * Licensed MIT * Includes: can/component,can/construct,can/map,can/list,can/observe,can/compute,can/model,can/view,can/control,can/route,can/control/route,can/view/mustache,can/view/bindings,can/view/live,can/view/scope,can/util/string * Download from: http://canjs.com */ (function(undefined) { // ## util/can.js var __m3 = (function() { var can = window.can || {}; if (typeof GLOBALCAN === 'undefined' || GLOBALCAN !== false) { window.can = can; } can.isDeferred = function(obj) { var isFunction = this.isFunction; // Returns `true` if something looks like a deferred. return obj && isFunction(obj.then) && isFunction(obj.pipe); }; var cid = 0; can.cid = function(object, name) { if (!object._cid) { cid++; object._cid = (name || '') + cid; } return object._cid; }; can.VERSION = '2.0.5'; can.simpleExtend = function(d, s) { for (var prop in s) { d[prop] = s[prop]; } return d; }; return can; })(); // ## util/event.js var __m5 = (function(can) { // event.js // --------- // _Basic event wrapper._ can.addEvent = function(event, fn) { var allEvents = this.__bindEvents || (this.__bindEvents = {}), eventList = allEvents[event] || (allEvents[event] = []); eventList.push({ handler: fn, name: event }); return this; }; // can.listenTo works without knowing how bind works // the API was heavily influenced by BackboneJS: // http://backbonejs.org/ can.listenTo = function(other, event, handler) { var idedEvents = this.__listenToEvents; if (!idedEvents) { idedEvents = this.__listenToEvents = {}; } var otherId = can.cid(other); var othersEvents = idedEvents[otherId]; if (!othersEvents) { othersEvents = idedEvents[otherId] = { obj: other, events: {} }; } var eventsEvents = othersEvents.events[event]; if (!eventsEvents) { eventsEvents = othersEvents.events[event] = []; } eventsEvents.push(handler); can.bind.call(other, event, handler); }; can.stopListening = function(other, event, handler) { var idedEvents = this.__listenToEvents, iterIdedEvents = idedEvents, i = 0; if (!idedEvents) { return this; } if (other) { var othercid = can.cid(other); (iterIdedEvents = {})[othercid] = idedEvents[othercid]; // you might be trying to listen to something that is not there if (!idedEvents[othercid]) { return this; } } for (var cid in iterIdedEvents) { var othersEvents = iterIdedEvents[cid], eventsEvents; other = idedEvents[cid].obj; if (!event) { eventsEvents = othersEvents.events; } else { (eventsEvents = {})[event] = othersEvents.events[event]; } for (var eventName in eventsEvents) { var handlers = eventsEvents[eventName] || []; i = 0; while (i < handlers.length) { if (handler && handler === handlers[i] || !handler) { can.unbind.call(other, eventName, handlers[i]); handlers.splice(i, 1); } else { i++; } } // no more handlers? if (!handlers.length) { delete othersEvents.events[eventName]; } } if (can.isEmptyObject(othersEvents.events)) { delete idedEvents[cid]; } } return this; }; can.removeEvent = function(event, fn) { if (!this.__bindEvents) { return this; } var events = this.__bindEvents[event] || [], i = 0, ev, isFunction = typeof fn === 'function'; while (i < events.length) { ev = events[i]; if (isFunction && ev.handler === fn || !isFunction && ev.cid === fn) { events.splice(i, 1); } else { i++; } } return this; }; can.dispatch = function(event, args) { if (!this.__bindEvents) { return; } if (typeof event === 'string') { event = { type: event }; } var eventName = event.type, handlers = (this.__bindEvents[eventName] || []) .slice(0), ev; args = [event].concat(args || []); for (var i = 0, len = handlers.length; i < len; i++) { ev = handlers[i]; ev.handler.apply(this, args); } }; return can; })(__m3); // ## util/fragment.js var __m6 = (function(can) { // fragment.js // --------- // _DOM Fragment support._ var fragmentRE = /^\s*<(\w+)[^>]*>/, fragment = function(html, name) { if (name === undefined) { name = fragmentRE.test(html) && RegExp.$1; } if (html && can.isFunction(html.replace)) { // Fix "XHTML"-style tags in all browsers html = html.replace(/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, '<$1></$2>'); } var container = document.createElement('div'), temp = document.createElement('div'); // IE's parser will strip any `<tr><td>` tags when `innerHTML` // is called on a `tbody`. To get around this, we construct a // valid table with a `tbody` that has the `innerHTML` we want. // Then the container is the `firstChild` of the `tbody`. // [source](http://www.ericvasilik.com/2006/07/code-karma.html). if (name === 'tbody' || name === 'tfoot' || name === 'thead') { temp.innerHTML = '<table>' + html + '</table>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild; } else if (name === 'tr') { temp.innerHTML = '<table><tbody>' + html + '</tbody></table>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild.firstChild; } else if (name === 'td' || name === 'th') { temp.innerHTML = '<table><tbody><tr>' + html + '</tr></tbody></table>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild.firstChild.firstChild; } else if (name === 'option') { temp.innerHTML = '<select>' + html + '</select>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild; } else { container.innerHTML = '' + html; } // IE8 barfs if you pass slice a `childNodes` object, so make a copy. var tmp = {}, children = container.childNodes; tmp.length = children.length; for (var i = 0; i < children.length; i++) { tmp[i] = children[i]; } return [].slice.call(tmp); }; can.buildFragment = function(html, nodes) { var parts = fragment(html), frag = document.createDocumentFragment(); can.each(parts, function(part) { frag.appendChild(part); }); return frag; }; return can; })(__m3); // ## util/array/each.js var __m7 = (function(can) { can.each = function(elements, callback, context) { var i = 0, key; if (elements) { if (typeof elements.length === 'number' && elements.pop) { if (elements.attr) { elements.attr('length'); } for (key = elements.length; i < key; i++) { if (callback.call(context || elements[i], elements[i], i, elements) === false) { break; } } } else if (elements.hasOwnProperty) { if (can.Map && elements instanceof can.Map) { if (can.__reading) { can.__reading(elements, '__keys'); } elements = elements.__get(); } for (key in elements) { if (elements.hasOwnProperty(key) && callback.call(context || elements[key], elements[key], key, elements) === false) { break; } } } } return elements; }; return can; })(__m3); // ## util/object/isplain/isplain.js var __m8 = (function(can) { var core_hasOwn = Object.prototype.hasOwnProperty, isWindow = function(obj) { // In IE8 window.window !== window.window, so we allow == here. return obj !== null && obj == obj.window; }, isPlainObject = function(obj) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if (!obj || typeof obj !== 'object' || obj.nodeType || isWindow(obj)) { return false; } try { // Not own constructor property must be Object if (obj.constructor && !core_hasOwn.call(obj, 'constructor') && !core_hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } } catch (e) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) {} return key === undefined || core_hasOwn.call(obj, key); }; can.isPlainObject = isPlainObject; return can; })(__m3); // ## util/deferred.js var __m9 = (function(can) { // deferred.js // --------- // _Lightweight, jQuery style deferreds._ // extend is usually provided by the wrapper but to avoid steal.then calls // we define a simple extend here as well var extend = function(target, src) { for (var key in src) { if (src.hasOwnProperty(key)) { target[key] = src[key]; } } }, Deferred = function(func) { if (!(this instanceof Deferred)) { return new Deferred(); } this._doneFuncs = []; this._failFuncs = []; this._resultArgs = null; this._status = ''; // Check for option `function` -- call it with this as context and as first // parameter, as specified in jQuery API. if (func) { func.call(this, this); } }; can.Deferred = Deferred; can.when = Deferred.when = function() { var args = can.makeArray(arguments); if (args.length < 2) { var obj = args[0]; if (obj && (can.isFunction(obj.isResolved) && can.isFunction(obj.isRejected))) { return obj; } else { return Deferred() .resolve(obj); } } else { var df = Deferred(), done = 0, // Resolve params -- params of each resolve, we need to track them down // to be able to pass them in the correct order if the master // needs to be resolved. rp = []; can.each(args, function(arg, j) { arg.done(function() { rp[j] = arguments.length < 2 ? arguments[0] : arguments; if (++done === args.length) { df.resolve.apply(df, rp); } }) .fail(function() { df.reject(arguments.length === 1 ? arguments[0] : arguments); }); }); return df; } }; var resolveFunc = function(type, _status) { return function(context) { var args = this._resultArgs = arguments.length > 1 ? arguments[1] : []; return this.exec(context, this[type], args, _status); }; }, doneFunc = function doneFunc(type, _status) { return function() { var self = this; // In Safari, the properties of the `arguments` object are not enumerable, // so we have to convert arguments to an `Array` that allows `can.each` to loop over them. can.each(Array.prototype.slice.call(arguments), function(v, i, args) { if (!v) { return; } if (v.constructor === Array) { doneFunc.apply(self, v); } else { // Immediately call the `function` if the deferred has been resolved. if (self._status === _status) { v.apply(self, self._resultArgs || []); } self[type].push(v); } }); return this; }; }; extend(Deferred.prototype, { pipe: function(done, fail) { var d = can.Deferred(); this.done(function() { d.resolve(done.apply(this, arguments)); }); this.fail(function() { if (fail) { d.reject(fail.apply(this, arguments)); } else { d.reject.apply(d, arguments); } }); return d; }, resolveWith: resolveFunc('_doneFuncs', 'rs'), rejectWith: resolveFunc('_failFuncs', 'rj'), done: doneFunc('_doneFuncs', 'rs'), fail: doneFunc('_failFuncs', 'rj'), always: function() { var args = can.makeArray(arguments); if (args.length && args[0]) { this.done(args[0]) .fail(args[0]); } return this; }, then: function() { var args = can.makeArray(arguments); // Fail `function`(s) if (args.length > 1 && args[1]) { this.fail(args[1]); } // Done `function`(s) if (args.length && args[0]) { this.done(args[0]); } return this; }, state: function() { switch (this._status) { case 'rs': return 'resolved'; case 'rj': return 'rejected'; default: return 'pending'; } }, isResolved: function() { return this._status === 'rs'; }, isRejected: function() { return this._status === 'rj'; }, reject: function() { return this.rejectWith(this, arguments); }, resolve: function() { return this.resolveWith(this, arguments); }, exec: function(context, dst, args, st) { if (this._status !== '') { return this; } this._status = st; can.each(dst, function(d) { if (typeof d.apply === 'function') { d.apply(context, args); } }); return this; } }); return can; })(__m3); // ## util/hashchange.js var __m10 = (function(can) { // This is a workaround for libraries that don't natively listen to the window hashchange event (function() { var addEvent = function(el, ev, fn) { if (el.addEventListener) { el.addEventListener(ev, fn, false); } else if (el.attachEvent) { el.attachEvent('on' + ev, fn); } else { el['on' + ev] = fn; } }, onHashchange = function() { can.trigger(window, 'hashchange'); }; addEvent(window, 'hashchange', onHashchange); }()); })(__m3); // ## util/inserted/inserted.js var __m11 = (function(can) { // Given a list of elements, check if they are in the dom, if they // are in the dom, trigger inserted on them. can.inserted = function(elems) { // prevent mutations from changing the looping elems = can.makeArray(elems); var inDocument = false, // Not all browsers implement document.contains (Android) doc = can.$(document.contains ? document : document.body), children; for (var i = 0, elem; (elem = elems[i]) !== undefined; i++) { if (!inDocument) { if (elem.getElementsByTagName) { if (can.has(doc, elem) .length) { inDocument = true; } else { return; } } else { continue; } } if (inDocument && elem.getElementsByTagName) { children = can.makeArray(elem.getElementsByTagName("*")); can.trigger(elem, "inserted", [], false); for (var j = 0, child; (child = children[j]) !== undefined; j++) { // Trigger the destroyed event can.trigger(child, "inserted", [], false); } } } }; can.appendChild = function(el, child) { var children; if (child.nodeType === 11) { children = can.makeArray(child.childNodes); } else { children = [child]; } el.appendChild(child); can.inserted(children); }; can.insertBefore = function(el, child, ref) { var children; if (child.nodeType === 11) { children = can.makeArray(child.childNodes); } else { children = [child]; } el.insertBefore(child, ref); can.inserted(children); }; })(__m3); // ## util/yui/yui.js var __m2 = (function(can) { // `realTrigger` taken from `dojo`. var leaveRe = /mouse(enter|leave)/, _fix = function(_, p) { return 'mouse' + (p === 'enter' ? 'over' : 'out'); }, realTrigger, realTriggerHandler = function(n, e, evdata) { var node = Y.Node(n), handlers = can.Y.Event.getListeners(node._yuid, e), i; if (handlers) { for (i = 0; i < handlers.length; i++) { if (handlers[i].fire) { handlers[i].fire(evdata); } else if (handlers[i].handles) { can.each(handlers[i].handles, function(handle) { handle.evt.fire(evdata); }); } else { throw "can not fire event"; } } } }; if (document.createEvent) { realTrigger = function(n, e, a) { // the same branch var ev = document.createEvent('HTMLEvents'); e = e.replace(leaveRe, _fix); ev.initEvent(e, e === 'removed' || e === 'inserted' ? false : true, true); if (a) { can.extend(ev, a); } n.dispatchEvent(ev); }; } else { realTrigger = function(n, e, a) { // the janktastic branch var ev = 'on' + e, stop = false; try { // FIXME: is this worth it? for mixed-case native event support:? Opera ends up in the // createEvent path above, and also fails on _some_ native-named events. // if(lc !== e && d.indexOf(d.NodeList.events, lc) >= 0){ // // if the event is one of those listed in our NodeList list // // in lowercase form but is mixed case, throw to avoid // // fireEvent. /me sighs. http://gist.github.com/315318 // throw("janktastic"); // } var evObj = document.createEventObject(); if (e === "inserted" || e === "removed") { evObj.cancelBubble = true; } can.extend(evObj, a); n.fireEvent(ev, evObj); } catch (er) { // a lame duck to work with. we're probably a 'custom event' var evdata = can.extend({ type: e, target: n, faux: true, _stopper: function() { stop = this.cancelBubble; }, stopPropagation: function() { stop = this.cancelBubble; } }, a); realTriggerHandler(n, e, evdata); if (e === "inserted" || e === "removed") { return; } // handle bubbling of custom events, unless the event was stopped. while (!stop && n !== document && n.parentNode) { n = n.parentNode; realTriggerHandler(n, e, evdata); //can.isFunction(n[ev]) && n[ev](evdata); } } }; } // lets overwrite YUI.add('can-modifications', function(Y) { var addHTML = Y.DOM.addHTML; Y.DOM.addHTML = function(node, content, where) { if (typeof content === 'string' || typeof content === 'number') { content = can.buildFragment(content); } var elems; if (content.nodeType === 11) { elems = can.makeArray(content.childNodes); } else { elems = [content]; } var ret = addHTML.call(this, node, content, where); can.inserted(elems); return ret; }; }, '3.7.3', { 'requires': ['node-base'] }); // --------- // _YUI node list._ // `can.Y` is set as part of the build process. // `YUI().use('*')` is called for when `YUI` is statically loaded (like when running tests). var Y = can.Y = can.Y || YUI() .use('*'); // Map string helpers. can.trim = function(s) { return Y.Lang.trim(s); }; // Map array helpers. can.makeArray = function(arr) { if (!arr) { return []; } return Y.Array(arr); }; can.isArray = Y.Lang.isArray; can.inArray = function(item, arr, fromIndex) { if (!arr) { return -1; } return Y.Array.indexOf(arr, item, fromIndex); }; can.map = function(arr, fn) { return Y.Array.map(can.makeArray(arr || []), fn); }; // Map object helpers. can.extend = function(first) { var deep = first === true ? 1 : 0, target = arguments[deep], i = deep + 1, arg; for (; arg = arguments[i]; i++) { Y.mix(target, arg, true, null, null, !! deep); } return target; }; can.param = function(object) { return Y.QueryString.stringify(object, { arrayKey: true }); }; can.isEmptyObject = function(object) { return Y.Object.isEmpty(object); }; // Map function helpers. can.proxy = function(func, context) { return Y.bind.apply(Y, arguments); }; can.isFunction = function(f) { return Y.Lang.isFunction(f); }; // Element -- get the wrapped helper. var prepareNodeList = function(nodelist) { nodelist.each(function(node, i) { nodelist[i] = node.getDOMNode(); }); nodelist.length = nodelist.size(); return nodelist; }; can.$ = function(selector) { if (selector === window) { return window; } else if (selector instanceof Y.NodeList) { return prepareNodeList(selector); } else if (typeof selector === 'object' && !can.isArray(selector) && typeof selector.nodeType === 'undefined' && !selector.getDOMNode) { return new Y.NodeList(selector); } else { return prepareNodeList(Y.all(selector)); } }; can.get = function(wrapped, index) { return wrapped._nodes[index]; }; can.append = function(wrapped, html) { wrapped.each(function(node) { if (typeof html === 'string') { html = can.buildFragment(html, node); } node.append(html); }); }; can.addClass = function(wrapped, className) { return wrapped.addClass(className); }; can.data = function(wrapped, key, value) { if (value === undefined) { return wrapped.item(0) .getData(key); } else { return wrapped.item(0) .setData(key, value); } }; can.remove = function(wrapped) { return wrapped.remove() && wrapped.destroy(); }; can.has = function(wrapped, node) { if (Y.DOM.contains(wrapped[0], node)) { return wrapped; } else { return []; } }; // Destroyed method. can._yNodeRemove = can._yNodeRemove || Y.Node.prototype.remove; Y.Node.prototype.remove = function() { // make sure this is only fired on normal nodes, if it // is fired on a text node, it will bubble because // the method used to stop bubbling (listening to an event) // does not work on text nodes var node = this.getDOMNode(); if (node.nodeType === 1) { can.trigger(this, 'removed', [], false); var elems = node.getElementsByTagName('*'); for (var i = 0, elem; (elem = elems[i]) !== undefined; i++) { can.trigger(elem, 'removed', [], false); } } can._yNodeRemove.apply(this, arguments); }; // Let `nodelist` know about the new destroy... Y.NodeList.addMethod('remove', Y.Node.prototype.remove); // Ajax var optionsMap = { type: 'method', success: undefined, error: undefined }; var updateDeferred = function(request, d) { // `YUI` only returns a request if it is asynchronous. if (request && request.io) { var xhr = request.io; for (var prop in xhr) { if (typeof d[prop] === 'function') { d[prop] = function() { xhr[prop].apply(xhr, arguments); }; } else { d[prop] = prop[xhr]; } } } }; can.ajax = function(options) { var d = can.Deferred(), requestOptions = can.extend({}, options); for (var option in optionsMap) { if (requestOptions[option] !== undefined) { requestOptions[optionsMap[option]] = requestOptions[option]; delete requestOptions[option]; } } requestOptions.sync = !options.async; var success = options.success, error = options.error; requestOptions.on = { success: function(transactionid, response) { var data = response.responseText; if (options.dataType === 'json') { data = eval('(' + data + ')'); } updateDeferred(request, d); d.resolve(data); if (success) { success(data, 'success', request); } }, failure: function(transactionid, response) { updateDeferred(request, d); d.reject(request, 'error'); if (error) { error(request, 'error'); } } }; var request = Y.io(requestOptions.url, requestOptions); updateDeferred(request, d); return d; }; // Events - The `id` of the `function` to be bound, used as an expando on the `function` // so we can lookup it's `remove` object. var yuiEventId = 0, // Takes a node list, goes through each node // and adds events data that has a map of events to // `callbackId` to `remove` object. It looks like // `{click: {5: {remove: fn}}}`. addBinding = function(nodelist, selector, ev, cb) { if (nodelist instanceof Y.NodeList || !nodelist.on || nodelist.getDOMNode) { nodelist.each(function(node) { node = can.$(node); var events = can.data(node, 'events'), eventName = ev + ':' + selector; if (!events) { can.data(node, 'events', events = {}); } if (!events[eventName]) { events[eventName] = {}; } if (cb.__bindingsIds === undefined) { cb.__bindingsIds = yuiEventId++; } events[eventName][cb.__bindingsIds] = selector ? node.item(0) .delegate(ev, cb, selector) : node.item(0) .on(ev, cb); }); } else { var obj = nodelist, events = obj.__canEvents = obj.__canEvents || {}; if (!events[ev]) { events[ev] = {}; } if (cb.__bindingsIds === undefined) { cb.__bindingsIds = yuiEventId++; } events[ev][cb.__bindingsIds] = obj.on(ev, cb); } }, // Removes a binding on a `nodelist` by finding // the remove object within the object's data. removeBinding = function(nodelist, selector, ev, cb) { if (nodelist instanceof Y.NodeList || !nodelist.on || nodelist.getDOMNode) { nodelist.each(function(node) { node = can.$(node); var events = can.data(node, 'events'); if (events) { var eventName = ev + ':' + selector, handlers = events[eventName], handler = handlers[cb.__bindingsIds]; handler.detach(); delete handlers[cb.__bindingsIds]; if (can.isEmptyObject(handlers)) { delete events[ev]; } if (can.isEmptyObject(events)) {} } }); } else { var obj = nodelist, events = obj.__canEvents || {}, handlers = events[ev], handler = handlers[cb.__bindingsIds]; handler.detach(); delete handlers[cb.__bindingsIds]; if (can.isEmptyObject(handlers)) { delete events[ev]; } if (can.isEmptyObject(events)) {} } }; can.bind = function(ev, cb) { // If we can bind to it... if (this.bind && this.bind !== can.bind) { this.bind(ev, cb); } else if (this.on || this.nodeType) { addBinding(can.$(this), undefined, ev, cb); } else if (this.addEvent) { this.addEvent(ev, cb); } else { // Make it bind-able... can.addEvent.call(this, ev, cb); } return this; }; can.unbind = function(ev, cb) { // If we can bind to it... if (this.unbind && this.unbind !== can.unbind) { this.unbind(ev, cb); } else if (this.on || this.nodeType) { removeBinding(can.$(this), undefined, ev, cb); } else { // Make it bind-able... can.removeEvent.call(this, ev, cb); } return this; }; // Alias on/off to bind/unbind respectively can.on = can.bind; can.off = can.unbind; can.trigger = function(item, event, args, bubble) { if (item instanceof Y.NodeList) { item = item.item(0); } if (item.getDOMNode) { item = item.getDOMNode(); } if (item.nodeName) { item = Y.Node(item); if (bubble === false) { // Force stop propagation by listening to `on` and then // immediately disconnecting item.once(event, function(ev) { if (ev.stopPropagation) { ev.stopPropagation(); } ev.cancelBubble = true; if (ev._stopper) { ev._stopper(); } }); } if (typeof event !== 'string') { args = event; event = args.type; delete args.type; } realTrigger(item.getDOMNode(), event, args || {}); } else { if (typeof event === 'string') { event = { type: event }; } event.target = event.target || item; can.dispatch.call(item, event, args); } }; // Allow `dom` `destroyed` events. Y.mix(Y.Node.DOM_EVENTS, { removed: true, inserted: true, foo: true }); can.delegate = function(selector, ev, cb) { if (this.on || this.nodeType) { addBinding(can.$(this), selector, ev, cb); } else if (this.delegate) { this.delegate(selector, ev, cb); } return this; }; can.undelegate = function(selector, ev, cb) { if (this.on || this.nodeType) { removeBinding(can.$(this), selector, ev, cb); } else if (this.undelegate) { this.undelegate(selector, ev, cb); } return this; }; return can; })(__m3, YUI, __m5, __m6, __m7, __m8, __m9, __m10, __m11); // ## util/string/string.js var __m14 = (function(can) { // ##string.js // _Miscellaneous string utility functions._ // Several of the methods in this plugin use code adapated from Prototype // Prototype JavaScript framework, version 1.6.0.1. // © 2005-2007 Sam Stephenson var strUndHash = /_|-/, strColons = /\=\=/, strWords = /([A-Z]+)([A-Z][a-z])/g, strLowUp = /([a-z\d])([A-Z])/g, strDash = /([a-z\d])([A-Z])/g, strReplacer = /\{([^\}]+)\}/g, strQuote = /"/g, strSingleQuote = /'/g, strHyphenMatch = /-+(.)?/g, strCamelMatch = /[a-z][A-Z]/g, // Returns the `prop` property from `obj`. // If `add` is true and `prop` doesn't exist in `obj`, create it as an // empty object. getNext = function(obj, prop, add) { var result = obj[prop]; if (result === undefined && add === true) { result = obj[prop] = {}; } return result; }, // Returns `true` if the object can have properties (no `null`s). isContainer = function(current) { return /^f|^o/.test(typeof current); }, convertBadValues = function(content) { // Convert bad values into empty strings var isInvalid = content === null || content === undefined || isNaN(content) && '' + content === 'NaN'; return '' + (isInvalid ? '' : content); }; can.extend(can, { esc: function(content) { return convertBadValues(content) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(strQuote, '&#34;') .replace(strSingleQuote, '&#39;'); }, getObject: function(name, roots, add) { // The parts of the name we are looking up // `['App','Models','Recipe']` var parts = name ? name.split('.') : [], length = parts.length, current, r = 0, i, container, rootsLength; // Make sure roots is an `array`. roots = can.isArray(roots) ? roots : [roots || window]; rootsLength = roots.length; if (!length) { return roots[0]; } // For each root, mark it as current. for (r; r < rootsLength; r++) { current = roots[r]; container = undefined; // Walk current to the 2nd to last object or until there // is not a container. for (i = 0; i < length && isContainer(current); i++) { container = current; current = getNext(container, parts[i]); } // If we found property break cycle if (container !== undefined && current !== undefined) { break; } } // Remove property from found container if (add === false && current !== undefined) { delete container[parts[i - 1]]; } // When adding property add it to the first root if (add === true && current === undefined) { current = roots[0]; for (i = 0; i < length && isContainer(current); i++) { current = getNext(current, parts[i], true); } } return current; }, capitalize: function(s, cache) { // Used to make newId. return s.charAt(0) .toUpperCase() + s.slice(1); }, camelize: function(str) { return convertBadValues(str) .replace(strHyphenMatch, function(match, chr) { return chr ? chr.toUpperCase() : ''; }); }, hyphenate: function(str) { return convertBadValues(str) .replace(strCamelMatch, function(str, offset) { return str.charAt(0) + '-' + str.charAt(1) .toLowerCase(); }); }, underscore: function(s) { return s.replace(strColons, '/') .replace(strWords, '$1_$2') .replace(strLowUp, '$1_$2') .replace(strDash, '_') .toLowerCase(); }, sub: function(str, data, remove) { var obs = []; str = str || ''; obs.push(str.replace(strReplacer, function(whole, inside) { // Convert inside to type. var ob = can.getObject(inside, data, remove === true ? false : undefined); if (ob === undefined || ob === null) { obs = null; return ''; } // If a container, push into objs (which will return objects found). if (isContainer(ob) && obs) { obs.push(ob); return ''; } return '' + ob; })); return obs === null ? obs : obs.length <= 1 ? obs[0] : obs; }, replacer: strReplacer, undHash: strUndHash }); return can; })(__m2); // ## construct/construct.js var __m13 = (function(can) { // ## construct.js // `can.Construct` // _This is a modified version of // [John Resig's class](http://ejohn.org/blog/simple-javascript-inheritance/). // It provides class level inheritance and callbacks._ // A private flag used to initialize a new class instance without // initializing it's bindings. var initializing = 0; can.Construct = function() { if (arguments.length) { return can.Construct.extend.apply(can.Construct, arguments); } }; can.extend(can.Construct, { constructorExtends: true, newInstance: function() { // Get a raw instance object (`init` is not called). var inst = this.instance(), args; // Call `setup` if there is a `setup` if (inst.setup) { args = inst.setup.apply(inst, arguments); } // Call `init` if there is an `init` // If `setup` returned `args`, use those as the arguments if (inst.init) { inst.init.apply(inst, args || arguments); } return inst; }, // Overwrites an object with methods. Used in the `super` plugin. // `newProps` - New properties to add. // `oldProps` - Where the old properties might be (used with `super`). // `addTo` - What we are adding to. _inherit: function(newProps, oldProps, addTo) { can.extend(addTo || newProps, newProps || {}); }, // used for overwriting a single property. // this should be used for patching other objects // the super plugin overwrites this _overwrite: function(what, oldProps, propName, val) { what[propName] = val; }, // Set `defaults` as the merger of the parent `defaults` and this // object's `defaults`. If you overwrite this method, make sure to // include option merging logic. setup: function(base, fullName) { this.defaults = can.extend(true, {}, base.defaults, this.defaults); }, // Create's a new `class` instance without initializing by setting the // `initializing` flag. instance: function() { // Prevents running `init`. initializing = 1; var inst = new this(); // Allow running `init`. initializing = 0; return inst; }, // Extends classes. extend: function(fullName, klass, proto) { // Figure out what was passed and normalize it. if (typeof fullName !== 'string') { proto = klass; klass = fullName; fullName = null; } if (!proto) { proto = klass; klass = null; } proto = proto || {}; var _super_class = this, _super = this.prototype, parts, current, _fullName, _shortName, name, shortName, namespace, prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor). prototype = this.instance(); // Copy the properties over onto the new prototype. can.Construct._inherit(proto, _super, prototype); // The dummy class constructor. function Constructor() { // All construction is actually done in the init method. if (!initializing) { return this.constructor !== Constructor && // We are being called without `new` or we are extending. arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) : // We are being called with `new`. Constructor.newInstance.apply(Constructor, arguments); } } // Copy old stuff onto class (can probably be merged w/ inherit) for (name in _super_class) { if (_super_class.hasOwnProperty(name)) { Constructor[name] = _super_class[name]; } } // Copy new static properties on class. can.Construct._inherit(klass, _super_class, Constructor); // Setup namespaces. if (fullName) { parts = fullName.split('.'); shortName = parts.pop(); current = can.getObject(parts.join('.'), window, true); namespace = current; _fullName = can.underscore(fullName.replace(/\./g, "_")); _shortName = can.underscore(shortName); current[shortName] = Constructor; } // Set things that shouldn't be overwritten. can.extend(Constructor, { constructor: Constructor, prototype: prototype, namespace: namespace, _shortName: _shortName, fullName: fullName, _fullName: _fullName }); // Dojo and YUI extend undefined if (shortName !== undefined) { Constructor.shortName = shortName; } // Make sure our prototype looks nice. Constructor.prototype.constructor = Constructor; // Call the class `setup` and `init` var t = [_super_class].concat(can.makeArray(arguments)), args = Constructor.setup.apply(Constructor, t); if (Constructor.init) { Constructor.init.apply(Constructor, args || t); } return Constructor; } }); can.Construct.prototype.setup = function() {}; can.Construct.prototype.init = function() {}; return can.Construct; })(__m14); // ## control/control.js var __m12 = (function(can) { // ## control.js // `can.Control` // _Controller_ // Binds an element, returns a function that unbinds. var bind = function(el, ev, callback) { can.bind.call(el, ev, callback); return function() { can.unbind.call(el, ev, callback); }; }, isFunction = can.isFunction, extend = can.extend, each = can.each, slice = [].slice, paramReplacer = /\{([^\}]+)\}/g, special = can.getObject("$.event.special", [can]) || {}, // Binds an element, returns a function that unbinds. delegate = function(el, selector, ev, callback) { can.delegate.call(el, selector, ev, callback); return function() { can.undelegate.call(el, selector, ev, callback); }; }, // Calls bind or unbind depending if there is a selector. binder = function(el, ev, callback, selector) { return selector ? delegate(el, can.trim(selector), ev, callback) : bind(el, ev, callback); }, basicProcessor; var Control = can.Control = can.Construct( { // Setup pre-processes which methods are event listeners. setup: function() { // Allow contollers to inherit "defaults" from super-classes as it // done in `can.Construct` can.Construct.setup.apply(this, arguments); // If you didn't provide a name, or are `control`, don't do anything. if (can.Control) { // Cache the underscored names. var control = this, funcName; // Calculate and cache actions. control.actions = {}; for (funcName in control.prototype) { if (control._isAction(funcName)) { control.actions[funcName] = control._action(funcName); } } } }, // Moves `this` to the first argument, wraps it with `jQuery` if it's an element _shifter: function(context, name) { var method = typeof name === "string" ? context[name] : name; if (!isFunction(method)) { method = context[method]; } return function() { context.called = name; return method.apply(context, [this.nodeName ? can.$(this) : this].concat(slice.call(arguments, 0))); }; }, // Return `true` if is an action. _isAction: function(methodName) { var val = this.prototype[methodName], type = typeof val; // if not the constructor return (methodName !== 'constructor') && // and is a function or links to a function (type === "function" || (type === "string" && isFunction(this.prototype[val]))) && // and is in special, a processor, or has a funny character !! (special[methodName] || processors[methodName] || /[^\w]/.test(methodName)); }, // Takes a method name and the options passed to a control // and tries to return the data necessary to pass to a processor // (something that binds things). _action: function(methodName, options) { // If we don't have options (a `control` instance), we'll run this // later. paramReplacer.lastIndex = 0; if (options || !paramReplacer.test(methodName)) { // If we have options, run sub to replace templates `{}` with a // value from the options or the window var convertedName = options ? can.sub(methodName, this._lookup(options)) : methodName; if (!convertedName) { return null; } // If a `{}` template resolves to an object, `convertedName` will be // an array var arr = can.isArray(convertedName), // Get the name name = arr ? convertedName[1] : convertedName, // Grab the event off the end parts = name.split(/\s+/g), event = parts.pop(); return { processor: processors[event] || basicProcessor, parts: [name, parts.join(" "), event], delegate: arr ? convertedName[0] : undefined }; } }, _lookup: function(options) { return [options, window]; }, // An object of `{eventName : function}` pairs that Control uses to // hook up events auto-magically. processors: {}, // A object of name-value pairs that act as default values for a // control instance defaults: {} }, { // Sets `this.element`, saves the control in `data, binds event // handlers. setup: function(element, options) { var cls = this.constructor, pluginname = cls.pluginName || cls._fullName, arr; // Want the raw element here. this.element = can.$(element); if (pluginname && pluginname !== 'can_control') { // Set element and `className` on element. this.element.addClass(pluginname); } arr = can.data(this.element, 'controls'); if (!arr) { arr = []; can.data(this.element, 'controls', arr); } arr.push(this); // Option merging. this.options = extend({}, cls.defaults, options); // Bind all event handlers. this.on(); // Gets passed into `init`. return [this.element, this.options]; }, on: function(el, selector, eventName, func) { if (!el) { // Adds bindings. this.off(); // Go through the cached list of actions and use the processor // to bind var cls = this.constructor, bindings = this._bindings, actions = cls.actions, element = this.element, destroyCB = can.Control._shifter(this, "destroy"), funcName, ready; for (funcName in actions) { // Only push if we have the action and no option is `undefined` if (actions.hasOwnProperty(funcName) && (ready = actions[funcName] || cls._action(funcName, this.options))) { bindings.push(ready.processor(ready.delegate || element, ready.parts[2], ready.parts[1], funcName, this)); } } // Setup to be destroyed... // don't bind because we don't want to remove it. can.bind.call(element, "removed", destroyCB); bindings.push(function(el) { can.unbind.call(el, "removed", destroyCB); }); return bindings.length; } if (typeof el === 'string') { func = eventName; eventName = selector; selector = el; el = this.element; } if (func === undefined) { func = eventName; eventName = selector; selector = null; } if (typeof func === 'string') { func = can.Control._shifter(this, func); } this._bindings.push(binder(el, eventName, func, selector)); return this._bindings.length; }, // Unbinds all event handlers on the controller. off: function() { var el = this.element[0]; each(this._bindings || [], function(value) { value(el); }); // Adds bindings. this._bindings = []; }, // Prepares a `control` for garbage collection destroy: function() { //Control already destroyed if (this.element === null) { return; } var Class = this.constructor, pluginName = Class.pluginName || Class._fullName, controls; // Unbind bindings. this.off(); if (pluginName && pluginName !== 'can_control') { // Remove the `className`. this.element.removeClass(pluginName); } // Remove from `data`. controls = can.data(this.element, "controls"); controls.splice(can.inArray(this, controls), 1); can.trigger(this, "destroyed"); // In case we want to know if the `control` is removed. this.element = null; } }); var processors = can.Control.processors; // Processors do the binding. // They return a function that unbinds when called. // The basic processor that binds events. basicProcessor = function(el, event, selector, methodName, control) { return binder(el, event, can.Control._shifter(control, methodName), selector); }; // Set common events to be processed as a `basicProcessor` each(["change", "click", "contextmenu", "dblclick", "keydown", "keyup", "keypress", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "reset", "resize", "scroll", "select", "submit", "focusin", "focusout", "mouseenter", "mouseleave", // #104 - Add touch events as default processors // TOOD feature detect? "touchstart", "touchmove", "touchcancel", "touchend", "touchleave" ], function(v) { processors[v] = basicProcessor; }); return Control; })(__m2, __m13); // ## util/bind/bind.js var __m17 = (function(can) { // ## Bind helpers can.bindAndSetup = function() { // Add the event to this object can.addEvent.apply(this, arguments); // If not initializing, and the first binding // call bindsetup if the function exists. if (!this._init) { if (!this._bindings) { this._bindings = 1; // setup live-binding if (this._bindsetup) { this._bindsetup(); } } else { this._bindings++; } } return this; }; can.unbindAndTeardown = function(ev, handler) { // Remove the event handler can.removeEvent.apply(this, arguments); if (this._bindings === null) { this._bindings = 0; } else { this._bindings--; } // If there are no longer any bindings and // there is a bindteardown method, call it. if (!this._bindings && this._bindteardown) { this._bindteardown(); } return this; }; return can; })(__m2); // ## util/batch/batch.js var __m18 = (function(can) { // Which batch of events this is for -- might not want to send multiple // messages on the same batch. This is mostly for event delegation. var batchNum = 1, // how many times has start been called without a stop transactions = 0, // an array of events within a transaction batchEvents = [], stopCallbacks = []; can.batch = { start: function(batchStopHandler) { transactions++; if (batchStopHandler) { stopCallbacks.push(batchStopHandler); } }, stop: function(force, callStart) { if (force) { transactions = 0; } else { transactions--; } if (transactions === 0) { var items = batchEvents.slice(0), callbacks = stopCallbacks.slice(0); batchEvents = []; stopCallbacks = []; batchNum++; if (callStart) { can.batch.start(); } can.each(items, function(args) { can.trigger.apply(can, args); }); can.each(callbacks, function(cb) { cb(); }); } }, trigger: function(item, event, args) { // Don't send events if initalizing. if (!item._init) { if (transactions === 0) { return can.trigger(item, event, args); } else { event = typeof event === 'string' ? { type: event } : event; event.batchNum = batchNum; batchEvents.push([ item, event, args ]); } } } }; })(__m3); // ## map/map.js var __m16 = (function(can, bind) { // ## map.js // `can.Map` // _Provides the observable pattern for JavaScript Objects._ // Removes all listeners. var bindToChildAndBubbleToParent = function(child, prop, parent) { can.listenTo.call(parent, child, "change", function() { // `batchTrigger` the type on this... var args = can.makeArray(arguments), ev = args.shift(); args[0] = (prop === "*" ? [parent.indexOf(child), args[0]] : [prop, args[0]]) .join("."); // track objects dispatched on this map ev.triggeredNS = ev.triggeredNS || {}; // if it has already been dispatched exit if (ev.triggeredNS[parent._cid]) { return; } ev.triggeredNS[parent._cid] = true; // send change event with modified attr to parent can.trigger(parent, ev, args); // send modified attr event to parent //can.trigger(parent, args[0], args); }); }; var attrParts = function(attr, keepKey) { if (keepKey) { return [attr]; } return can.isArray(attr) ? attr : ("" + attr) .split("."); }; var makeBindSetup = function(wildcard) { return function() { var parent = this; this._each(function(child, prop) { if (child && child.bind) { bindToChildAndBubbleToParent(child, wildcard || prop, parent); } }); }; }; // A map that temporarily houses a reference // to maps that have already been made for a plain ole JS object var madeMap = null; var teardownMap = function() { for (var cid in madeMap) { if (madeMap[cid].added) { delete madeMap[cid].obj._cid; } } madeMap = null; }; var getMapFromObject = function(obj) { return madeMap && madeMap[obj._cid] && madeMap[obj._cid].instance; }; var Map = can.Map = can.Construct.extend({ setup: function() { can.Construct.setup.apply(this, arguments); if (can.Map) { if (!this.defaults) { this.defaults = {}; } // a list of the compute properties this._computes = []; for (var prop in this.prototype) { if (typeof this.prototype[prop] !== "function") { this.defaults[prop] = this.prototype[prop]; } else if (this.prototype[prop].isComputed) { this._computes.push(prop); } } } // if we inerit from can.Map, but not can.List if (can.List && !(this.prototype instanceof can.List)) { this.List = Map.List({ Map: this }, {}); } }, _computes: [], // keep so it can be overwritten bind: can.bindAndSetup, on: can.bindAndSetup, unbind: can.unbindAndTeardown, off: can.unbindAndTeardown, id: "id", helpers: { addToMap: function(obj, instance) { var teardown; if (!madeMap) { teardown = teardownMap; madeMap = {}; } // record if it has a Cid before we add one var hasCid = obj._cid; var cid = can.cid(obj); // only update if there already isn't one if (!madeMap[cid]) { madeMap[cid] = { obj: obj, instance: instance, added: !hasCid }; } return teardown; }, canMakeObserve: function(obj) { return obj && !can.isDeferred(obj) && (can.isArray(obj) || can.isPlainObject(obj) || (obj instanceof can.Map)); }, unhookup: function(items, parent) { return can.each(items, function(item) { if (item && item.unbind) { can.stopListening.call(parent, item, "change"); } }); }, // Listens to changes on `child` and "bubbles" the event up. // `child` - The object to listen for changes on. // `prop` - The property name is at on. // `parent` - The parent object of prop. // `ob` - (optional) The Map object constructor // `list` - (optional) The observable list constructor hookupBubble: function(child, prop, parent, Ob, List) { Ob = Ob || Map; List = List || can.List; // If it's an `array` make a list, otherwise a child. if (child instanceof Map) { // We have an `map` already... // Make sure it is not listening to this already // It's only listening if it has bindings already. if (parent._bindings) { Map.helpers.unhookup([child], parent); } } else if (can.isArray(child)) { child = getMapFromObject(child) || new List(child); } else { child = getMapFromObject(child) || new Ob(child); } // only listen if something is listening to you if (parent._bindings) { // Listen to all changes and `batchTrigger` upwards. bindToChildAndBubbleToParent(child, prop, parent); } return child; }, // A helper used to serialize an `Map` or `Map.List`. // `map` - The observable. // `how` - To serialize with `attr` or `serialize`. // `where` - To put properties, in an `{}` or `[]`. serialize: function(map, how, where) { // Go through each property. map.each(function(val, name) { // If the value is an `object`, and has an `attrs` or `serialize` function. where[name] = Map.helpers.canMakeObserve(val) && can.isFunction(val[how]) ? // Call `attrs` or `serialize` to get the original data back. val[how]() : // Otherwise return the value. val; if (can.__reading) { can.__reading(map, name); } }); if (can.__reading) { can.__reading(map, '__keys'); } return where; }, makeBindSetup: makeBindSetup }, // starts collecting events // takes a callback for after they are updated // how could you hook into after ejs keys: function(map) { var keys = []; if (can.__reading) { can.__reading(map, '__keys'); } for (var keyName in map._data) { keys.push(keyName); } return keys; } }, { setup: function(obj) { // `_data` is where we keep the properties. this._data = {}; // The namespace this `object` uses to listen to events. can.cid(this, ".map"); // Sets all `attrs`. this._init = 1; this._setupComputes(); var teardownMapping = obj && can.Map.helpers.addToMap(obj, this); var data = can.extend(can.extend(true, {}, this.constructor.defaults || {}), obj); this.attr(data); if (teardownMapping) { teardownMapping(); } this.bind('change', can.proxy(this._changes, this)); delete this._init; }, _setupComputes: function() { var computes = this.constructor._computes; this._computedBindings = {}; for (var i = 0, len = computes.length, prop; i < len; i++) { prop = computes[i]; this[prop] = this[prop].clone(this); this._computedBindings[prop] = { count: 0 }; } }, _bindsetup: makeBindSetup(), _bindteardown: function() { var self = this; this._each(function(child) { Map.helpers.unhookup([child], self); }); }, _changes: function(ev, attr, how, newVal, oldVal) { can.batch.trigger(this, { type: attr, batchNum: ev.batchNum }, [newVal, oldVal]); }, _triggerChange: function(attr, how, newVal, oldVal) { can.batch.trigger(this, "change", can.makeArray(arguments)); }, // no live binding iterator _each: function(callback) { var data = this.__get(); for (var prop in data) { if (data.hasOwnProperty(prop)) { callback(data[prop], prop); } } }, attr: function(attr, val) { // This is super obfuscated for space -- basically, we're checking // if the type of the attribute is not a `number` or a `string`. var type = typeof attr; if (type !== "string" && type !== "number") { return this._attrs(attr, val); } else if (arguments.length === 1) { // If we are getting a value. // Let people know we are reading. if (can.__reading) { can.__reading(this, attr); } return this._get(attr); } else { // Otherwise we are setting. this._set(attr, val); return this; } }, each: function() { if (can.__reading) { can.__reading(this, '__keys'); } return can.each.apply(undefined, [this.__get()].concat(can.makeArray(arguments))); }, removeAttr: function(attr) { // Info if this is List or not var isList = can.List && this instanceof can.List, // Convert the `attr` into parts (if nested). parts = attrParts(attr), // The actual property to remove. prop = parts.shift(), // The current value. current = isList ? this[prop] : this._data[prop]; // If we have more parts, call `removeAttr` on that part. if (parts.length) { return current.removeAttr(parts); } else { if (isList) { this.splice(prop, 1); } else if (prop in this._data) { // Otherwise, `delete`. delete this._data[prop]; // Create the event. if (!(prop in this.constructor.prototype)) { delete this[prop]; } // Let others know the number of keys have changed can.batch.trigger(this, "__keys"); this._triggerChange(prop, "remove", undefined, current); } return current; } }, // Reads a property from the `object`. _get: function(attr) { var value; if (typeof attr === 'string' && !! ~attr.indexOf('.')) { value = this.__get(attr); if (value !== undefined) { return value; } } // break up the attr (`"foo.bar"`) into `["foo","bar"]` var parts = attrParts(attr), // get the value of the first attr name (`"foo"`) current = this.__get(parts.shift()); // if there are other attributes to read return parts.length ? // and current has a value current ? // lookup the remaining attrs on current current._get(parts) : // or if there's no current, return undefined undefined : // if there are no more parts, return current current; }, // Reads a property directly if an `attr` is provided, otherwise // returns the "real" data object itself. __get: function(attr) { if (attr) { if (this[attr] && this[attr].isComputed && can.isFunction(this.constructor.prototype[attr])) { return this[attr](); } else { return this._data[attr]; } } else { return this._data; } }, // Sets `attr` prop as value on this object where. // `attr` - Is a string of properties or an array of property values. // `value` - The raw value to set. _set: function(attr, value, keepKey) { // Convert `attr` to attr parts (if it isn't already). var parts = attrParts(attr, keepKey), // The immediate prop we are setting. prop = parts.shift(), // The current value. current = this.__get(prop); // If we have an `object` and remaining parts. if (parts.length && Map.helpers.canMakeObserve(current)) { // That `object` should set it (this might need to call attr). current._set(parts, value); } else if (!parts.length) { // We're in "real" set territory. if (this.__convert) { value = this.__convert(prop, value); } this.__set(prop, value, current); } else { throw "can.Map: Object does not exist"; } }, __set: function(prop, value, current) { // Otherwise, we are setting it on this `object`. // TODO: Check if value is object and transform // are we changing the value. if (value !== current) { // Check if we are adding this for the first time -- // if we are, we need to create an `add` event. var changeType = this.__get() .hasOwnProperty(prop) ? "set" : "add"; // Set the value on data. this.___set(prop, // If we are getting an object. Map.helpers.canMakeObserve(value) ? // Hook it up to send event. Map.helpers.hookupBubble(value, prop, this) : // Value is normal. value); if (changeType === "add") { // If there is no current value, let others know that // the the number of keys have changed can.batch.trigger(this, "__keys", undefined); } // `batchTrigger` the change event. this._triggerChange(prop, changeType, value, current); //can.batch.trigger(this, prop, [value, current]); // If we can stop listening to our old value, do it. if (current) { Map.helpers.unhookup([current], this); } } }, // Directly sets a property on this `object`. ___set: function(prop, val) { if (this[prop] && this[prop].isComputed && can.isFunction(this.constructor.prototype[prop])) { this[prop](val); } this._data[prop] = val; // Add property directly for easy writing. // Check if its on the `prototype` so we don't overwrite methods like `attrs`. if (!(can.isFunction(this.constructor.prototype[prop]))) { this[prop] = val; } }, bind: function(eventName, handler) { var computedBinding = this._computedBindings && this._computedBindings[eventName]; if (computedBinding) { if (!computedBinding.count) { computedBinding.count = 1; var self = this; computedBinding.handler = function(ev, newVal, oldVal) { can.batch.trigger(self, { type: eventName, batchNum: ev.batchNum }, [newVal, oldVal]); }; this[eventName].bind("change", computedBinding.handler); } else { computedBinding.count++; } } return can.bindAndSetup.apply(this, arguments); }, unbind: function(eventName, handler) { var computedBinding = this._computedBindings && this._computedBindings[eventName]; if (computedBinding) { if (computedBinding.count === 1) { computedBinding.count = 0; this[eventName].unbind("change", computedBinding.handler); delete computedBinding.handler; } else { computedBinding.count++; } } return can.unbindAndTeardown.apply(this, arguments); }, serialize: function() { return can.Map.helpers.serialize(this, 'serialize', {}); }, _attrs: function(props, remove) { var self = this, newVal; if (props === undefined) { return Map.helpers.serialize(this, 'attr', {}); } props = can.simpleExtend({}, props); can.batch.start(); this.each(function(curVal, prop) { // you can not have a _cid property! if (prop === "_cid") { return; } newVal = props[prop]; // If we are merging... if (newVal === undefined) { if (remove) { self.removeAttr(prop); } return; } if (self.__convert) { newVal = self.__convert(prop, newVal); } // if we're dealing with models, want to call _set to let converter run if (newVal instanceof can.Map) { self.__set(prop, newVal, curVal); // if its an object, let attr merge } else if (Map.helpers.canMakeObserve(curVal) && Map.helpers.canMakeObserve(newVal) && curVal.attr) { curVal.attr(newVal, remove); // otherwise just set } else if (curVal !== newVal) { self.__set(prop, newVal, curVal); } delete props[prop]; }); // Add remaining props. for (var prop in props) { if (prop !== "_cid") { newVal = props[prop]; this._set(prop, newVal, true); } } can.batch.stop(); return this; }, compute: function(prop) { if (can.isFunction(this.constructor.prototype[prop])) { return can.compute(this[prop], this); } else { var reads = prop.split("."), last = reads.length - 1, options = { args: [] }; return can.compute(function(newVal) { if (arguments.length) { can.compute.read(this, reads.slice(0, last)) .value.attr(reads[last], newVal); } else { return can.compute.read(this, reads, options) .value; } }, this); } } }); Map.prototype.on = Map.prototype.bind; Map.prototype.off = Map.prototype.unbind; return Map; })(__m2, __m17, __m13, __m18); // ## list/list.js var __m19 = (function(can, Map) { // Helpers for `observable` lists. var splice = [].splice, // test if splice works correctly spliceRemovesProps = (function() { // IE's splice doesn't remove properties var obj = { 0: "a", length: 1 }; splice.call(obj, 0, 1); return !obj[0]; })(); var list = Map( { Map: Map }, { setup: function(instances, options) { this.length = 0; can.cid(this, ".map"); this._init = 1; instances = instances || []; var teardownMapping; if (can.isDeferred(instances)) { this.replace(instances); } else { teardownMapping = instances.length && can.Map.helpers.addToMap(instances, this); this.push.apply(this, can.makeArray(instances || [])); } if (teardownMapping) { teardownMapping(); } // this change needs to be ignored this.bind('change', can.proxy(this._changes, this)); can.simpleExtend(this, options); delete this._init; }, _triggerChange: function(attr, how, newVal, oldVal) { Map.prototype._triggerChange.apply(this, arguments); // `batchTrigger` direct add and remove events... if (!~attr.indexOf('.')) { if (how === 'add') { can.batch.trigger(this, how, [newVal, +attr]); can.batch.trigger(this, 'length', [this.length]); } else if (how === 'remove') { can.batch.trigger(this, how, [oldVal, +attr]); can.batch.trigger(this, 'length', [this.length]); } else { can.batch.trigger(this, how, [newVal, +attr]); } } }, __get: function(attr) { return attr ? this[attr] : this; }, ___set: function(attr, val) { this[attr] = val; if (+attr >= this.length) { this.length = (+attr + 1); } }, _each: function(callback) { var data = this.__get(); for (var i = 0; i < data.length; i++) { callback(data[i], i); } }, _bindsetup: Map.helpers.makeBindSetup("*"), // Returns the serialized form of this list. serialize: function() { return Map.helpers.serialize(this, 'serialize', []); }, splice: function(index, howMany) { var args = can.makeArray(arguments), i; for (i = 2; i < args.length; i++) { var val = args[i]; if (Map.helpers.canMakeObserve(val)) { args[i] = Map.helpers.hookupBubble(val, "*", this, this.constructor.Map, this.constructor); } } if (howMany === undefined) { howMany = args[1] = this.length - index; } var removed = splice.apply(this, args); if (!spliceRemovesProps) { for (i = this.length; i < removed.length + this.length; i++) { delete this[i]; } } can.batch.start(); if (howMany > 0) { this._triggerChange("" + index, "remove", undefined, removed); Map.helpers.unhookup(removed, this); } if (args.length > 2) { this._triggerChange("" + index, "add", args.slice(2), removed); } can.batch.stop(); return removed; }, _attrs: function(items, remove) { if (items === undefined) { return Map.helpers.serialize(this, 'attr', []); } // Create a copy. items = can.makeArray(items); can.batch.start(); this._updateAttrs(items, remove); can.batch.stop(); }, _updateAttrs: function(items, remove) { var len = Math.min(items.length, this.length); for (var prop = 0; prop < len; prop++) { var curVal = this[prop], newVal = items[prop]; if (Map.helpers.canMakeObserve(curVal) && Map.helpers.canMakeObserve(newVal)) { curVal.attr(newVal, remove); //changed from a coercion to an explicit } else if (curVal !== newVal) { this._set(prop, newVal); } else { } } if (items.length > this.length) { // Add in the remaining props. this.push.apply(this, items.slice(this.length)); } else if (items.length < this.length && remove) { this.splice(items.length); } } }), // Converts to an `array` of arguments. getArgs = function(args) { return args[0] && can.isArray(args[0]) ? args[0] : can.makeArray(args); }; // Create `push`, `pop`, `shift`, and `unshift` can.each({ push: "length", unshift: 0 }, // Adds a method // `name` - The method name. // `where` - Where items in the `array` should be added. function(where, name) { var orig = [][name]; list.prototype[name] = function() { // Get the items being added. var args = [], // Where we are going to add items. len = where ? this.length : 0, i = arguments.length, res, val; // Go through and convert anything to an `map` that needs to be converted. while (i--) { val = arguments[i]; args[i] = Map.helpers.canMakeObserve(val) ? Map.helpers.hookupBubble(val, "*", this, this.constructor.Map, this.constructor) : val; } // Call the original method. res = orig.apply(this, args); if (!this.comparator || args.length) { this._triggerChange("" + len, "add", args, undefined); } return res; }; }); can.each({ pop: "length", shift: 0 }, // Creates a `remove` type method function(where, name) { list.prototype[name] = function() { var args = getArgs(arguments), len = where && this.length ? this.length - 1 : 0; var res = [][name].apply(this, args); // Create a change where the args are // `len` - Where these items were removed. // `remove` - Items removed. // `undefined` - The new values (there are none). // `res` - The old, removed values (should these be unbound). this._triggerChange("" + len, "remove", undefined, [res]); if (res && res.unbind) { can.stopListening.call(this, res, "change"); } return res; }; }); can.extend(list.prototype, { indexOf: function(item, fromIndex) { this.attr('length'); return can.inArray(item, this, fromIndex); }, join: function() { return [].join.apply(this.attr(), arguments); }, reverse: [].reverse, slice: function() { var temp = Array.prototype.slice.apply(this, arguments); return new this.constructor(temp); }, concat: function() { var args = []; can.each(can.makeArray(arguments), function(arg, i) { args[i] = arg instanceof can.List ? arg.serialize() : arg; }); return new this.constructor(Array.prototype.concat.apply(this.serialize(), args)); }, forEach: function(cb, thisarg) { return can.each(this, cb, thisarg || this); }, replace: function(newList) { if (can.isDeferred(newList)) { newList.then(can.proxy(this.replace, this)); } else { this.splice.apply(this, [0, this.length].concat(can.makeArray(newList || []))); } return this; } }); can.List = Map.List = list; return can.List; })(__m2, __m16); // ## compute/compute.js var __m20 = (function(can, bind) { var names = [ '__reading', '__clearReading', '__setReading' ], setup = function(observed) { var old = {}; for (var i = 0; i < names.length; i++) { old[names[i]] = can[names[i]]; } can.__reading = function(obj, attr) { // Add the observe and attr that was read // to `observed` observed.push({ obj: obj, attr: attr + '' }); }; can.__clearReading = function() { return observed.splice(0, observed.length); }; can.__setReading = function(o) { [].splice.apply(observed, [ 0, observed.length ].concat(o)); }; return old; }, // empty default function k = function() {}; // returns the // - observes and attr methods are called by func // - the value returned by func // ex: `{value: 100, observed: [{obs: o, attr: "completed"}]}` var getValueAndObserved = function(func, self) { var observed = [], old = setup(observed), // Call the "wrapping" function to get the value. `observed` // will have the observe/attribute pairs that were read. value = func.call(self); // Set back so we are no longer reading. can.simpleExtend(can, old); return { value: value, observed: observed }; }, // Calls `callback(newVal, oldVal)` everytime an observed property // called within `getterSetter` is changed and creates a new result of `getterSetter`. // Also returns an object that can teardown all event handlers. computeBinder = function(getterSetter, context, callback, computeState) { // track what we are observing var observing = {}, // a flag indicating if this observe/attr pair is already bound matched = true, // the data to return data = { value: undefined, teardown: function() { for (var name in observing) { var ob = observing[name]; ob.observe.obj.unbind(ob.observe.attr, onchanged); delete observing[name]; } } }, batchNum; // when a property value is changed var onchanged = function(ev) { // If the compute is no longer bound (because the same change event led to an unbind) // then do not call getValueAndBind, or we will leak bindings. if (computeState && !computeState.bound) { return; } if (ev.batchNum === undefined || ev.batchNum !== batchNum) { // store the old value var oldValue = data.value, // get the new value newvalue = getValueAndBind(); // update the value reference (in case someone reads) data.value = newvalue; // if a change happened if (newvalue !== oldValue) { callback(newvalue, oldValue); } batchNum = batchNum = ev.batchNum; } }; // gets the value returned by `getterSetter` and also binds to any attributes // read by the call var getValueAndBind = function() { var info = getValueAndObserved(getterSetter, context), newObserveSet = info.observed; var value = info.value, ob; matched = !matched; // go through every attribute read by this observe for (var i = 0, len = newObserveSet.length; i < len; i++) { ob = newObserveSet[i]; // if the observe/attribute pair is being observed if (observing[ob.obj._cid + '|' + ob.attr]) { // mark at as observed observing[ob.obj._cid + '|' + ob.attr].matched = matched; } else { // otherwise, set the observe/attribute on oldObserved, marking it as being observed observing[ob.obj._cid + '|' + ob.attr] = { matched: matched, observe: ob }; ob.obj.bind(ob.attr, onchanged); } } // Iterate through oldObserved, looking for observe/attributes // that are no longer being bound and unbind them for (var name in observing) { ob = observing[name]; if (ob.matched !== matched) { ob.observe.obj.unbind(ob.observe.attr, onchanged); delete observing[name]; } } return value; }; // set the initial value data.value = getValueAndBind(); data.isListening = !can.isEmptyObject(observing); return data; }; var isObserve = function(obj) { return obj instanceof can.Map || obj && obj.__get; }; // if no one is listening ... we can not calculate every time can.compute = function(getterSetter, context, eventName) { if (getterSetter && getterSetter.isComputed) { return getterSetter; } // stores the result of computeBinder var computedData, // the computed object computed, // an object that keeps track if the computed is bound // onchanged needs to know this. It's possible a change happens and results in // something that unbinds the compute, it needs to not to try to recalculate who it // is listening to computeState = { bound: false, hasDependencies: false }, // The following functions are overwritten depending on how compute() is called // a method to setup listening on = k, // a method to teardown listening off = k, // the current cached value (only valid if bound = true) value, // how to read the value get = function() { return value; }, // sets the value set = function(newVal) { value = newVal; }, // this compute can be a dependency of other computes canReadForChangeEvent = true, // save for clone args = can.makeArray(arguments), updater = function(newValue, oldValue) { value = newValue; // might need a way to look up new and oldVal can.batch.trigger(computed, 'change', [ newValue, oldValue ]); }, // the form of the arguments form; computed = function(newVal) { // setting ... if (arguments.length) { // save a reference to the old value var old = value; // setter may return a value if // setter is for a value maintained exclusively by this compute var setVal = set.call(context, newVal, old); // if this has dependencies return the current value if (computed.hasDependencies) { return get.call(context); } if (setVal === undefined) { // it's possible, like with the DOM, setting does not // fire a change event, so we must read value = get.call(context); } else { value = setVal; } // fire the change if (old !== value) { can.batch.trigger(computed, 'change', [ value, old ]); } return value; } else { // Another compute wants to bind to this compute if (can.__reading && canReadForChangeEvent) { // Tell the compute to listen to change on this computed can.__reading(computed, 'change'); // We are going to bind on this compute. // If we are not bound, we should bind so that // we don't have to re-read to get the value of this compute. if (!computeState.bound) { can.compute.temporarilyBind(computed); } } // if we are bound, use the cached value if (computeState.bound) { return value; } else { return get.call(context); } } }; if (typeof getterSetter === 'function') { set = getterSetter; get = getterSetter; canReadForChangeEvent = eventName === false ? false : true; computed.hasDependencies = false; on = function(update) { computedData = computeBinder(getterSetter, context || this, update, computeState); computed.hasDependencies = computedData.isListening; value = computedData.value; }; off = function() { if (computedData) { computedData.teardown(); } }; } else if (context) { if (typeof context === 'string') { // `can.compute(obj, "propertyName", [eventName])` var propertyName = context, isObserve = getterSetter instanceof can.Map; if (isObserve) { computed.hasDependencies = true; } get = function() { if (isObserve) { return getterSetter.attr(propertyName); } else { return getterSetter[propertyName]; } }; set = function(newValue) { if (isObserve) { getterSetter.attr(propertyName, newValue); } else { getterSetter[propertyName] = newValue; } }; var handler; on = function(update) { handler = function() { update(get(), value); }; can.bind.call(getterSetter, eventName || propertyName, handler); // use getValueAndObserved because // we should not be indicating that some parent // reads this property if it happens to be binding on it value = getValueAndObserved(get) .value; }; off = function() { can.unbind.call(getterSetter, eventName || propertyName, handler); }; } else { // `can.compute(initialValue, setter)` if (typeof context === 'function') { value = getterSetter; set = context; context = eventName; form = 'setter'; } else { // `can.compute(initialValue,{get:, set:, on:, off:})` value = getterSetter; var options = context; get = options.get || get; set = options.set || set; on = options.on || on; off = options.off || off; } } } else { // `can.compute(5)` value = getterSetter; } can.cid(computed, 'compute'); return can.simpleExtend(computed, { isComputed: true, _bindsetup: function() { computeState.bound = true; // setup live-binding // while binding, this does not count as a read var oldReading = can.__reading; delete can.__reading; on.call(this, updater); can.__reading = oldReading; }, _bindteardown: function() { off.call(this, updater); computeState.bound = false; }, bind: can.bindAndSetup, unbind: can.unbindAndTeardown, clone: function(context) { if (context) { if (form === 'setter') { args[2] = context; } else { args[1] = context; } } return can.compute.apply(can, args); } }); }; // a list of temporarily bound computes var computes, unbindComputes = function() { for (var i = 0, len = computes.length; i < len; i++) { computes[i].unbind('change', k); } computes = null; }; // Binds computes for a moment to retain their value and prevent caching can.compute.temporarilyBind = function(compute) { compute.bind('change', k); if (!computes) { computes = []; setTimeout(unbindComputes, 10); } computes.push(compute); }; can.compute.binder = computeBinder; can.compute.truthy = function(compute) { return can.compute(function() { var res = compute(); if (typeof res === 'function') { res = res(); } return !!res; }); }; can.compute.read = function(parent, reads, options) { options = options || {}; // `cur` is the current value. var cur = parent, type, // `prev` is the object we are reading from. prev, // `foundObs` did we find an observable. foundObs; for (var i = 0, readLength = reads.length; i < readLength; i++) { // Update what we are reading from. prev = cur; // Read from the compute. We can't read a property yet. if (prev && prev.isComputed) { if (options.foundObservable) { options.foundObservable(prev, i); } prev = prev(); } // Look to read a property from something. if (isObserve(prev)) { if (!foundObs && options.foundObservable) { options.foundObservable(prev, i); } foundObs = 1; // is it a method on the prototype? if (typeof prev[reads[i]] === 'function' && prev.constructor.prototype[reads[i]] === prev[reads[i]]) { // call that method if (options.returnObserveMethods) { cur = cur[reads[i]]; } else if (reads[i] === 'constructor' && prev instanceof can.Construct) { cur = prev[reads[i]]; } else { cur = prev[reads[i]].apply(prev, options.args || []); } } else { // use attr to get that value cur = cur.attr(reads[i]); } } else { // just do the dot operator cur = prev[reads[i]]; } // If it's a compute, get the compute's value // unless we are at the end of the if (cur && cur.isComputed && (!options.isArgument && i < readLength - 1)) { if (!foundObs && options.foundObservable) { options.foundObservable(prev, i + 1); } cur = cur(); } type = typeof cur; // if there are properties left to read, and we don't have an object, early exit if (i < reads.length - 1 && (cur === null || type !== 'function' && type !== 'object')) { if (options.earlyExit) { options.earlyExit(prev, i, cur); } // return undefined so we know this isn't the right value return { value: undefined, parent: prev }; } } // handle an ending function if (typeof cur === 'function') { if (options.isArgument) { if (!cur.isComputed && options.proxyMethods !== false) { cur = can.proxy(cur, prev); } } else { if (cur.isComputed && !foundObs && options.foundObservable) { options.foundObservable(cur, i); } cur = cur.call(prev); } } // if we don't have a value, exit early. if (cur === undefined) { if (options.earlyExit) { options.earlyExit(prev, i - 1); } } return { value: cur, parent: prev }; }; return can.compute; })(__m2, __m17, __m18); // ## observe/observe.js var __m15 = (function(can) { can.Observe = can.Map; can.Observe.startBatch = can.batch.start; can.Observe.stopBatch = can.batch.stop; can.Observe.triggerBatch = can.batch.trigger; return can; })(__m2, __m16, __m19, __m20); // ## view/view.js var __m23 = (function(can) { // ## view.js // `can.view` // _Templating abstraction._ var isFunction = can.isFunction, makeArray = can.makeArray, // Used for hookup `id`s. hookupId = 1, $view = can.view = can.template = function(view, data, helpers, callback) { // If helpers is a `function`, it is actually a callback. if (isFunction(helpers)) { callback = helpers; helpers = undefined; } var pipe = function(result) { return $view.frag(result); }, // In case we got a callback, we need to convert the can.view.render // result to a document fragment wrapCallback = isFunction(callback) ? function(frag) { callback(pipe(frag)); } : null, // Get the result, if a renderer function is passed in, then we just use that to render the data result = isFunction(view) ? view(data, helpers, wrapCallback) : $view.render(view, data, helpers, wrapCallback), deferred = can.Deferred(); if (isFunction(result)) { return result; } if (can.isDeferred(result)) { result.then(function(result, data) { deferred.resolve.call(deferred, pipe(result), data); }, function() { deferred.fail.apply(deferred, arguments); }); return deferred; } // Convert it into a dom frag. return pipe(result); }; can.extend($view, { // creates a frag and hooks it up all at once frag: function(result, parentNode) { return $view.hookup($view.fragment(result), parentNode); }, // simply creates a frag // this is used internally to create a frag // insert it // then hook it up fragment: function(result) { var frag = can.buildFragment(result, document.body); // If we have an empty frag... if (!frag.childNodes.length) { frag.appendChild(document.createTextNode('')); } return frag; }, // Convert a path like string into something that's ok for an `element` ID. toId: function(src) { return can.map(src.toString() .split(/\/|\./g), function(part) { // Dont include empty strings in toId functions if (part) { return part; } }) .join('_'); }, hookup: function(fragment, parentNode) { var hookupEls = [], id, func; // Get all `childNodes`. can.each(fragment.childNodes ? can.makeArray(fragment.childNodes) : fragment, function(node) { if (node.nodeType === 1) { hookupEls.push(node); hookupEls.push.apply(hookupEls, can.makeArray(node.getElementsByTagName('*'))); } }); // Filter by `data-view-id` attribute. can.each(hookupEls, function(el) { if (el.getAttribute && (id = el.getAttribute('data-view-id')) && (func = $view.hookups[id])) { func(el, parentNode, id); delete $view.hookups[id]; el.removeAttribute('data-view-id'); } }); return fragment; }, // auj // heir hookups: {}, hook: function(cb) { $view.hookups[++hookupId] = cb; return ' data-view-id=\'' + hookupId + '\''; }, cached: {}, cachedRenderers: {}, cache: true, register: function(info) { this.types['.' + info.suffix] = info; }, types: {}, ext: ".ejs", registerScript: function() {}, preload: function() {}, render: function(view, data, helpers, callback) { // If helpers is a `function`, it is actually a callback. if (isFunction(helpers)) { callback = helpers; helpers = undefined; } // See if we got passed any deferreds. var deferreds = getDeferreds(data); var reading, deferred, dataCopy, async, response; if (deferreds.length) { // Does data contain any deferreds? // The deferred that resolves into the rendered content... deferred = new can.Deferred(); dataCopy = can.extend({}, data); // Add the view request to the list of deferreds. deferreds.push(get(view, true)); // Wait for the view and all deferreds to finish... can.when.apply(can, deferreds) .then(function(resolved) { // Get all the resolved deferreds. var objs = makeArray(arguments), // Renderer is the last index of the data. renderer = objs.pop(), // The result of the template rendering with data. result; // Make data look like the resolved deferreds. if (can.isDeferred(data)) { dataCopy = usefulPart(resolved); } else { // Go through each prop in data again and // replace the defferreds with what they resolved to. for (var prop in data) { if (can.isDeferred(data[prop])) { dataCopy[prop] = usefulPart(objs.shift()); } } } // Get the rendered result. result = renderer(dataCopy, helpers); // Resolve with the rendered view. deferred.resolve(result, dataCopy); // If there's a `callback`, call it back with the result. if (callback) { callback(result, dataCopy); } }, function() { deferred.reject.apply(deferred, arguments); }); // Return the deferred... return deferred; } else { // get is called async but in // ff will be async so we need to temporarily reset if (can.__reading) { reading = can.__reading; can.__reading = null; } // No deferreds! Render this bad boy. // If there's a `callback` function async = isFunction(callback); // Get the `view` type deferred = get(view, async); if (can.Map && reading) { can.__reading = reading; } // If we are `async`... if (async) { // Return the deferred response = deferred; // And fire callback with the rendered result. deferred.then(function(renderer) { callback(data ? renderer(data, helpers) : renderer); }); } else { // if the deferred is resolved, call the cached renderer instead // this is because it's possible, with recursive deferreds to // need to render a view while its deferred is _resolving_. A _resolving_ deferred // is a deferred that was just resolved and is calling back it's success callbacks. // If a new success handler is called while resoliving, it does not get fired by // jQuery's deferred system. So instead of adding a new callback // we use the cached renderer. // We also add __view_id on the deferred so we can look up it's cached renderer. // In the future, we might simply store either a deferred or the cached result. if (deferred.state() === 'resolved' && deferred.__view_id) { var currentRenderer = $view.cachedRenderers[deferred.__view_id]; return data ? currentRenderer(data, helpers) : currentRenderer; } else { // Otherwise, the deferred is complete, so // set response to the result of the rendering. deferred.then(function(renderer) { response = data ? renderer(data, helpers) : renderer; }); } } return response; } }, registerView: function(id, text, type, def) { // Get the renderer function. var func = (type || $view.types[$view.ext]) .renderer(id, text); def = def || new can.Deferred(); // Cache if we are caching. if ($view.cache) { $view.cached[id] = def; def.__view_id = id; $view.cachedRenderers[id] = func; } // Return the objects for the response's `dataTypes` // (in this case view). return def.resolve(func); } }); // Makes sure there's a template, if not, have `steal` provide a warning. var checkText = function(text, url) { if (!text.length) { throw "can.view: No template or empty template:" + url; } }, // `Returns a `view` renderer deferred. // `url` - The url to the template. // `async` - If the ajax request should be asynchronous. // Returns a deferred. get = function(obj, async) { var url = typeof obj === 'string' ? obj : obj.url, suffix = obj.engine || url.match(/\.[\w\d]+$/), type, // If we are reading a script element for the content of the template, // `el` will be set to that script element. el, // A unique identifier for the view (used for caching). // This is typically derived from the element id or // the url for the template. id; //If the url has a #, we assume we want to use an inline template //from a script element and not current page's HTML if (url.match(/^#/)) { url = url.substr(1); } // If we have an inline template, derive the suffix from the `text/???` part. // This only supports `<script>` tags. if (el = document.getElementById(url)) { suffix = '.' + el.type.match(/\/(x\-)?(.+)/)[2]; } // If there is no suffix, add one. if (!suffix && !$view.cached[url]) { url += suffix = $view.ext; } if (can.isArray(suffix)) { suffix = suffix[0]; } // Convert to a unique and valid id. id = $view.toId(url); // If an absolute path, use `steal`/`require` to get it. // You should only be using `//` if you are using an AMD loader like `steal` or `require` (not almond). if (url.match(/^\/\//)) { url = url.substr(2); url = !window.steal ? url : steal.config() .root.mapJoin("" + steal.id(url)); } // Localize for `require` (not almond) if (window.require) { if (require.toUrl) { url = require.toUrl(url); } } // Set the template engine type. type = $view.types[suffix]; // If it is cached, if ($view.cached[id]) { // Return the cached deferred renderer. return $view.cached[id]; // Otherwise if we are getting this from a `<script>` element. } else if (el) { // Resolve immediately with the element's `innerHTML`. return $view.registerView(id, el.innerHTML, type); } else { // Make an ajax request for text. var d = new can.Deferred(); can.ajax({ async: async, url: url, dataType: 'text', error: function(jqXHR) { checkText('', url); d.reject(jqXHR); }, success: function(text) { // Make sure we got some text back. checkText(text, url); $view.registerView(id, text, type, d); } }); return d; } }, // Gets an `array` of deferreds from an `object`. // This only goes one level deep. getDeferreds = function(data) { var deferreds = []; // pull out deferreds if (can.isDeferred(data)) { return [data]; } else { for (var prop in data) { if (can.isDeferred(data[prop])) { deferreds.push(data[prop]); } } } return deferreds; }, // Gets the useful part of a resolved deferred. // This is for `model`s and `can.ajax` that resolve to an `array`. usefulPart = function(resolved) { return can.isArray(resolved) && resolved[1] === 'success' ? resolved[0] : resolved; }; can.extend($view, { register: function(info) { this.types['.' + info.suffix] = info; $view[info.suffix] = function(id, text) { if (!text) { // Return a nameless renderer var renderer = function() { return $view.frag(renderer.render.apply(this, arguments)); }; renderer.render = function() { var renderer = info.renderer(null, id); return renderer.apply(renderer, arguments); }; return renderer; } return $view.preload(id, info.renderer(id, text)); }; }, registerScript: function(type, id, src) { return 'can.view.preload(\'' + id + '\',' + $view.types['.' + type].script(id, src) + ');'; }, preload: function(id, renderer) { var def = $view.cached[id] = new can.Deferred() .resolve(function(data, helpers) { return renderer.call(data, data, helpers); }); function frag() { return $view.frag(renderer.apply(this, arguments)); } // expose the renderer for mustache frag.render = renderer; // set cache references (otherwise preloaded recursive views won't recurse properly) def.__view_id = id; $view.cachedRenderers[id] = renderer; return frag; } }); return can; })(__m2); // ## view/scope/scope.js var __m22 = (function(can) { var escapeReg = /(\\)?\./g; var escapeDotReg = /\\\./g; var getNames = function(attr) { var names = [], last = 0; attr.replace(escapeReg, function(first, second, index) { if (!second) { names.push(attr.slice(last, index) .replace(escapeDotReg, '.')); last = index + first.length; } }); names.push(attr.slice(last) .replace(escapeDotReg, '.')); return names; }; var Scope = can.Construct.extend( { // reads properties from a parent. A much more complex version of getObject. read: can.compute.read }, { init: function(context, parent) { this._context = context; this._parent = parent; }, attr: function(key) { // reads for whatever called before attr. It's possible // that this.read clears them. We want to restore them. var previousReads = can.__clearReading && can.__clearReading(), res = this.read(key, { isArgument: true, returnObserveMethods: true, proxyMethods: false }) .value; if (can.__setReading) { can.__setReading(previousReads); } return res; }, add: function(context) { if (context !== this._context) { return new this.constructor(context, this); } else { return this; } }, computeData: function(key, options) { options = options || { args: [] }; var self = this, rootObserve, rootReads, computeData = { compute: can.compute(function(newVal) { if (arguments.length) { // check that there's just a compute with nothing from it ... if (rootObserve.isComputed && !rootReads.length) { rootObserve(newVal); } else { var last = rootReads.length - 1; Scope.read(rootObserve, rootReads.slice(0, last)) .value.attr(rootReads[last], newVal); } } else { if (rootObserve) { return Scope.read(rootObserve, rootReads, options) .value; } // otherwise, go get the value var data = self.read(key, options); rootObserve = data.rootObserve; rootReads = data.reads; computeData.scope = data.scope; computeData.initialValue = data.value; return data.value; } }) }; return computeData; }, read: function(attr, options) { // check if we should be running this on a parent. if (attr.substr(0, 3) === '../') { return this._parent.read(attr.substr(3), options); } else if (attr === '..') { return { value: this._parent._context }; } else if (attr === '.' || attr === 'this') { return { value: this._context }; } // Split the name up. var names = attr.indexOf('\\.') === -1 ? // Reference doesn't contain escaped periods attr.split('.') // Reference contains escaped periods (`a.b\c.foo` == `a["b.c"].foo) : getNames(attr), // The current context (a scope is just data and a parent scope). context, // The current scope. scope = this, // While we are looking for a value, we track the most likely place this value will be found. // This is so if there is no me.name.first, we setup a listener on me.name. // The most likely canidate is the one with the most "read matches" "lowest" in the // context chain. // By "read matches", we mean the most number of values along the key. // By "lowest" in the context chain, we mean the closest to the current context. // We track the starting position of the likely place with `defaultObserve`. defaultObserve, // Tracks how to read from the defaultObserve. defaultReads = [], // Tracks the highest found number of "read matches". defaultPropertyDepth = -1, // `scope.read` is designed to be called within a compute, but // for performance reasons only listens to observables within one context. // This is to say, if you have me.name in the current context, but me.name.first and // we are looking for me.name.first, we don't setup bindings on me.name and me.name.first. // To make this happen, we clear readings if they do not find a value. But, // if that path turns out to be the default read, we need to restore them. This // variable remembers those reads so they can be restored. defaultComputeReadings, // Tracks the default's scope. defaultScope, // Tracks the first found observe. currentObserve, // Tracks the reads to get the value for a scope. currentReads; // While there is a scope/context to look in. while (scope) { // get the context context = scope._context; if (context !== null) { // Lets try this context var data = Scope.read(context, names, can.simpleExtend({ // Called when an observable is found. foundObservable: function(observe, nameIndex) { // Save the current observe. currentObserve = observe; currentReads = names.slice(nameIndex); }, // Called when we were unable to find a value. earlyExit: function(parentValue, nameIndex) { // If this has more matching values, if (nameIndex > defaultPropertyDepth) { // save the state. defaultObserve = currentObserve; defaultReads = currentReads; defaultPropertyDepth = nameIndex; defaultScope = scope; // Clear and save readings so next attempt does not use these readings defaultComputeReadings = can.__clearReading && can.__clearReading(); } } }, options)); // Found a matched reference. if (data.value !== undefined) { return { scope: scope, rootObserve: currentObserve, value: data.value, reads: currentReads }; } } // Prevent prior readings. if (can.__clearReading) { can.__clearReading(); } // Move up to the next scope. scope = scope._parent; } // If there was a likely observe. if (defaultObserve) { // Restore reading for previous compute if (can.__setReading) { can.__setReading(defaultComputeReadings); } return { scope: defaultScope, rootObserve: defaultObserve, reads: defaultReads, value: undefined }; } else { // we found nothing and no observable return { names: names, value: undefined }; } } }); can.view.Scope = Scope; return Scope; })(__m2, __m13, __m16, __m19, __m23, __m20); // ## view/elements.js var __m25 = (function(can) { var elements = { tagToContentPropMap: { option: 'textContent' in document.createElement('option') ? 'textContent' : 'innerText', textarea: 'value' }, attrMap: { 'class': 'className', 'value': 'value', 'innerText': 'innerText', 'textContent': 'textContent', 'checked': true, 'disabled': true, 'readonly': true, 'required': true, src: function(el, val) { if (val === null || val === '') { el.removeAttribute('src'); } else { el.setAttribute('src', val); } } }, attrReg: /([^\s=]+)[\s]*=[\s]*/, // elements whos default value we should set defaultValue: ["input", "textarea"], // a map of parent element to child elements tagMap: { '': 'span', table: 'tbody', tr: 'td', ol: 'li', ul: 'li', tbody: 'tr', thead: 'tr', tfoot: 'tr', select: 'option', optgroup: 'option' }, // a tag's parent element reverseTagMap: { tr: 'tbody', option: 'select', td: 'tr', th: 'tr', li: 'ul' }, // Used to determine the parentNode if el is directly within a documentFragment getParentNode: function(el, defaultParentNode) { return defaultParentNode && el.parentNode.nodeType === 11 ? defaultParentNode : el.parentNode; }, // Set an attribute on an element setAttr: function(el, attrName, val) { var tagName = el.nodeName.toString() .toLowerCase(), prop = elements.attrMap[attrName]; // if this is a special property if (typeof prop === "function") { prop(el, val); } else if (prop === true && attrName === "checked" && el.type === "radio") { // IE7 bugs sometimes if defaultChecked isn't set first if (can.inArray(tagName, elements.defaultValue) >= 0) { el.defaultChecked = true; } el[attrName] = true; } else if (prop === true) { el[attrName] = true; } else if (prop) { // set the value as true / false el[prop] = val; if (prop === 'value' && can.inArray(tagName, elements.defaultValue) >= 0) { el.defaultValue = val; } } else { el.setAttribute(attrName, val); } }, // Gets the value of an attribute. getAttr: function(el, attrName) { // Default to a blank string for IE7/8 return (elements.attrMap[attrName] && el[elements.attrMap[attrName]] ? el[elements.attrMap[attrName]] : el.getAttribute(attrName)) || ''; }, // Removes the attribute. removeAttr: function(el, attrName) { var setter = elements.attrMap[attrName]; if (setter === true) { el[attrName] = false; } else if (typeof setter === 'string') { el[setter] = ''; } else { el.removeAttribute(attrName); } }, // Gets a "pretty" value for something contentText: function(text) { if (typeof text === 'string') { return text; } // If has no value, return an empty string. if (!text && text !== 0) { return ''; } return '' + text; }, after: function(oldElements, newFrag) { var last = oldElements[oldElements.length - 1]; // Insert it in the `document` or `documentFragment` if (last.nextSibling) { can.insertBefore(last.parentNode, newFrag, last.nextSibling); } else { can.appendChild(last.parentNode, newFrag); } }, replace: function(oldElements, newFrag) { elements.after(oldElements, newFrag); can.remove(can.$(oldElements)); } }; // TODO: this doesn't seem to be doing anything // feature detect if setAttribute works with styles (function() { // feature detect if var div = document.createElement('div'); div.setAttribute('style', 'width: 5px'); div.setAttribute('style', 'width: 10px'); // make style use cssText elements.attrMap.style = function(el, val) { el.style.cssText = val || ''; }; }()); return elements; })(__m2); // ## view/scanner.js var __m24 = (function(can, elements) { var newLine = /(\r|\n)+/g, // Escapes characters starting with `\`. clean = function(content) { return content.split('\\') .join('\\\\') .split('\n') .join('\\n') .split('"') .join('\\"') .split('\t') .join('\\t'); }, // Returns a tagName to use as a temporary placeholder for live content // looks forward ... could be slow, but we only do it when necessary getTag = function(tagName, tokens, i) { // if a tagName is provided, use that if (tagName) { return tagName; } else { // otherwise go searching for the next two tokens like "<",TAG while (i < tokens.length) { if (tokens[i] === '<' && elements.reverseTagMap[tokens[i + 1]]) { return elements.reverseTagMap[tokens[i + 1]]; } i++; } } return ''; }, bracketNum = function(content) { return content.split('{') .length - content.split('}') .length; }, myEval = function(script) { eval(script); }, attrReg = /([^\s]+)[\s]*=[\s]*$/, // Commands for caching. startTxt = 'var ___v1ew = [];', finishTxt = 'return ___v1ew.join(\'\')', put_cmd = '___v1ew.push(\n', insert_cmd = put_cmd, // Global controls (used by other functions to know where we are). // Are we inside a tag? htmlTag = null, // Are we within a quote within a tag? quote = null, // What was the text before the current quote? (used to get the `attr` name) beforeQuote = null, // Whether a rescan is in progress rescan = null, getAttrName = function() { var matches = beforeQuote.match(attrReg); return matches && matches[1]; }, // Used to mark where the element is. status = function() { // `t` - `1`. // `h` - `0`. // `q` - String `beforeQuote`. return quote ? '\'' + getAttrName() + '\'' : htmlTag ? 1 : 0; }, // returns the top of a stack top = function(stack) { return stack[stack.length - 1]; }, // characters that automatically mean a custom element automaticCustomElementCharacters = /[-\:]/, Scanner; can.view.Scanner = Scanner = function(options) { // Set options on self can.extend(this, { text: {}, tokens: [] }, options); // make sure it's an empty string if it's not this.text.options = this.text.options || ''; // Cache a token lookup this.tokenReg = []; this.tokenSimple = { "<": "<", ">": ">", '"': '"', "'": "'" }; this.tokenComplex = []; this.tokenMap = {}; for (var i = 0, token; token = this.tokens[i]; i++) { // Save complex mappings (custom regexp) if (token[2]) { this.tokenReg.push(token[2]); this.tokenComplex.push({ abbr: token[1], re: new RegExp(token[2]), rescan: token[3] }); } // Save simple mappings (string only, no regexp) else { this.tokenReg.push(token[1]); this.tokenSimple[token[1]] = token[0]; } this.tokenMap[token[0]] = token[1]; } // Cache the token registry. this.tokenReg = new RegExp("(" + this.tokenReg.slice(0) .concat(["<", ">", '"', "'"]) .join("|") + ")", "g"); }; Scanner.attributes = {}; Scanner.regExpAttributes = {}; Scanner.attribute = function(attribute, callback) { if (typeof attribute === 'string') { Scanner.attributes[attribute] = callback; } else { Scanner.regExpAttributes[attribute] = { match: attribute, callback: callback }; } }; Scanner.hookupAttributes = function(options, el) { can.each(options && options.attrs || [], function(attr) { options.attr = attr; if (Scanner.attributes[attr]) { Scanner.attributes[attr](options, el); } else { can.each(Scanner.regExpAttributes, function(attrMatcher) { if (attrMatcher.match.test(attr)) { attrMatcher.callback(options, el); } }); } }); }; Scanner.tag = function(tagName, callback) { // if we have html5shive ... re-generate if (window.html5) { window.html5.elements += ' ' + tagName; window.html5.shivDocument(); } Scanner.tags[tagName.toLowerCase()] = callback; }; Scanner.tags = {}; // This is called when there is a special tag Scanner.hookupTag = function(hookupOptions) { // we need to call any live hookups // so get that and return the hook // a better system will always be called with the same stuff var hooks = can.view.getHooks(); return can.view.hook(function(el) { can.each(hooks, function(fn) { fn(el); }); var tagName = hookupOptions.tagName, helperTagCallback = hookupOptions.options.read('helpers._tags.' + tagName, { isArgument: true, proxyMethods: false }) .value, tagCallback = helperTagCallback || Scanner.tags[tagName]; // If this was an element like <foo-bar> that doesn't have a component, just render its content var scope = hookupOptions.scope, res = tagCallback ? tagCallback(el, hookupOptions) : scope; // If the tagCallback gave us something to render with, and there is content within that element // render it! if (res && hookupOptions.subtemplate) { if (scope !== res) { scope = scope.add(res); } var frag = can.view.frag(hookupOptions.subtemplate(scope, hookupOptions.options)); can.appendChild(el, frag); } can.view.Scanner.hookupAttributes(hookupOptions, el); }); }; Scanner.prototype = { // a default that can be overwritten helpers: [], scan: function(source, name) { var tokens = [], last = 0, simple = this.tokenSimple, complex = this.tokenComplex; var cleanedTagName; source = source.replace(newLine, '\n'); if (this.transform) { source = this.transform(source); } source.replace(this.tokenReg, function(whole, part) { // offset is the second to last argument var offset = arguments[arguments.length - 2]; // if the next token starts after the last token ends // push what's in between if (offset > last) { tokens.push(source.substring(last, offset)); } // push the simple token (if there is one) if (simple[whole]) { tokens.push(whole); } // otherwise lookup complex tokens else { for (var i = 0, token; token = complex[i]; i++) { if (token.re.test(whole)) { tokens.push(token.abbr); // Push a rescan function if one exists if (token.rescan) { tokens.push(token.rescan(part)); } break; } } } // update the position of the last part of the last token last = offset + part.length; }); // if there's something at the end, add it if (last < source.length) { tokens.push(source.substr(last)); } var content = '', buff = [startTxt + (this.text.start || '')], // Helper `function` for putting stuff in the view concat. put = function(content, bonus) { buff.push(put_cmd, '"', clean(content), '"' + (bonus || '') + ');'); }, // A stack used to keep track of how we should end a bracket // `}`. // Once we have a `<%= %>` with a `leftBracket`, // we store how the file should end here (either `))` or `;`). endStack = [], // The last token, used to remember which tag we are in. lastToken, // The corresponding magic tag. startTag = null, // Was there a magic tag inside an html tag? magicInTag = false, // was there a special state specialStates = { attributeHookups: [], // a stack of tagHookups tagHookups: [] }, // The current tag name. tagName = '', // stack of tagNames tagNames = [], // Pop from tagNames? popTagName = false, // Declared here. bracketCount, // in a special attr like src= or style= specialAttribute = false, i = 0, token, tmap = this.tokenMap, attrName; // Reinitialize the tag state goodness. htmlTag = quote = beforeQuote = null; for (; (token = tokens[i++]) !== undefined;) { if (startTag === null) { switch (token) { case tmap.left: case tmap.escapeLeft: case tmap.returnLeft: magicInTag = htmlTag && 1; case tmap.commentLeft: // A new line -- just add whatever content within a clean. // Reset everything. startTag = token; if (content.length) { put(content); } content = ''; break; case tmap.escapeFull: // This is a full line escape (a line that contains only whitespace and escaped logic) // Break it up into escape left and right magicInTag = htmlTag && 1; rescan = 1; startTag = tmap.escapeLeft; if (content.length) { put(content); } rescan = tokens[i++]; content = rescan.content || rescan; if (rescan.before) { put(rescan.before); } tokens.splice(i, 0, tmap.right); break; case tmap.commentFull: // Ignore full line comments. break; case tmap.templateLeft: content += tmap.left; break; case '<': // Make sure we are not in a comment. if (tokens[i].indexOf('!--') !== 0) { htmlTag = 1; magicInTag = 0; } content += token; break; case '>': htmlTag = 0; // content.substr(-1) doesn't work in IE7/8 var emptyElement = content.substr(content.length - 1) === '/' || content.substr(content.length - 2) === '--', attrs = ''; // if there was a magic tag // or it's an element that has text content between its tags, // but content is not other tags add a hookup // TODO: we should only add `can.EJS.pending()` if there's a magic tag // within the html tags. if (specialStates.attributeHookups.length) { attrs = "attrs: ['" + specialStates.attributeHookups.join("','") + "'], "; specialStates.attributeHookups = []; } // this is the > of a special tag if (tagName === top(specialStates.tagHookups)) { // If it's a self closing tag (like <content/>) make sure we put the / at the end. if (emptyElement) { content = content.substr(0, content.length - 1); } // Put the start of the end buff.push(put_cmd, '"', clean(content), '"', ",can.view.Scanner.hookupTag({tagName:'" + tagName + "'," + (attrs) + "scope: " + (this.text.scope || "this") + this.text.options); // if it's a self closing tag (like <content/>) close and end the tag if (emptyElement) { buff.push("}));"); content = "/>"; specialStates.tagHookups.pop(); } // if it's an empty tag else if (tokens[i] === "<" && tokens[i + 1] === "/" + tagName) { buff.push("}));"); content = token; specialStates.tagHookups.pop(); } else { // it has content buff.push(",subtemplate: function(" + this.text.argNames + "){\n" + startTxt + (this.text.start || '')); content = ''; } } else if (magicInTag || !popTagName && elements.tagToContentPropMap[tagNames[tagNames.length - 1]] || attrs) { // make sure / of /> is on the right of pending var pendingPart = ",can.view.pending({" + attrs + "scope: " + (this.text.scope || "this") + this.text.options + "}),\""; if (emptyElement) { put(content.substr(0, content.length - 1), pendingPart + "/>\""); } else { put(content, pendingPart + ">\""); } content = ''; magicInTag = 0; } else { content += token; } // if it's a tag like <input/> if (emptyElement || popTagName) { // remove the current tag in the stack tagNames.pop(); // set the current tag to the previous parent tagName = tagNames[tagNames.length - 1]; // Don't pop next time popTagName = false; } specialStates.attributeHookups = []; break; case "'": case '"': // If we are in an html tag, finding matching quotes. if (htmlTag) { // We have a quote and it matches. if (quote && quote === token) { // We are exiting the quote. quote = null; // Otherwise we are creating a quote. // TODO: does this handle `\`? var attr = getAttrName(); if (Scanner.attributes[attr]) { specialStates.attributeHookups.push(attr); } else { can.each(Scanner.regExpAttributes, function(attrMatcher) { if (attrMatcher.match.test(attr)) { specialStates.attributeHookups.push(attr); } }); } if (specialAttribute) { content += token; put(content); buff.push(finishTxt, "}));\n"); content = ""; specialAttribute = false; break; } } else if (quote === null) { quote = token; beforeQuote = lastToken; attrName = getAttrName(); // TODO: check if there's magic!!!! if (tagName === 'img' && attrName === 'src' || attrName === 'style') { // put content that was before the attr name, but don't include the src= put(content.replace(attrReg, "")); content = ''; specialAttribute = true; buff.push(insert_cmd, "can.view.txt(2,'" + getTag(tagName, tokens, i) + "'," + status() + ",this,function(){", startTxt); put(attrName + "=" + token); break; } } } //default is meant to run on all cases default: // Track the current tag if (lastToken === '<') { tagName = token.substr(0, 3) === "!--" ? "!--" : token.split(/\s/)[0]; var isClosingTag = false; if (tagName.indexOf("/") === 0) { isClosingTag = true; cleanedTagName = tagName.substr(1); } if (isClosingTag) { // </tag> // when we enter a new tag, pop the tag name stack if (top(tagNames) === cleanedTagName) { // set tagName to the last tagName // if there are no more tagNames, we'll rely on getTag. tagName = cleanedTagName; popTagName = true; } // if we are in a closing tag of a custom tag if (top(specialStates.tagHookups) === cleanedTagName) { // remove the last < from the content put(content.substr(0, content.length - 1)); // finish the "section" buff.push(finishTxt + "}}) );"); // the < belongs to the outside content = "><"; specialStates.tagHookups.pop(); } } else { if (tagName.lastIndexOf('/') === tagName.length - 1) { tagName = tagName.substr(0, tagName.length - 1); } if (tagName !== "!--" && (Scanner.tags[tagName] || automaticCustomElementCharacters.test(tagName))) { // if the content tag is inside something it doesn't belong ... if (tagName === 'content' && elements.tagMap[top(tagNames)]) { // convert it to an element that will work token = token.replace('content', elements.tagMap[top(tagNames)]); } // we will hookup at the ending tag> specialStates.tagHookups.push(tagName); } tagNames.push(tagName); } } content += token; break; } } else { // We have a start tag. switch (token) { case tmap.right: case tmap.returnRight: switch (startTag) { case tmap.left: // Get the number of `{ minus }` bracketCount = bracketNum(content); // We are ending a block. if (bracketCount === 1) { // We are starting on. buff.push(insert_cmd, 'can.view.txt(0,\'' + getTag(tagName, tokens, i) + '\',' + status() + ',this,function(){', startTxt, content); endStack.push({ before: '', after: finishTxt + '}));\n' }); } else { // How are we ending this statement? last = endStack.length && bracketCount === -1 ? endStack.pop() : { after: ';' }; // If we are ending a returning block, // add the finish text which returns the result of the // block. if (last.before) { buff.push(last.before); } // Add the remaining content. buff.push(content, ';', last.after); } break; case tmap.escapeLeft: case tmap.returnLeft: // We have an extra `{` -> `block`. // Get the number of `{ minus }`. bracketCount = bracketNum(content); // If we have more `{`, it means there is a block. if (bracketCount) { // When we return to the same # of `{` vs `}` end with a `doubleParent`. endStack.push({ before: finishTxt, after: '}));\n' }); } var escaped = startTag === tmap.escapeLeft ? 1 : 0, commands = { insert: insert_cmd, tagName: getTag(tagName, tokens, i), status: status(), specialAttribute: specialAttribute }; for (var ii = 0; ii < this.helpers.length; ii++) { // Match the helper based on helper // regex name value var helper = this.helpers[ii]; if (helper.name.test(content)) { content = helper.fn(content, commands); // dont escape partials if (helper.name.source === /^>[\s]*\w*/.source) { escaped = 0; } break; } } // Handle special cases if (typeof content === 'object') { if (content.raw) { buff.push(content.raw); } } else if (specialAttribute) { buff.push(insert_cmd, content, ');'); } else { // If we have `<%== a(function(){ %>` then we want // `can.EJS.text(0,this, function(){ return a(function(){ var _v1ew = [];`. buff.push(insert_cmd, "can.view.txt(\n" + (typeof status() === "string" || escaped) + ",\n'" + tagName + "',\n" + status() + ",\n" + "this,\nfunction(){ " + (this.text.escape || '') + "return ", content, // If we have a block. bracketCount ? // Start with startTxt `"var _v1ew = [];"`. startTxt : // If not, add `doubleParent` to close push and text. "}));\n"); } if (rescan && rescan.after && rescan.after.length) { put(rescan.after.length); rescan = null; } break; } startTag = null; content = ''; break; case tmap.templateLeft: content += tmap.left; break; default: content += token; break; } } lastToken = token; } // Put it together... if (content.length) { // Should be `content.dump` in Ruby. put(content); } buff.push(';'); var template = buff.join(''), out = { out: (this.text.outStart || '') + template + ' ' + finishTxt + (this.text.outEnd || '') }; // Use `eval` instead of creating a function, because it is easier to debug. myEval.call(out, 'this.fn = (function(' + this.text.argNames + '){' + out.out + '});\r\n//@ sourceURL=' + name + '.js'); return out; } }; can.view.Scanner.tag('content', function(el, options) { return options.scope; }); return Scanner; })(__m23, __m25); // ## view/node_lists/node_lists.js var __m28 = (function(can) { // In some browsers, text nodes can not take expando properties. // We test that here. var canExpando = true; try { document.createTextNode('') ._ = 0; } catch (ex) { canExpando = false; } // A mapping of element ids to nodeList id var nodeMap = {}, // A mapping of ids to text nodes textNodeMap = {}, expando = 'ejs_' + Math.random(), _id = 0, id = function(node) { if (canExpando || node.nodeType !== 3) { if (node[expando]) { return node[expando]; } else { ++_id; return node[expando] = (node.nodeName ? 'element_' : 'obj_') + _id; } } else { for (var textNodeID in textNodeMap) { if (textNodeMap[textNodeID] === node) { return textNodeID; } } ++_id; textNodeMap['text_' + _id] = node; return 'text_' + _id; } }, splice = [].splice; var nodeLists = { id: id, update: function(nodeList, newNodes) { // Unregister all childNodes. can.each(nodeList.childNodeLists, function(nodeList) { nodeLists.unregister(nodeList); }); nodeList.childNodeLists = []; // Remove old node pointers to this list. can.each(nodeList, function(node) { delete nodeMap[id(node)]; }); newNodes = can.makeArray(newNodes); // indicate the new nodes belong to this list can.each(newNodes, function(node) { nodeMap[id(node)] = nodeList; }); var oldListLength = nodeList.length, firstNode = nodeList[0]; // Replace oldNodeLists's contents' splice.apply(nodeList, [ 0, oldListLength ].concat(newNodes)); // update all parent nodes so they are able to replace the correct elements var parentNodeList = nodeList; while (parentNodeList = parentNodeList.parentNodeList) { splice.apply(parentNodeList, [ can.inArray(firstNode, parentNodeList), oldListLength ].concat(newNodes)); } }, register: function(nodeList, unregistered, parent) { // add an id to the nodeList nodeList.unregistered = unregistered; nodeList.childNodeLists = []; if (!parent) { // find the parent by looking up where this node is if (nodeList.length > 1) { throw 'does not work'; } var nodeId = id(nodeList[0]); parent = nodeMap[nodeId]; } nodeList.parentNodeList = parent; if (parent) { parent.childNodeLists.push(nodeList); } return nodeList; }, // removes node in all parent nodes and unregisters all childNodes unregister: function(nodeList) { if (!nodeList.isUnregistered) { nodeList.isUnregistered = true; // unregister all childNodeLists delete nodeList.parentNodeList; can.each(nodeList, function(node) { var nodeId = id(node); delete nodeMap[nodeId]; }); // this can unbind which will call itself if (nodeList.unregistered) { nodeList.unregistered(); } can.each(nodeList.childNodeLists, function(nodeList) { nodeLists.unregister(nodeList); }); } }, nodeMap: nodeMap }; return nodeLists; })(__m2, __m25); // ## view/live/live.js var __m27 = (function(can, elements, view, nodeLists) { // ## live.js // The live module provides live binding for computes // and can.List. // Currently, it's API is designed for `can/view/render`, but // it could easily be used for other purposes. // ### Helper methods // #### setup // `setup(HTMLElement, bind(data), unbind(data)) -> data` // Calls bind right away, but will call unbind // if the element is "destroyed" (removed from the DOM). var setup = function(el, bind, unbind) { // Removing an element can call teardown which // unregister the nodeList which calls teardown var tornDown = false, teardown = function() { if (!tornDown) { tornDown = true; unbind(data); can.unbind.call(el, 'removed', teardown); } return true; }, data = { teardownCheck: function(parent) { return parent ? false : teardown(); } }; can.bind.call(el, 'removed', teardown); bind(data); return data; }, // #### listen // Calls setup, but presets bind and unbind to // operate on a compute listen = function(el, compute, change) { return setup(el, function() { compute.bind('change', change); }, function(data) { compute.unbind('change', change); if (data.nodeList) { nodeLists.unregister(data.nodeList); } }); }, // #### getAttributeParts // Breaks up a string like foo='bar' into ["foo","'bar'""] getAttributeParts = function(newVal) { return (newVal || '') .replace(/['"]/g, '') .split('='); }, splice = [].splice; var live = { list: function(el, compute, render, context, parentNode) { // A nodeList of all elements this live-list manages. // This is here so that if this live list is within another section // that section is able to remove the items in this list. var masterNodeList = [el], // A mapping of the index of an item to an array // of elements that represent the item. // Each array is registered so child or parent // live structures can update the elements. itemIndexToNodeListsMap = [], // A mapping of items to their indicies' indexMap = [], // Called when items are added to the list. add = function(ev, items, index) { // Collect new html and mappings var frag = document.createDocumentFragment(), newNodeLists = [], newIndicies = []; // For each new item, can.each(items, function(item, key) { var itemIndex = can.compute(key + index), // get its string content itemHTML = render.call(context, item, itemIndex), // and convert it into elements. itemFrag = can.view.fragment(itemHTML); // Add those elements to the mappings. newNodeLists.push(nodeLists.register(can.makeArray(itemFrag.childNodes), undefined, masterNodeList)); // Hookup the fragment (which sets up child live-bindings) and // add it to the collection of all added elements. frag.appendChild(can.view.hookup(itemFrag)); newIndicies.push(itemIndex); }); // Check if we are adding items at the end if (!itemIndexToNodeListsMap[index]) { elements.after(index === 0 ? [text] : itemIndexToNodeListsMap[index - 1], frag); } else { // Add elements before the next index's first element. var el = itemIndexToNodeListsMap[index][0]; can.insertBefore(el.parentNode, frag, el); } splice.apply(itemIndexToNodeListsMap, [ index, 0 ].concat(newNodeLists)); // update indices after insert point splice.apply(indexMap, [ index, 0 ].concat(newIndicies)); for (var i = index + newIndicies.length, len = indexMap.length; i < len; i++) { indexMap[i](i); } }, // Called when items are removed or when the bindings are torn down. remove = function(ev, items, index, duringTeardown) { // If this is because an element was removed, we should // check to make sure the live elements are still in the page. // If we did this during a teardown, it would cause an infinite loop. if (!duringTeardown && data.teardownCheck(text.parentNode)) { return; } var removedMappings = itemIndexToNodeListsMap.splice(index, items.length), itemsToRemove = []; can.each(removedMappings, function(nodeList) { // add items that we will remove all at once [].push.apply(itemsToRemove, nodeList); // Update any parent lists to remove these items nodeLists.update(nodeList, []); // unregister the list nodeLists.unregister(nodeList); }); // update indices after remove point indexMap.splice(index, items.length); for (var i = index, len = indexMap.length; i < len; i++) { indexMap[i](i); } can.remove(can.$(itemsToRemove)); }, text = document.createTextNode(''), // The current list. list, // Called when the list is replaced with a new list or the binding is torn-down. teardownList = function() { // there might be no list right away, and the list might be a plain // array if (list && list.unbind) { list.unbind('add', add) .unbind('remove', remove); } // use remove to clean stuff up for us remove({}, { length: itemIndexToNodeListsMap.length }, 0, true); }, // Called when the list is replaced or setup. updateList = function(ev, newList, oldList) { teardownList(); // make an empty list if the compute returns null or undefined list = newList || []; // list might be a plain array if (list.bind) { list.bind('add', add) .bind('remove', remove); } add({}, list, 0); }; parentNode = elements.getParentNode(el, parentNode); // Setup binding and teardown to add and remove events var data = setup(parentNode, function() { if (can.isFunction(compute)) { compute.bind('change', updateList); } }, function() { if (can.isFunction(compute)) { compute.unbind('change', updateList); } teardownList(); }); live.replace(masterNodeList, text, data.teardownCheck); // run the list setup updateList({}, can.isFunction(compute) ? compute() : compute); }, html: function(el, compute, parentNode) { var data; parentNode = elements.getParentNode(el, parentNode); data = listen(parentNode, compute, function(ev, newVal, oldVal) { // TODO: remove teardownCheck in 2.1 var attached = nodes[0].parentNode; // update the nodes in the DOM with the new rendered value if (attached) { makeAndPut(newVal); } data.teardownCheck(nodes[0].parentNode); }); var nodes = [el], makeAndPut = function(val) { var frag = can.view.fragment('' + val), oldNodes = can.makeArray(nodes); // We need to mark each node as belonging to the node list. nodeLists.update(nodes, frag.childNodes); frag = can.view.hookup(frag, parentNode); elements.replace(oldNodes, frag); }; data.nodeList = nodes; // register the span so nodeLists knows the parentNodeList nodeLists.register(nodes, data.teardownCheck); makeAndPut(compute()); }, replace: function(nodes, val, teardown) { var oldNodes = nodes.slice(0), frag; nodeLists.register(nodes, teardown); if (typeof val === 'string') { frag = can.view.fragment(val); } else if (val.nodeType !== 11) { frag = document.createDocumentFragment(); frag.appendChild(val); } else { frag = val; } // We need to mark each node as belonging to the node list. nodeLists.update(nodes, frag.childNodes); if (typeof val === 'string') { // if it was a string, check for hookups frag = can.view.hookup(frag, nodes[0].parentNode); } elements.replace(oldNodes, frag); return nodes; }, text: function(el, compute, parentNode) { var parent = elements.getParentNode(el, parentNode); // setup listening right away so we don't have to re-calculate value var data = listen(parent, compute, function(ev, newVal, oldVal) { // Sometimes this is 'unknown' in IE and will throw an exception if it is if (typeof node.nodeValue !== 'unknown') { node.nodeValue = '' + newVal; } // TODO: remove in 2.1 data.teardownCheck(node.parentNode); }), // The text node that will be updated node = document.createTextNode(compute()); // Replace the placeholder with the live node and do the nodeLists thing. // Add that node to nodeList so we can remove it when the parent element is removed from the page data.nodeList = live.replace([el], node, data.teardownCheck); }, attributes: function(el, compute, currentValue) { var setAttrs = function(newVal) { var parts = getAttributeParts(newVal), newAttrName = parts.shift(); // Remove if we have a change and used to have an `attrName`. if (newAttrName !== attrName && attrName) { elements.removeAttr(el, attrName); } // Set if we have a new `attrName`. if (newAttrName) { elements.setAttr(el, newAttrName, parts.join('=')); attrName = newAttrName; } }; listen(el, compute, function(ev, newVal) { setAttrs(newVal); }); // current value has been set if (arguments.length >= 3) { var attrName = getAttributeParts(currentValue)[0]; } else { setAttrs(compute()); } }, attributePlaceholder: '__!!__', attributeReplace: /__!!__/g, attribute: function(el, attributeName, compute) { listen(el, compute, function(ev, newVal) { elements.setAttr(el, attributeName, hook.render()); }); var wrapped = can.$(el), hooks; // Get the list of hookups or create one for this element. // Hooks is a map of attribute names to hookup `data`s. // Each hookup data has: // `render` - A `function` to render the value of the attribute. // `funcs` - A list of hookup `function`s on that attribute. // `batchNum` - The last event `batchNum`, used for performance. hooks = can.data(wrapped, 'hooks'); if (!hooks) { can.data(wrapped, 'hooks', hooks = {}); } // Get the attribute value. var attr = elements.getAttr(el, attributeName), // Split the attribute value by the template. // Only split out the first __!!__ so if we have multiple hookups in the same attribute, // they will be put in the right spot on first render parts = attr.split(live.attributePlaceholder), goodParts = [], hook; goodParts.push(parts.shift(), parts.join(live.attributePlaceholder)); // If we already had a hookup for this attribute... if (hooks[attributeName]) { // Just add to that attribute's list of `function`s. hooks[attributeName].computes.push(compute); } else { // Create the hookup data. hooks[attributeName] = { render: function() { var i = 0, // attr doesn't have a value in IE newAttr = attr ? attr.replace(live.attributeReplace, function() { return elements.contentText(hook.computes[i++]()); }) : elements.contentText(hook.computes[i++]()); return newAttr; }, computes: [compute], batchNum: undefined }; } // Save the hook for slightly faster performance. hook = hooks[attributeName]; // Insert the value in parts. goodParts.splice(1, 0, compute()); // Set the attribute. elements.setAttr(el, attributeName, goodParts.join('')); }, specialAttribute: function(el, attributeName, compute) { listen(el, compute, function(ev, newVal) { elements.setAttr(el, attributeName, getValue(newVal)); }); elements.setAttr(el, attributeName, getValue(compute())); } }; var newLine = /(\r|\n)+/g; var getValue = function(val) { var regexp = /^["'].*["']$/; val = val.replace(elements.attrReg, '') .replace(newLine, ''); // check if starts and ends with " or ' return regexp.test(val) ? val.substr(1, val.length - 2) : val; }; can.view.live = live; can.view.nodeLists = nodeLists; can.view.elements = elements; return live; })(__m2, __m25, __m23, __m28); // ## view/render.js var __m26 = (function(can, elements, live) { var pendingHookups = [], tagChildren = function(tagName) { var newTag = elements.tagMap[tagName] || "span"; if (newTag === "span") { //innerHTML in IE doesn't honor leading whitespace after empty elements return "@@!!@@"; } return "<" + newTag + ">" + tagChildren(newTag) + "</" + newTag + ">"; }, contentText = function(input, tag) { // If it's a string, return. if (typeof input === 'string') { return input; } // If has no value, return an empty string. if (!input && input !== 0) { return ''; } // If it's an object, and it has a hookup method. var hook = (input.hookup && // Make a function call the hookup method. function(el, id) { input.hookup.call(input, el, id); }) || // Or if it's a `function`, just use the input. (typeof input === 'function' && input); // Finally, if there is a `function` to hookup on some dom, // add it to pending hookups. if (hook) { if (tag) { return "<" + tag + " " + can.view.hook(hook) + "></" + tag + ">"; } else { pendingHookups.push(hook); } return ''; } // Finally, if all else is `false`, `toString()` it. return '' + input; }, // Returns escaped/sanatized content for anything other than a live-binding contentEscape = function(txt, tag) { return (typeof txt === 'string' || typeof txt === 'number') ? can.esc(txt) : contentText(txt, tag); }, // A flag to indicate if .txt was called within a live section within an element like the {{name}} // within `<div {{#person}}{{name}}{{/person}}/>`. withinTemplatedSectionWithinAnElement = false, emptyHandler = function() {}; var lastHookups; can.extend(can.view, { live: live, // called in text to make a temporary // can.view.lists function that can be called with // the list to iterate over and the template // used to produce the content within the list setupLists: function() { var old = can.view.lists, data; can.view.lists = function(list, renderer) { data = { list: list, renderer: renderer }; return Math.random(); }; // sets back to the old data return function() { can.view.lists = old; return data; }; }, pending: function(data) { // TODO, make this only run for the right tagName var hooks = can.view.getHooks(); return can.view.hook(function(el) { can.each(hooks, function(fn) { fn(el); }); can.view.Scanner.hookupAttributes(data, el); }); }, getHooks: function() { var hooks = pendingHookups.slice(0); lastHookups = hooks; pendingHookups = []; return hooks; }, onlytxt: function(self, func) { return contentEscape(func.call(self)); }, txt: function(escape, tagName, status, self, func) { // the temporary tag needed for any live setup var tag = (elements.tagMap[tagName] || "span"), // should live-binding be setup setupLiveBinding = false, // the compute's value compute, value, unbind, listData, attributeName; // Are we currently within a live section within an element like the {{name}} // within `<div {{#person}}{{name}}{{/person}}/>`. if (withinTemplatedSectionWithinAnElement) { value = func.call(self); } else { // If this magic tag is within an attribute or an html element, // set the flag to true so we avoid trying to live bind // anything that func might be setup. // TODO: the scanner should be able to set this up. if (typeof status === "string" || status === 1) { withinTemplatedSectionWithinAnElement = true; } // Sets up a listener so we know any can.view.lists called // when func is called var listTeardown = can.view.setupLists(); unbind = function() { compute.unbind("change", emptyHandler); }; // Create a compute that calls func and looks for dependencies. // By passing `false`, this compute can not be a dependency of other // computes. This is because live-bits are nested, but // handle their own updating. For example: // {{#if items.length}}{{#items}}{{.}}{{/items}}{{/if}} // We do not want `{{#if items.length}}` changing the DOM if // `{{#items}}` text changes. compute = can.compute(func, self, false); // Bind to get and temporarily cache the value of the compute. compute.bind("change", emptyHandler); // Call the "wrapping" function and get the binding information listData = listTeardown(); // Get the value of the compute value = compute(); // Let people know we are no longer within an element. withinTemplatedSectionWithinAnElement = false; // If we should setup live-binding. setupLiveBinding = compute.hasDependencies; } if (listData) { if (unbind) { unbind(); } return "<" + tag + can.view.hook(function(el, parentNode) { live.list(el, listData.list, listData.renderer, self, parentNode); }) + "></" + tag + ">"; } // If we had no observes just return the value returned by func. if (!setupLiveBinding || typeof value === "function") { if (unbind) { unbind(); } return ((withinTemplatedSectionWithinAnElement || escape === 2 || !escape) ? contentText : contentEscape)(value, status === 0 && tag); } // the property (instead of innerHTML elements) to adjust. For // example options should use textContent var contentProp = elements.tagToContentPropMap[tagName]; // The magic tag is outside or between tags. if (status === 0 && !contentProp) { // Return an element tag with a hookup in place of the content return "<" + tag + can.view.hook( // if value is an object, it's likely something returned by .safeString escape && typeof value !== "object" ? // If we are escaping, replace the parentNode with // a text node who's value is `func`'s return value. function(el, parentNode) { live.text(el, compute, parentNode); unbind(); } : // If we are not escaping, replace the parentNode with a // documentFragment created as with `func`'s return value. function(el, parentNode) { live.html(el, compute, parentNode); unbind(); //children have to be properly nested HTML for buildFragment to work properly }) + ">" + tagChildren(tag) + "</" + tag + ">"; // In a tag, but not in an attribute } else if (status === 1) { // remember the old attr name pendingHookups.push(function(el) { live.attributes(el, compute, compute()); unbind(); }); return compute(); } else if (escape === 2) { // In a special attribute like src or style attributeName = status; pendingHookups.push(function(el) { live.specialAttribute(el, attributeName, compute); unbind(); }); return compute(); } else { // In an attribute... attributeName = status === 0 ? contentProp : status; // if the magic tag is inside the element, like `<option><% TAG %></option>`, // we add this hookup to the last element (ex: `option`'s) hookups. // Otherwise, the magic tag is in an attribute, just add to the current element's // hookups. (status === 0 ? lastHookups : pendingHookups) .push(function(el) { live.attribute(el, attributeName, compute); unbind(); }); return live.attributePlaceholder; } } }); return can; })(__m23, __m25, __m27, __m14); // ## view/mustache/mustache.js var __m21 = (function(can) { // # mustache.js // `can.Mustache`: The Mustache templating engine. // See the [Transformation](#section-29) section within *Scanning Helpers* for a detailed explanation // of the runtime render code design. The majority of the Mustache engine implementation // occurs within the *Transformation* scanning helper. // ## Initialization // Define the view extension. can.view.ext = ".mustache"; // ### Setup internal helper variables and functions. // An alias for the context variable used for tracking a stack of contexts. // This is also used for passing to helper functions to maintain proper context. var SCOPE = 'scope', // An alias for the variable used for the hash object that can be passed // to helpers via `options.hash`. HASH = '___h4sh', // An alias for the most used context stacking call. CONTEXT_OBJ = '{scope:' + SCOPE + ',options:options}', // argument names used to start the function (used by scanner and steal) ARG_NAMES = SCOPE + ",options", // matches arguments inside a {{ }} argumentsRegExp = /((([^\s]+?=)?('.*?'|".*?"))|.*?)\s/g, // matches a literal number, string, null or regexp literalNumberStringBooleanRegExp = /^(('.*?'|".*?"|[0-9]+\.?[0-9]*|true|false|null|undefined)|((.+?)=(('.*?'|".*?"|[0-9]+\.?[0-9]*|true|false)|(.+))))$/, // returns an object literal that we can use to look up a value in the current scope makeLookupLiteral = function(type) { return '{get:"' + type.replace(/"/g, '\\"') + '"}'; }, // returns if the object is a lookup isLookup = function(obj) { return obj && typeof obj.get === "string"; }, isObserveLike = function(obj) { return obj instanceof can.Map || (obj && !! obj._get); }, isArrayLike = function(obj) { return obj && obj.splice && typeof obj.length === 'number'; }, // used to make sure .fn and .inverse are always called with a Scope like object makeConvertToScopes = function(orignal, scope, options) { return function(updatedScope, updatedOptions) { if (updatedScope !== undefined && !(updatedScope instanceof can.view.Scope)) { updatedScope = scope.add(updatedScope); } if (updatedOptions !== undefined && !(updatedOptions instanceof OptionsScope)) { updatedOptions = options.add(updatedOptions); } return orignal(updatedScope, updatedOptions || options); }; }; // ## Mustache var Mustache = function(options, helpers) { // Support calling Mustache without the constructor. // This returns a function that renders the template. if (this.constructor !== Mustache) { var mustache = new Mustache(options); return function(data, options) { return mustache.render(data, options); }; } // If we get a `function` directly, it probably is coming from // a `steal`-packaged view. if (typeof options === "function") { this.template = { fn: options }; return; } // Set options on self. can.extend(this, options); this.template = this.scanner.scan(this.text, this.name); }; // Put Mustache on the `can` object. can.Mustache = window.Mustache = Mustache; Mustache.prototype. render = function(data, options) { if (!(data instanceof can.view.Scope)) { data = new can.view.Scope(data || {}); } if (!(options instanceof OptionsScope)) { options = new OptionsScope(options || {}); } options = options || {}; return this.template.fn.call(data, data, options); }; can.extend(Mustache.prototype, { // Share a singleton scanner for parsing templates. scanner: new can.view.Scanner({ // A hash of strings for the scanner to inject at certain points. text: { // This is the logic to inject at the beginning of a rendered template. // This includes initializing the `context` stack. start: "", //"var "+SCOPE+"= this instanceof can.view.Scope? this : new can.view.Scope(this);\n", scope: SCOPE, options: ",options: options", argNames: ARG_NAMES }, // An ordered token registry for the scanner. // This needs to be ordered by priority to prevent token parsing errors. // Each token follows the following structure: // [ // // Which key in the token map to match. // "tokenMapName", // // A simple token to match, like "{{". // "token", // // Optional. A complex (regexp) token to match that // // overrides the simple token. // "[\\s\\t]*{{", // // Optional. A function that executes advanced // // manipulation of the matched content. This is // // rarely used. // function(content){ // return content; // } // ] tokens: [ // Return unescaped ["returnLeft", "{{{", "{{[{&]"], // Full line comments ["commentFull", "{{!}}", "^[\\s\\t]*{{!.+?}}\\n"], // Inline comments ["commentLeft", "{{!", "(\\n[\\s\\t]*{{!|{{!)"], // Full line escapes // This is used for detecting lines with only whitespace and an escaped tag ["escapeFull", "{{}}", "(^[\\s\\t]*{{[#/^][^}]+?}}\\n|\\n[\\s\\t]*{{[#/^][^}]+?}}\\n|\\n[\\s\\t]*{{[#/^][^}]+?}}$)", function(content) { return { before: /^\n.+?\n$/.test(content) ? '\n' : '', content: content.match(/\{\{(.+?)\}\}/)[1] || '' }; } ], // Return escaped ["escapeLeft", "{{"], // Close return unescaped ["returnRight", "}}}"], // Close tag ["right", "}}"] ], // ## Scanning Helpers // This is an array of helpers that transform content that is within escaped tags like `{{token}}`. These helpers are solely for the scanning phase; they are unrelated to Mustache/Handlebars helpers which execute at render time. Each helper has a definition like the following: // { // // The content pattern to match in order to execute. // // Only the first matching helper is executed. // name: /pattern to match/, // // The function to transform the content with. // // @param {String} content The content to transform. // // @param {Object} cmd Scanner helper data. // // { // // insert: "insert command", // // tagName: "div", // // status: 0 // // } // fn: function(content, cmd) { // return 'for text injection' || // { raw: 'to bypass text injection' }; // } // } helpers: [ // ### Partials // Partials begin with a greater than sign, like {{> box}}. // Partials are rendered at runtime (as opposed to compile time), // so recursive partials are possible. Just avoid infinite loops. // For example, this template and partial: // base.mustache: // <h2>Names</h2> // {{#names}} // {{> user}} // {{/names}} // user.mustache: // <strong>{{name}}</strong> { name: /^>[\s]*\w*/, fn: function(content, cmd) { // Get the template name and call back into the render method, // passing the name and the current context. var templateName = can.trim(content.replace(/^>\s?/, '')) .replace(/["|']/g, ""); return "can.Mustache.renderPartial('" + templateName + "'," + ARG_NAMES + ")"; } }, // ### Data Hookup // This will attach the data property of `this` to the element // its found on using the first argument as the data attribute // key. // For example: // <li id="nameli" {{ data 'name' }}></li> // then later you can access it like: // can.$('#nameli').data('name'); { name: /^\s*data\s/, fn: function(content, cmd) { var attr = content.match(/["|'](.*)["|']/)[1]; // return a function which calls `can.data` on the element // with the attribute name with the current context. return "can.proxy(function(__){" + // "var context = this[this.length-1];" + // "context = context." + STACKED + " ? context[context.length-2] : context; console.warn(this, context);" + "can.data(can.$(__),'" + attr + "', this.attr('.')); }, " + SCOPE + ")"; } }, { name: /\s*\(([\$\w]+)\)\s*->([^\n]*)/, fn: function(content) { var quickFunc = /\s*\(([\$\w]+)\)\s*->([^\n]*)/, parts = content.match(quickFunc); //find return "can.proxy(function(__){var " + parts[1] + "=can.$(__);with(" + SCOPE + ".attr('.')){" + parts[2] + "}}, this);"; } }, // ### Transformation (default) // This transforms all content to its interpolated equivalent, // including calls to the corresponding helpers as applicable. // This outputs the render code for almost all cases. // #### Definitions // * `context` - This is the object that the current rendering context operates within. // Each nested template adds a new `context` to the context stack. // * `stack` - Mustache supports nested sections, // each of which add their own context to a stack of contexts. // Whenever a token gets interpolated, it will check for a match against the // last context in the stack, then iterate through the rest of the stack checking for matches. // The first match is the one that gets returned. // * `Mustache.txt` - This serializes a collection of logic, optionally contained within a section. // If this is a simple interpolation, only the interpolation lookup will be passed. // If this is a section, then an `options` object populated by the truthy (`options.fn`) and // falsey (`options.inverse`) encapsulated functions will also be passed. This section handling // exists to support the runtime context nesting that Mustache supports. // * `Mustache.get` - This resolves an interpolation reference given a stack of contexts. // * `options` - An object containing methods for executing the inner contents of sections or helpers. // `options.fn` - Contains the inner template logic for a truthy section. // `options.inverse` - Contains the inner template logic for a falsey section. // `options.hash` - Contains the merged hash object argument for custom helpers. // #### Design // This covers the design of the render code that the transformation helper generates. // ##### Pseudocode // A detailed explanation is provided in the following sections, but here is some brief pseudocode // that gives a high level overview of what the generated render code does (with a template similar to // `"{{#a}}{{b.c.d.e.name}}{{/a}}" == "Phil"`). // *Initialize the render code.* // view = [] // context = [] // stack = fn { context.concat([this]) } // *Render the root section.* // view.push( "string" ) // view.push( can.view.txt( // *Render the nested section with `can.Mustache.txt`.* // txt( // *Add the current context to the stack.* // stack(), // *Flag this for truthy section mode.* // "#", // *Interpolate and check the `a` variable for truthyness using the stack with `can.Mustache.get`.* // get( "a", stack() ), // *Include the nested section's inner logic. // The stack argument is usually the parent section's copy of the stack, // but it can be an override context that was passed by a custom helper. // Sections can nest `0..n` times -- **NESTCEPTION**.* // { fn: fn(stack) { // *Render the nested section (everything between the `{{#a}}` and `{{/a}}` tokens).* // view = [] // view.push( "string" ) // view.push( // *Add the current context to the stack.* // stack(), // *Flag this as interpolation-only mode.* // null, // *Interpolate the `b.c.d.e.name` variable using the stack.* // get( "b.c.d.e.name", stack() ), // ) // view.push( "string" ) // *Return the result for the nested section.* // return view.join() // }} // ) // )) // view.push( "string" ) // *Return the result for the root section, which includes all nested sections.* // return view.join() // ##### Initialization // Each rendered template is started with the following initialization code: // var ___v1ew = []; // var ___c0nt3xt = []; // ___c0nt3xt.__sc0pe = true; // var __sc0pe = function(context, self) { // var s; // if (arguments.length == 1 && context) { // s = !context.__sc0pe ? [context] : context; // } else { // s = context && context.__sc0pe // ? context.concat([self]) // : __sc0pe(context).concat([self]); // } // return (s.__sc0pe = true) && s; // }; // The `___v1ew` is the the array used to serialize the view. // The `___c0nt3xt` is a stacking array of contexts that slices and expands with each nested section. // The `__sc0pe` function is used to more easily update the context stack in certain situations. // Usually, the stack function simply adds a new context (`self`/`this`) to a context stack. // However, custom helpers will occasionally pass override contexts that need their own context stack. // ##### Sections // Each section, `{{#section}} content {{/section}}`, within a Mustache template generates a section // context in the resulting render code. The template itself is treated like a root section, with the // same execution logic as any others. Each section can have `0..n` nested sections within it. // Here's an example of a template without any descendent sections. // Given the template: `"{{a.b.c.d.e.name}}" == "Phil"` // Would output the following render code: // ___v1ew.push("\""); // ___v1ew.push(can.view.txt(1, '', 0, this, function() { // return can.Mustache.txt(__sc0pe(___c0nt3xt, this), null, // can.Mustache.get("a.b.c.d.e.name", // __sc0pe(___c0nt3xt, this)) // ); // })); // ___v1ew.push("\" == \"Phil\""); // The simple strings will get appended to the view. Any interpolated references (like `{{a.b.c.d.e.name}}`) // will be pushed onto the view via `can.view.txt` in order to support live binding. // The function passed to `can.view.txt` will call `can.Mustache.txt`, which serializes the object data by doing // a context lookup with `can.Mustache.get`. // `can.Mustache.txt`'s first argument is a copy of the context stack with the local context `this` added to it. // This stack will grow larger as sections nest. // The second argument is for the section type. This will be `"#"` for truthy sections, `"^"` for falsey, // or `null` if it is an interpolation instead of a section. // The third argument is the interpolated value retrieved with `can.Mustache.get`, which will perform the // context lookup and return the approriate string or object. // Any additional arguments, if they exist, are used for passing arguments to custom helpers. // For nested sections, the last argument is an `options` object that contains the nested section's logic. // Here's an example of a template with a single nested section. // Given the template: `"{{#a}}{{b.c.d.e.name}}{{/a}}" == "Phil"` // Would output the following render code: // ___v1ew.push("\""); // ___v1ew.push(can.view.txt(0, '', 0, this, function() { // return can.Mustache.txt(__sc0pe(___c0nt3xt, this), "#", // can.Mustache.get("a", __sc0pe(___c0nt3xt, this)), // [{ // _: function() { // return ___v1ew.join(""); // } // }, { // fn: function(___c0nt3xt) { // var ___v1ew = []; // ___v1ew.push(can.view.txt(1, '', 0, this, // function() { // return can.Mustache.txt( // __sc0pe(___c0nt3xt, this), // null, // can.Mustache.get("b.c.d.e.name", // __sc0pe(___c0nt3xt, this)) // ); // } // )); // return ___v1ew.join(""); // } // }] // ) // })); // ___v1ew.push("\" == \"Phil\""); // This is specified as a truthy section via the `"#"` argument. The last argument includes an array of helper methods used with `options`. // These act similarly to custom helpers: `options.fn` will be called for truthy sections, `options.inverse` will be called for falsey sections. // The `options._` function only exists as a dummy function to make generating the section nesting easier (a section may have a `fn`, `inverse`, // or both, but there isn't any way to determine that at compilation time). // Within the `fn` function is the section's render context, which in this case will render anything between the `{{#a}}` and `{{/a}}` tokens. // This function has `___c0nt3xt` as an argument because custom helpers can pass their own override contexts. For any case where custom helpers // aren't used, `___c0nt3xt` will be equivalent to the `__sc0pe(___c0nt3xt, this)` stack created by its parent section. The `inverse` function // works similarly, except that it is added when `{{^a}}` and `{{else}}` are used. `var ___v1ew = []` is specified in `fn` and `inverse` to // ensure that live binding in nested sections works properly. // All of these nested sections will combine to return a compiled string that functions similar to EJS in its uses of `can.view.txt`. // #### Implementation { name: /^.*$/, fn: function(content, cmd) { var mode = false, result = []; // Trim the content so we don't have any trailing whitespace. content = can.trim(content); // Determine what the active mode is. // * `#` - Truthy section // * `^` - Falsey section // * `/` - Close the prior section // * `else` - Inverted section (only exists within a truthy/falsey section) if (content.length && (mode = content.match(/^([#^/]|else$)/))) { mode = mode[0]; switch (mode) { // Open a new section. case '#': case '^': if (cmd.specialAttribute) { result.push(cmd.insert + 'can.view.onlytxt(this,function(){ return '); } else { result.push(cmd.insert + 'can.view.txt(0,\'' + cmd.tagName + '\',' + cmd.status + ',this,function(){ return '); } break; // Close the prior section. case '/': return { raw: 'return ___v1ew.join("");}}])}));' }; } // Trim the mode off of the content. content = content.substring(1); } // `else` helpers are special and should be skipped since they don't // have any logic aside from kicking off an `inverse` function. if (mode !== 'else') { var args = [], i = 0, m; // Start the content render block. result.push('can.Mustache.txt(\n' + CONTEXT_OBJ + ',\n' + (mode ? '"' + mode + '"' : 'null') + ','); // Parse the helper arguments. // This needs uses this method instead of a split(/\s/) so that // strings with spaces can be correctly parsed. var hashes = []; (can.trim(content) + ' ') .replace(argumentsRegExp, function(whole, arg) { // Check for special helper arguments (string/number/boolean/hashes). if (i && (m = arg.match(literalNumberStringBooleanRegExp))) { // Found a native type like string/number/boolean. if (m[2]) { args.push(m[0]); } // Found a hash object. else { // Addd to the hash object. hashes.push(m[4] + ":" + (m[6] ? m[6] : makeLookupLiteral(m[5]))); } } // Otherwise output a normal interpolation reference. else { args.push(makeLookupLiteral(arg)); } i++; }); result.push(args.join(",")); if (hashes.length) { result.push(",{" + HASH + ":{" + hashes.join(",") + "}}"); } } // Create an option object for sections of code. if (mode && mode !== 'else') { result.push(',[\n\n'); } switch (mode) { // Truthy section case '#': result.push('{fn:function(' + ARG_NAMES + '){var ___v1ew = [];'); break; // If/else section // Falsey section case 'else': result.push('return ___v1ew.join("");}},\n{inverse:function(' + ARG_NAMES + '){\nvar ___v1ew = [];'); break; case '^': result.push('{inverse:function(' + ARG_NAMES + '){\nvar ___v1ew = [];'); break; // Not a section, no mode default: result.push(')'); break; } // Return a raw result if there was a section, otherwise return the default string. result = result.join(''); return mode ? { raw: result } : result; } } ] }) }); // Add in default scanner helpers first. // We could probably do this differently if we didn't 'break' on every match. var helpers = can.view.Scanner.prototype.helpers; for (var i = 0; i < helpers.length; i++) { Mustache.prototype.scanner.helpers.unshift(helpers[i]); } Mustache.txt = function(scopeAndOptions, mode, name) { var scope = scopeAndOptions.scope, options = scopeAndOptions.options, args = [], helperOptions = { fn: function() {}, inverse: function() {} }, hash, context = scope.attr("."), getHelper = true; // An array of arguments to check for truthyness when evaluating sections. var validArgs, // Whether the arguments meet the condition of the section. valid = true, result = [], helper, argIsObserve, arg; // convert lookup values to actual values in name, arguments, and hash for (var i = 3; i < arguments.length; i++) { arg = arguments[i]; if (mode && can.isArray(arg)) { // merge into options helperOptions = can.extend.apply(can, [helperOptions].concat(arg)); } else if (arg && arg[HASH]) { hash = arg[HASH]; // get values on hash for (var prop in hash) { if (isLookup(hash[prop])) { hash[prop] = Mustache.get(hash[prop].get, scopeAndOptions); } } } else if (arg && isLookup(arg)) { args.push(Mustache.get(arg.get, scopeAndOptions, false, true)); } else { args.push(arg); } } if (isLookup(name)) { var get = name.get; name = Mustache.get(name.get, scopeAndOptions, args.length, false); // Base whether or not we will get a helper on whether or not the original // name.get and Mustache.get resolve to the same thing. Saves us from running // into issues like {{text}} / {text: 'with'} getHelper = (get === name); } // overwrite fn and inverse to always convert to scopes helperOptions.fn = makeConvertToScopes(helperOptions.fn, scope, options); helperOptions.inverse = makeConvertToScopes(helperOptions.inverse, scope, options); // Check for a registered helper or a helper-like function. if (helper = (getHelper && (typeof name === "string" && Mustache.getHelper(name, options)) || (can.isFunction(name) && !name.isComputed && { fn: name }))) { // Add additional data to be used by helper functions can.extend(helperOptions, { context: context, scope: scope, contexts: scope, hash: hash }); args.push(helperOptions); // Call the helper. return helper.fn.apply(context, args) || ''; } if (can.isFunction(name)) { if (name.isComputed) { name = name(); } } validArgs = args.length ? args : [name]; // Validate the arguments based on the section mode. if (mode) { for (i = 0; i < validArgs.length; i++) { arg = validArgs[i]; argIsObserve = typeof arg !== 'undefined' && isObserveLike(arg); // Array-like objects are falsey if their length = 0. if (isArrayLike(arg)) { // Use .attr to trigger binding on empty lists returned from function if (mode === '#') { valid = valid && !! (argIsObserve ? arg.attr('length') : arg.length); } else if (mode === '^') { valid = valid && !(argIsObserve ? arg.attr('length') : arg.length); } } // Otherwise just check if it is truthy or not. else { valid = mode === '#' ? valid && !! arg : mode === '^' ? valid && !arg : valid; } } } // Otherwise interpolate like normal. if (valid) { switch (mode) { // Truthy section. case '#': // Iterate over arrays if (isArrayLike(name)) { var isObserveList = isObserveLike(name); // Add the reference to the list in the contexts. for (i = 0; i < name.length; i++) { result.push(helperOptions.fn(name[i])); // Ensure that live update works on observable lists if (isObserveList) { name.attr('' + i); } } return result.join(''); } // Normal case. else { return helperOptions.fn(name || {}) || ''; } break; // Falsey section. case '^': return helperOptions.inverse(name || {}) || ''; default: // Add + '' to convert things like numbers to strings. // This can cause issues if you are trying to // eval on the length but this is the more // common case. return '' + (name != null ? name : ''); } } return ''; }; Mustache.get = function(key, scopeAndOptions, isHelper, isArgument) { // Cache a reference to the current context and options, we will use them a bunch. var context = scopeAndOptions.scope.attr('.'), options = scopeAndOptions.options || {}; // If key is called as a helper, if (isHelper) { // try to find a registered helper. if (Mustache.getHelper(key, options)) { return key; } // Support helper-like functions as anonymous helpers. // Check if there is a method directly in the "top" context. if (scopeAndOptions.scope && can.isFunction(context[key])) { return context[key]; } } // Get a compute (and some helper data) that represents key's value in the current scope var computeData = scopeAndOptions.scope.computeData(key, { isArgument: isArgument, args: [context, scopeAndOptions.scope] }), compute = computeData.compute; // Bind on the compute to cache its value. We will unbind in a timeout later. can.compute.temporarilyBind(compute); // computeData gives us an initial value var initialValue = computeData.initialValue; // Use helper over the found value if the found value isn't in the current context if ((initialValue === undefined || computeData.scope !== scopeAndOptions.scope) && Mustache.getHelper(key, options)) { return key; } // If there are no dependencies, just return the value. if (!compute.hasDependencies) { return initialValue; } else { return compute; } }; Mustache.resolve = function(value) { if (isObserveLike(value) && isArrayLike(value) && value.attr('length')) { return value; } else if (can.isFunction(value)) { return value(); } else { return value; } }; var OptionsScope = can.view.Scope.extend({ init: function(data, parent) { if (!data.helpers && !data.partials) { data = { helpers: data }; } can.view.Scope.prototype.init.apply(this, arguments); } }); // ## Helpers // Helpers are functions that can be called from within a template. // These helpers differ from the scanner helpers in that they execute // at runtime instead of during compilation. // Custom helpers can be added via `can.Mustache.registerHelper`, // but there are also some built-in helpers included by default. // Most of the built-in helpers are little more than aliases to actions // that the base version of Mustache simply implies based on the // passed in object. // Built-in helpers: // * `data` - `data` is a special helper that is implemented via scanning helpers. // It hooks up the active element to the active data object: `<div {{data "key"}} />` // * `if` - Renders a truthy section: `{{#if var}} render {{/if}}` // * `unless` - Renders a falsey section: `{{#unless var}} render {{/unless}}` // * `each` - Renders an array: `{{#each array}} render {{this}} {{/each}}` // * `with` - Opens a context section: `{{#with var}} render {{/with}}` Mustache._helpers = {}; Mustache.registerHelper = function(name, fn) { this._helpers[name] = { name: name, fn: fn }; }; Mustache.getHelper = function(name, options) { var helper = options.attr("helpers." + name); return helper ? { fn: helper } : this._helpers[name]; }; Mustache.render = function(partial, scope, options) { // TOOD: clean up the following // If there is a "partial" property and there is not // an already-cached partial, we use the value of the // property to look up the partial // if this partial is not cached ... if (!can.view.cached[partial]) { // we don't want to bind to changes so clear and restore reading var reads = can.__clearReading && can.__clearReading(); if (scope.attr('partial')) { partial = scope.attr('partial'); } if (can.__setReading) { can.__setReading(reads); } } // Call into `can.view.render` passing the // partial and scope. return can.view.render(partial, scope); }; Mustache.safeString = function(str) { return { toString: function() { return str; } }; }; Mustache.renderPartial = function(partialName, scope, options) { var partial = options.attr("partials." + partialName); if (partial) { return partial.render ? partial.render(scope, options) : partial(scope, options); } else { return can.Mustache.render(partialName, scope, options); } }; // The built-in Mustache helpers. can.each({ // Implements the `if` built-in helper. 'if': function(expr, options) { var value; // if it's a function, wrap its value in a compute // that will only change values from true to false if (can.isFunction(expr)) { value = can.compute.truthy(expr)(); } else { value = !! Mustache.resolve(expr); } if (value) { return options.fn(options.contexts || this); } else { return options.inverse(options.contexts || this); } }, // Implements the `unless` built-in helper. 'unless': function(expr, options) { if (!Mustache.resolve(expr)) { return options.fn(options.contexts || this); } }, // Implements the `each` built-in helper. 'each': function(expr, options) { var result = []; var keys, key, i; // Check if this is a list or a compute that resolves to a list, and setup // the incremental live-binding // First, see what we are dealing with. It's ok to read the compute // because can.view.text is only temporarily binding to what is going on here. // Calling can.view.lists prevents anything from listening on that compute. var resolved = Mustache.resolve(expr); // When resolved === undefined, the property hasn't been defined yet // Assume it is intended to be a list if (can.view.lists && (resolved instanceof can.List || (expr && expr.isComputed && resolved === undefined))) { return can.view.lists(expr, function(item, index) { return options.fn(options.scope.add({ "@index": index }) .add(item)); }); } expr = resolved; if ( !! expr && isArrayLike(expr)) { for (i = 0; i < expr.length; i++) { var index = function() { return i; }; result.push(options.fn(options.scope.add({ "@index": index }) .add(expr[i]))); } return result.join(''); } else if (isObserveLike(expr)) { keys = can.Map.keys(expr); for (i = 0; i < keys.length; i++) { key = keys[i]; result.push(options.fn(options.scope.add({ "@key": key }) .add(expr[key]))); } return result.join(''); } else if (expr instanceof Object) { for (key in expr) { result.push(options.fn(options.scope.add({ "@key": key }) .add(expr[key]))); } return result.join(''); } }, // Implements the `with` built-in helper. 'with': function(expr, options) { var ctx = expr; expr = Mustache.resolve(expr); if ( !! expr) { return options.fn(ctx); } }, 'log': function(expr, options) { if (console !== undefined) { if (!options) { console.log(expr.context); } else { console.log(expr, options.context); } } } }, function(fn, name) { Mustache.registerHelper(name, fn); }); // ## Registration // Registers Mustache with can.view. can.view.register({ suffix: "mustache", contentType: "x-mustache-template", // Returns a `function` that renders the view. script: function(id, src) { return "can.Mustache(function(" + ARG_NAMES + ") { " + new Mustache({ text: src, name: id }) .template.out + " })"; }, renderer: function(id, text) { return Mustache({ text: text, name: id }); } }); return can; })(__m2, __m22, __m23, __m24, __m20, __m26); // ## view/bindings/bindings.js var __m29 = (function(can) { // IE < 8 doesn't support .hasAttribute, so feature detect it. var hasAttribute = function(el, name) { return el.hasAttribute ? el.hasAttribute(name) : el.getAttribute(name) !== null; }; can.view.Scanner.attribute("can-value", function(data, el) { var attr = el.getAttribute("can-value"), value = data.scope.computeData(attr, { args: [] }) .compute; if (el.nodeName.toLowerCase() === "input") { var trueValue, falseValue; if (el.type === "checkbox") { if (hasAttribute(el, "can-true-value")) { trueValue = data.scope.compute(el.getAttribute("can-true-value")); } else { trueValue = can.compute(true); } if (hasAttribute(el, "can-false-value")) { falseValue = data.scope.compute(el.getAttribute("can-false-value")); } else { falseValue = can.compute(false); } } if (el.type === "checkbox" || el.type === "radio") { new Checked(el, { value: value, trueValue: trueValue, falseValue: falseValue }); return; } } new Value(el, { value: value }); }); var special = { enter: function(data, el, original) { return { event: "keyup", handler: function(ev) { if (ev.keyCode === 13) { return original.call(this, ev); } } }; } }; can.view.Scanner.attribute(/can-[\w\.]+/, function(data, el) { var attributeName = data.attr, event = data.attr.substr("can-".length), handler = function(ev) { var attr = el.getAttribute(attributeName), scopeData = data.scope.read(attr, { returnObserveMethods: true, isArgument: true }); return scopeData.value.call(scopeData.parent, data.scope._context, can.$(this), ev); }; if (special[event]) { var specialData = special[event](data, el, handler); handler = specialData.handler; event = specialData.event; } can.bind.call(el, event, handler); }); var Value = can.Control.extend({ init: function() { if (this.element[0].nodeName.toUpperCase() === "SELECT") { // need to wait until end of turn ... setTimeout(can.proxy(this.set, this), 1); } else { this.set(); } }, "{value} change": "set", set: function() { //this may happen in some edgecases, esp. with selects that are not in DOM after the timeout has fired if (!this.element) { return; } var val = this.options.value(); this.element[0].value = (typeof val === 'undefined' ? '' : val); }, "change": function() { //this may happen in some edgecases, esp. with selects that are not in DOM after the timeout has fired if (!this.element) { return; } this.options.value(this.element[0].value); } }); var Checked = can.Control.extend({ init: function() { this.isCheckebox = (this.element[0].type.toLowerCase() === "checkbox"); this.check(); }, "{value} change": "check", "{trueValue} change": "check", "{falseValue} change": "check", check: function() { if (this.isCheckebox) { var value = this.options.value(), trueValue = this.options.trueValue() || true; this.element[0].checked = (value === trueValue); } else { var method = this.options.value() === this.element[0].value ? "setAttr" : "removeAttr"; can.view.elements[method](this.element[0], 'checked', true); } }, "change": function() { if (this.isCheckebox) { this.options.value(this.element[0].checked ? this.options.trueValue() : this.options.falseValue()); } else { if (this.element[0].checked) { this.options.value(this.element[0].value); } } } }); })(__m2, __m21, __m12); // ## component/component.js var __m1 = (function(can) { // ## Helpers // Attribute names to ignore for setting scope values. var ignoreAttributesRegExp = /^(dataViewId|class|id)$/i; var Component = can.Component = can.Construct.extend( // ## Static { // ### setup // When a component is extended, this sets up the component's internal constructor // functions and templates for later fast initialization. setup: function() { can.Construct.setup.apply(this, arguments); // Run the following only in constructors that extend can.Component. if (can.Component) { var self = this; // Define a control using the `events` prototype property. this.Control = can.Control.extend({ // Change lookup to first look in the scope. _lookup: function(options) { return [options.scope, options, window]; } }, // Extend `events` with a setup method that listens to changes in `scope` and // rebinds all templated event handlers. can.extend({ setup: function(el, options) { var res = can.Control.prototype.setup.call(this, el, options); this.scope = options.scope; var self = this; this.on(this.scope, "change", function handler() { self.on(); self.on(self.scope, "change", handler); }); return res; } }, this.prototype.events)); // Look to convert `scope` to a Map constructor function. if (!this.prototype.scope || typeof this.prototype.scope === "object") { // If scope is an object, use that object as the prototype of an extended // Map constructor function. // A new instance of that Map constructor function will be created and // set a the constructor instance's scope. this.Map = can.Map.extend(this.prototype.scope || {}); } else if (this.prototype.scope.prototype instanceof can.Map) { // If scope is a can.Map constructor function, just use that. this.Map = this.prototype.scope; } // Look for default `@` values. If a `@` is found, these // attributes string values will be set and 2-way bound on the // component instance's scope. this.attributeScopeMappings = {}; can.each(this.Map ? this.Map.defaults : {}, function(val, prop) { if (val === "@") { self.attributeScopeMappings[prop] = prop; } }); // Convert the template into a renderer function. if (this.prototype.template) { if (typeof this.prototype.template === "function") { var temp = this.prototype.template; this.renderer = function() { return can.view.frag(temp.apply(null, arguments)); }; } else { this.renderer = can.view.mustache(this.prototype.template); } } // Register this component to be created when its `tag` is found. can.view.Scanner.tag(this.prototype.tag, function(el, options) { new self(el, options); }); } } }, { // ## Prototype // ### setup // When a new component instance is created, setup bindings, render the template, etc. setup: function(el, hookupOptions) { // Setup values passed to component var initalScopeData = {}, component = this, twoWayBindings = {}, // what scope property is currently updating scopePropertyUpdating, // the object added to the scope componentScope, frag; // scope prototype properties marked with an "@" are added here can.each(this.constructor.attributeScopeMappings, function(val, prop) { initalScopeData[prop] = el.getAttribute(can.hyphenate(val)); }); // get the value in the scope for each attribute // the hookup should probably happen after? can.each(can.makeArray(el.attributes), function(node, index) { var name = can.camelize(node.nodeName.toLowerCase()), value = node.value; // ignore attributes already in ScopeMappings if (component.constructor.attributeScopeMappings[name] || ignoreAttributesRegExp.test(name) || can.view.Scanner.attributes[node.nodeName]) { return; } // ignore attr regexps for (var regAttr in can.view.Scanner.regExpAttributes) { if (can.view.Scanner.regExpAttributes[regAttr].match.test(node.nodeName)) { return; } } // Cross-bind the value in the scope to this // component's scope var computeData = hookupOptions.scope.computeData(value, { args: [] }), compute = computeData.compute; // bind on this, check it's value, if it has dependencies var handler = function(ev, newVal) { scopePropertyUpdating = name; componentScope.attr(name, newVal); scopePropertyUpdating = null; }; // compute only returned if bindable compute.bind("change", handler); // set the value to be added to the scope initalScopeData[name] = compute(); if (!compute.hasDependencies) { compute.unbind("change", handler); } else { // make sure we unbind (there's faster ways of doing this) can.bind.call(el, "removed", function() { compute.unbind("change", handler); }); // setup two-way binding twoWayBindings[name] = computeData; } }); if (this.constructor.Map) { componentScope = new this.constructor.Map(initalScopeData); } else if (this.scope instanceof can.Map) { componentScope = this.scope; } else if (can.isFunction(this.scope)) { var scopeResult = this.scope(initalScopeData, hookupOptions.scope, el); // if the function returns a can.Map, use that as the scope if (scopeResult instanceof can.Map) { componentScope = scopeResult; } else if (scopeResult.prototype instanceof can.Map) { componentScope = new scopeResult(initalScopeData); } else { componentScope = new(can.Map.extend(scopeResult))(initalScopeData); } } var handlers = {}; // setup reverse bindings can.each(twoWayBindings, function(computeData, prop) { handlers[prop] = function(ev, newVal) { // check that this property is not being changed because // it's source value just changed if (scopePropertyUpdating !== prop) { computeData.compute(newVal); } }; componentScope.bind(prop, handlers[prop]); }); // teardown reverse bindings when element is removed can.bind.call(el, "removed", function() { can.each(handlers, function(handler, prop) { componentScope.unbind(prop, handlers[prop]); }); }); this.scope = componentScope; can.data(can.$(el), "scope", this.scope); // create a real Scope object out of the scope property var renderedScope = hookupOptions.scope.add(this.scope), // setup helpers to callback with `this` as the component helpers = {}; can.each(this.helpers || {}, function(val, prop) { if (can.isFunction(val)) { helpers[prop] = function() { return val.apply(componentScope, arguments); }; } }); // create a control to listen to events this._control = new this.constructor.Control(el, { scope: this.scope }); // if this component has a template (that we've already converted to a renderer) if (this.constructor.renderer) { // add content to tags if (!helpers._tags) { helpers._tags = {}; } // we need be alerted to when a <content> element is rendered so we can put the original contents of the widget in its place helpers._tags.content = function render(el, rendererOptions) { // first check if there was content within the custom tag // otherwise, render what was within <content>, the default code var subtemplate = hookupOptions.subtemplate || rendererOptions.subtemplate; if (subtemplate) { // rendererOptions.options is a scope of helpers where `<content>` was found, so // the right helpers should already be available. // However, _tags.content is going to point to this current content callback. We need to // remove that so it will walk up the chain delete helpers._tags.content; can.view.live.replace([el], subtemplate( // This is the context of where `<content>` was found // which will have the the component's context rendererOptions.scope, rendererOptions.options)); // restore the content tag so it could potentially be used again (as in lists) helpers._tags.content = render; } }; // render the component's template frag = this.constructor.renderer(renderedScope, hookupOptions.options.add(helpers)); } else { // otherwise render the contents between the frag = can.view.frag(hookupOptions.subtemplate ? hookupOptions.subtemplate(renderedScope, hookupOptions.options.add(helpers)) : ""); } can.appendChild(el, frag); } }); if (window.$ && $.fn) { $.fn.scope = function(attr) { if (attr) { return this.data("scope") .attr(attr); } else { return this.data("scope"); } }; } can.scope = function(el, attr) { el = can.$(el); if (attr) { return can.data(el, "scope") .attr(attr); } else { return can.data(el, "scope"); } }; return Component; })(__m2, __m12, __m15, __m21, __m29); // ## model/model.js var __m30 = (function(can) { // ## model.js // `can.Model` // _A `can.Map` that connects to a RESTful interface._ // Generic deferred piping function var pipe = function(def, model, func) { var d = new can.Deferred(); def.then(function() { var args = can.makeArray(arguments), success = true; try { args[0] = model[func](args[0]); } catch (e) { success = false; d.rejectWith(d, [e].concat(args)); } if (success) { d.resolveWith(d, args); } }, function() { d.rejectWith(this, arguments); }); if (typeof def.abort === 'function') { d.abort = function() { return def.abort(); }; } return d; }, modelNum = 0, getId = function(inst) { // Instead of using attr, use __get for performance. // Need to set reading if (can.__reading) { can.__reading(inst, inst.constructor.id); } return inst.__get(inst.constructor.id); }, // Ajax `options` generator function ajax = function(ajaxOb, data, type, dataType, success, error) { var params = {}; // If we get a string, handle it. if (typeof ajaxOb === 'string') { // If there's a space, it's probably the type. var parts = ajaxOb.split(/\s+/); params.url = parts.pop(); if (parts.length) { params.type = parts.pop(); } } else { can.extend(params, ajaxOb); } // If we are a non-array object, copy to a new attrs. params.data = typeof data === "object" && !can.isArray(data) ? can.extend(params.data || {}, data) : data; // Get the url with any templated values filled out. params.url = can.sub(params.url, params.data, true); return can.ajax(can.extend({ type: type || 'post', dataType: dataType || 'json', success: success, error: error }, params)); }, makeRequest = function(self, type, success, error, method) { var args; // if we pass an array as `self` it it means we are coming from // the queued request, and we're passing already serialized data // self's signature will be: [self, serializedData] if (can.isArray(self)) { args = self[1]; self = self[0]; } else { args = self.serialize(); } args = [args]; var deferred, // The model. model = self.constructor, jqXHR; // `update` and `destroy` need the `id`. if (type !== 'create') { args.unshift(getId(self)); } jqXHR = model[type].apply(model, args); deferred = jqXHR.pipe(function(data) { self[method || type + "d"](data, jqXHR); return self; }); // Hook up `abort` if (jqXHR.abort) { deferred.abort = function() { jqXHR.abort(); }; } deferred.then(success, error); return deferred; }, initializers = { // makes a models function that looks up the data in a particular property models: function(prop) { return function(instancesRawData, oldList) { // until "end of turn", increment reqs counter so instances will be added to the store can.Model._reqs++; if (!instancesRawData) { return; } if (instancesRawData instanceof this.List) { return instancesRawData; } // Get the list type. var self = this, tmp = [], Cls = self.List || ML, res = oldList instanceof can.List ? oldList : new Cls(), // Did we get an `array`? arr = can.isArray(instancesRawData), // Did we get a model list? ml = instancesRawData instanceof ML, // Get the raw `array` of objects. raw = arr ? // If an `array`, return the `array`. instancesRawData : // Otherwise if a model list. (ml ? // Get the raw objects from the list. instancesRawData.serialize() : // Get the object's data. can.getObject(prop || "data", instancesRawData)); if (typeof raw === 'undefined') { throw new Error('Could not get any raw data while converting using .models'); } if (res.length) { res.splice(0); } can.each(raw, function(rawPart) { tmp.push(self.model(rawPart)); }); // We only want one change event so push everything at once res.push.apply(res, tmp); if (!arr) { // Push other stuff onto `array`. can.each(instancesRawData, function(val, prop) { if (prop !== 'data') { res.attr(prop, val); } }); } // at "end of turn", clean up the store setTimeout(can.proxy(this._clean, this), 1); return res; }; }, model: function(prop) { return function(attributes) { if (!attributes) { return; } if (typeof attributes.serialize === 'function') { attributes = attributes.serialize(); } if (prop) { attributes = can.getObject(prop || 'data', attributes); } var id = attributes[this.id], model = (id || id === 0) && this.store[id] ? this.store[id].attr(attributes, this.removeAttr || false) : new this(attributes); return model; }; } }, // This object describes how to make an ajax request for each ajax method. // The available properties are: // `url` - The default url to use as indicated as a property on the model. // `type` - The default http request type // `data` - A method that takes the `arguments` and returns `data` used for ajax. ajaxMethods = { create: { url: "_shortName", type: "post" }, update: { data: function(id, attrs) { attrs = attrs || {}; var identity = this.id; if (attrs[identity] && attrs[identity] !== id) { attrs["new" + can.capitalize(id)] = attrs[identity]; delete attrs[identity]; } attrs[identity] = id; return attrs; }, type: "put" }, destroy: { type: 'delete', data: function(id, attrs) { attrs = attrs || {}; attrs.id = attrs[this.id] = id; return attrs; } }, findAll: { url: "_shortName" }, findOne: {} }, // Makes an ajax request `function` from a string. // `ajaxMethod` - The `ajaxMethod` object defined above. // `str` - The string the user provided. Ex: `findAll: "/recipes.json"`. ajaxMaker = function(ajaxMethod, str) { // Return a `function` that serves as the ajax method. return function(data) { // If the ajax method has it's own way of getting `data`, use that. data = ajaxMethod.data ? ajaxMethod.data.apply(this, arguments) : // Otherwise use the data passed in. data; // Return the ajax method with `data` and the `type` provided. return ajax(str || this[ajaxMethod.url || "_url"], data, ajaxMethod.type || "get"); }; }; can.Model = can.Map({ fullName: 'can.Model', _reqs: 0, setup: function(base) { // create store here if someone wants to use model without inheriting from it this.store = {}; can.Map.setup.apply(this, arguments); // Set default list as model list if (!can.Model) { return; } this.List = ML({ Map: this }, {}); var self = this, clean = can.proxy(this._clean, self); // go through ajax methods and set them up can.each(ajaxMethods, function(method, name) { // if an ajax method is not a function, it's either // a string url like findAll: "/recipes" or an // ajax options object like {url: "/recipes"} if (!can.isFunction(self[name])) { // use ajaxMaker to convert that into a function // that returns a deferred with the data self[name] = ajaxMaker(method, self[name]); } // check if there's a make function like makeFindAll // these take deferred function and can do special // behavior with it (like look up data in a store) if (self['make' + can.capitalize(name)]) { // pass the deferred method to the make method to get back // the "findAll" method. var newMethod = self['make' + can.capitalize(name)](self[name]); can.Construct._overwrite(self, base, name, function() { // increment the numer of requests can.Model._reqs++; var def = newMethod.apply(this, arguments); var then = def.then(clean, clean); then.abort = def.abort; // attach abort to our then and return it return then; }); } }); can.each(initializers, function(makeInitializer, name) { if (typeof self[name] === 'string') { can.Construct._overwrite(self, base, name, makeInitializer(self[name])); } }); if (self.fullName === 'can.Model' || !self.fullName) { modelNum++; self.fullName = 'Model' + modelNum; } // Add ajax converters. can.Model._reqs = 0; this._url = this._shortName + '/{' + this.id + '}'; }, _ajax: ajaxMaker, _makeRequest: makeRequest, _clean: function() { can.Model._reqs--; if (!can.Model._reqs) { for (var id in this.store) { if (!this.store[id]._bindings) { delete this.store[id]; } } } return arguments[0]; }, models: initializers.models("data"), model: initializers.model() }, { setup: function(attrs) { // try to add things as early as possible to the store (#457) // we add things to the store before any properties are even set var id = attrs && attrs[this.constructor.id]; if (can.Model._reqs && id !== null) { this.constructor.store[id] = this; } can.Map.prototype.setup.apply(this, arguments); }, isNew: function() { var id = getId(this); return !(id || id === 0); // If `null` or `undefined` }, save: function(success, error) { return makeRequest(this, this.isNew() ? 'create' : 'update', success, error); }, destroy: function(success, error) { if (this.isNew()) { var self = this; var def = can.Deferred(); def.then(success, error); return def.done(function(data) { self.destroyed(data); }) .resolve(self); } return makeRequest(this, 'destroy', success, error, 'destroyed'); }, _bindsetup: function() { this.constructor.store[this.__get(this.constructor.id)] = this; return can.Map.prototype._bindsetup.apply(this, arguments); }, _bindteardown: function() { delete this.constructor.store[getId(this)]; return can.Map.prototype._bindteardown.apply(this, arguments); }, // Change `id`. ___set: function(prop, val) { can.Map.prototype.___set.call(this, prop, val); // If we add an `id`, move it to the store. if (prop === this.constructor.id && this._bindings) { this.constructor.store[getId(this)] = this; } } }); can.each({ makeFindAll: "models", makeFindOne: "model", makeCreate: "model", makeUpdate: "model" }, function(method, name) { can.Model[name] = function(oldMethod) { return function() { var args = can.makeArray(arguments), oldArgs = can.isFunction(args[1]) ? args.splice(0, 1) : args.splice(0, 2), def = pipe(oldMethod.apply(this, oldArgs), this, method); def.then(args[0], args[1]); // return the original promise return def; }; }; }); can.each([ "created", "updated", "destroyed" ], function(funcName) { can.Model.prototype[funcName] = function(attrs) { var stub, constructor = this.constructor; // Update attributes if attributes have been passed stub = attrs && typeof attrs === 'object' && this.attr(attrs.attr ? attrs.attr() : attrs); // triggers change event that bubble's like // handler( 'change','1.destroyed' ). This is used // to remove items on destroyed from Model Lists. // but there should be a better way. can.trigger(this, "change", funcName); // Call event on the instance's Class can.trigger(constructor, funcName, this); }; }); // Model lists are just like `Map.List` except that when their items are // destroyed, it automatically gets removed from the list. var ML = can.Model.List = can.List({ setup: function(params) { if (can.isPlainObject(params) && !can.isArray(params)) { can.List.prototype.setup.apply(this); this.replace(this.constructor.Map.findAll(params)); } else { can.List.prototype.setup.apply(this, arguments); } }, _changes: function(ev, attr) { can.List.prototype._changes.apply(this, arguments); if (/\w+\.destroyed/.test(attr)) { var index = this.indexOf(ev.target); if (index !== -1) { this.splice(index, 1); } } } }); return can.Model; })(__m2, __m16, __m19); // ## util/string/deparam/deparam.js var __m32 = (function(can) { // ## deparam.js // `can.deparam` // _Takes a string of name value pairs and returns a Object literal that represents those params._ var digitTest = /^\d+$/, keyBreaker = /([^\[\]]+)|(\[\])/g, paramTest = /([^?#]*)(#.*)?$/, prep = function(str) { return decodeURIComponent(str.replace(/\+/g, ' ')); }; can.extend(can, { deparam: function(params) { var data = {}, pairs, lastPart; if (params && paramTest.test(params)) { pairs = params.split('&'); can.each(pairs, function(pair) { var parts = pair.split('='), key = prep(parts.shift()), value = prep(parts.join('=')), current = data; if (key) { parts = key.match(keyBreaker); for (var j = 0, l = parts.length - 1; j < l; j++) { if (!current[parts[j]]) { // If what we are pointing to looks like an `array` current[parts[j]] = digitTest.test(parts[j + 1]) || parts[j + 1] === '[]' ? [] : {}; } current = current[parts[j]]; } lastPart = parts.pop(); if (lastPart === '[]') { current.push(value); } else { current[lastPart] = value; } } }); } return data; } }); return can; })(__m2, __m14); // ## route/route.js var __m31 = (function(can) { // ## route.js // `can.route` // _Helps manage browser history (and client state) by synchronizing the // `window.location.hash` with a `can.Map`._ // Helper methods used for matching routes. var // `RegExp` used to match route variables of the type ':name'. // Any word character or a period is matched. matcher = /\:([\w\.]+)/g, // Regular expression for identifying &amp;key=value lists. paramsMatcher = /^(?:&[^=]+=[^&]*)+/, // Converts a JS Object into a list of parameters that can be // inserted into an html element tag. makeProps = function(props) { var tags = []; can.each(props, function(val, name) { tags.push((name === 'className' ? 'class' : name) + '="' + (name === "href" ? val : can.esc(val)) + '"'); }); return tags.join(" "); }, // Checks if a route matches the data provided. If any route variable // is not present in the data, the route does not match. If all route // variables are present in the data, the number of matches is returned // to allow discerning between general and more specific routes. matchesData = function(route, data) { var count = 0, i = 0, defaults = {}; // look at default values, if they match ... for (var name in route.defaults) { if (route.defaults[name] === data[name]) { // mark as matched defaults[name] = 1; count++; } } for (; i < route.names.length; i++) { if (!data.hasOwnProperty(route.names[i])) { return -1; } if (!defaults[route.names[i]]) { count++; } } return count; }, location = window.location, wrapQuote = function(str) { return (str + '') .replace(/([.?*+\^$\[\]\\(){}|\-])/g, "\\$1"); }, each = can.each, extend = can.extend, // Helper for convert any object (or value) to stringified object (or value) stringify = function(obj) { // Object is array, plain object, Map or List if (obj && typeof obj === "object") { // Get native object or array from Map or List if (obj instanceof can.Map) { obj = obj.attr(); // Clone object to prevent change original values } else { obj = can.isFunction(obj.slice) ? obj.slice() : can.extend({}, obj); } // Convert each object property or array item into stringified new can.each(obj, function(val, prop) { obj[prop] = stringify(val); }); // Object supports toString function } else if (obj !== undefined && obj !== null && can.isFunction(obj.toString)) { obj = obj.toString(); } return obj; }, removeBackslash = function(str) { return str.replace(/\\/g, ""); }, // A ~~throttled~~ debounced function called multiple times will only fire once the // timer runs down. Each call resets the timer. timer, // Intermediate storage for `can.route.data`. curParams, // The last hash caused by a data change lastHash, // Are data changes pending that haven't yet updated the hash changingData, // If the `can.route.data` changes, update the hash. // Using `.serialize()` retrieves the raw data contained in the `observable`. // This function is ~~throttled~~ debounced so it only updates once even if multiple values changed. // This might be able to use batchNum and avoid this. onRouteDataChange = function(ev, attr, how, newval) { // indicate that data is changing changingData = 1; clearTimeout(timer); timer = setTimeout(function() { // indicate that the hash is set to look like the data changingData = 0; var serialized = can.route.data.serialize(), path = can.route.param(serialized, true); can.route._call("setURL", path); lastHash = path; }, 10); }; can.route = function(url, defaults) { // if route ends with a / and url starts with a /, remove the leading / of the url var root = can.route._call("root"); if (root.lastIndexOf("/") === root.length - 1 && url.indexOf("/") === 0) { url = url.substr(1); } defaults = defaults || {}; // Extract the variable names and replace with `RegExp` that will match // an atual URL with values. var names = [], res, test = "", lastIndex = matcher.lastIndex = 0, next, querySeparator = can.route._call("querySeparator"); // res will be something like [":foo","foo"] while (res = matcher.exec(url)) { names.push(res[1]); test += removeBackslash(url.substring(lastIndex, matcher.lastIndex - res[0].length)); next = "\\" + (removeBackslash(url.substr(matcher.lastIndex, 1)) || querySeparator); // a name without a default value HAS to have a value // a name that has a default value can be empty // The `\\` is for string-escaping giving single `\` for `RegExp` escaping. test += "([^" + next + "]" + (defaults[res[1]] ? "*" : "+") + ")"; lastIndex = matcher.lastIndex; } test += url.substr(lastIndex) .replace("\\", ""); // Add route in a form that can be easily figured out. can.route.routes[url] = { // A regular expression that will match the route when variable values // are present; i.e. for `:page/:type` the `RegExp` is `/([\w\.]*)/([\w\.]*)/` which // will match for any value of `:page` and `:type` (word chars or period). test: new RegExp("^" + test + "($|" + wrapQuote(querySeparator) + ")"), // The original URL, same as the index for this entry in routes. route: url, // An `array` of all the variable names in this route. names: names, // Default values provided for the variables. defaults: defaults, // The number of parts in the URL separated by `/`. length: url.split('/') .length }; return can.route; }; extend(can.route, { param: function(data, _setRoute) { // Check if the provided data keys match the names in any routes; // Get the one with the most matches. var route, // Need to have at least 1 match. matches = 0, matchCount, routeName = data.route, propCount = 0; delete data.route; each(data, function() { propCount++; }); // Otherwise find route. each(can.route.routes, function(temp, name) { // best route is the first with all defaults matching matchCount = matchesData(temp, data); if (matchCount > matches) { route = temp; matches = matchCount; } if (matchCount >= propCount) { return false; } }); // If we have a route name in our `can.route` data, and it's // just as good as what currently matches, use that if (can.route.routes[routeName] && matchesData(can.route.routes[routeName], data) === matches) { route = can.route.routes[routeName]; } // If this is match... if (route) { var cpy = extend({}, data), // Create the url by replacing the var names with the provided data. // If the default value is found an empty string is inserted. res = route.route.replace(matcher, function(whole, name) { delete cpy[name]; return data[name] === route.defaults[name] ? "" : encodeURIComponent(data[name]); }) .replace("\\", ""), after; // Remove matching default values each(route.defaults, function(val, name) { if (cpy[name] === val) { delete cpy[name]; } }); // The remaining elements of data are added as // `&amp;` separated parameters to the url. after = can.param(cpy); // if we are paraming for setting the hash // we also want to make sure the route value is updated if (_setRoute) { can.route.attr('route', route.route); } return res + (after ? can.route._call("querySeparator") + after : ""); } // If no route was found, there is no hash URL, only paramters. return can.isEmptyObject(data) ? "" : can.route._call("querySeparator") + can.param(data); }, deparam: function(url) { // remove the url var root = can.route._call("root"); if (root.lastIndexOf("/") === root.length - 1 && url.indexOf("/") === 0) { url = url.substr(1); } // See if the url matches any routes by testing it against the `route.test` `RegExp`. // By comparing the URL length the most specialized route that matches is used. var route = { length: -1 }, querySeparator = can.route._call("querySeparator"), paramsMatcher = can.route._call("paramsMatcher"); each(can.route.routes, function(temp, name) { if (temp.test.test(url) && temp.length > route.length) { route = temp; } }); // If a route was matched. if (route.length > -1) { var // Since `RegExp` backreferences are used in `route.test` (parens) // the parts will contain the full matched string and each variable (back-referenced) value. parts = url.match(route.test), // Start will contain the full matched string; parts contain the variable values. start = parts.shift(), // The remainder will be the `&amp;key=value` list at the end of the URL. remainder = url.substr(start.length - (parts[parts.length - 1] === querySeparator ? 1 : 0)), // If there is a remainder and it contains a `&amp;key=value` list deparam it. obj = (remainder && paramsMatcher.test(remainder)) ? can.deparam(remainder.slice(1)) : {}; // Add the default values for this route. obj = extend(true, {}, route.defaults, obj); // Overwrite each of the default values in `obj` with those in // parts if that part is not empty. each(parts, function(part, i) { if (part && part !== querySeparator) { obj[route.names[i]] = decodeURIComponent(part); } }); obj.route = route.route; return obj; } // If no route was matched, it is parsed as a `&amp;key=value` list. if (url.charAt(0) !== querySeparator) { url = querySeparator + url; } return paramsMatcher.test(url) ? can.deparam(url.slice(1)) : {}; }, data: new can.Map({}), routes: {}, ready: function(val) { if (val !== true) { can.route._setup(); can.route.setState(); } return can.route; }, url: function(options, merge) { if (merge) { options = can.extend({}, can.route.deparam(can.route._call("matchingPartOfURL")), options); } return can.route._call("root") + can.route.param(options); }, link: function(name, options, props, merge) { return "<a " + makeProps( extend({ href: can.route.url(options, merge) }, props)) + ">" + name + "</a>"; }, current: function(options) { return this._call("matchingPartOfURL") === can.route.param(options); }, bindings: { hashchange: { paramsMatcher: paramsMatcher, querySeparator: "&", bind: function() { can.bind.call(window, 'hashchange', setState); }, unbind: function() { can.unbind.call(window, 'hashchange', setState); }, // Gets the part of the url we are determinging the route from. // For hashbased routing, it's everything after the #, for // pushState it's configurable matchingPartOfURL: function() { return location.href.split(/#!?/)[1] || ""; }, // gets called with the serialized can.route data after a route has changed // returns what the url has been updated to (for matching purposes) setURL: function(path) { location.hash = "#!" + path; return path; }, root: "#!" } }, defaultBinding: "hashchange", currentBinding: null, // ready calls setup // setup binds and listens to data changes // bind listens to whatever you should be listening to // data changes tries to set the path // we need to be able to // easily kick off calling setState // teardown whatever is there // turn on a particular binding // called when the route is ready _setup: function() { if (!can.route.currentBinding) { can.route._call("bind"); can.route.bind("change", onRouteDataChange); can.route.currentBinding = can.route.defaultBinding; } }, _teardown: function() { if (can.route.currentBinding) { can.route._call("unbind"); can.route.unbind("change", onRouteDataChange); can.route.currentBinding = null; } clearTimeout(timer); changingData = 0; }, // a helper to get stuff from the current or default bindings _call: function() { var args = can.makeArray(arguments), prop = args.shift(), binding = can.route.bindings[can.route.currentBinding || can.route.defaultBinding], method = binding[prop]; if (typeof method === "function") { return method.apply(binding, args); } else { return method; } } }); // The functions in the following list applied to `can.route` (e.g. `can.route.attr('...')`) will // instead act on the `can.route.data` observe. each(['bind', 'unbind', 'on', 'off', 'delegate', 'undelegate', 'removeAttr', 'compute', '_get', '__get'], function(name) { can.route[name] = function() { // `delegate` and `undelegate` require // the `can/map/delegate` plugin if (!can.route.data[name]) { return; } return can.route.data[name].apply(can.route.data, arguments); }; }); // Because everything in hashbang is in fact a string this will automaticaly convert new values to string. Works with single value, or deep hashes. // Main motivation for this is to prevent double route event call for same value. // Example (the problem): // When you load page with hashbang like #!&some_number=2 and bind 'some_number' on routes. // It will fire event with adding of "2" (string) to 'some_number' property // But when you after this set can.route.attr({some_number: 2}) or can.route.attr('some_number', 2). it fires another event with change of 'some_number' from "2" (string) to 2 (integer) // This wont happen again with this normalization can.route.attr = function(attr, val) { var type = typeof attr, newArguments; // Reading if (val === undefined) { newArguments = arguments; // Sets object } else if (type !== "string" && type !== "number") { newArguments = [stringify(attr), val]; // Sets key - value } else { newArguments = [attr, stringify(val)]; } return can.route.data.attr.apply(can.route.data, newArguments); }; var // Deparameterizes the portion of the hash of interest and assign the // values to the `can.route.data` removing existing values no longer in the hash. // setState is called typically by hashchange which fires asynchronously // So it's possible that someone started changing the data before the // hashchange event fired. For this reason, it will not set the route data // if the data is changing or the hash already matches the hash that was set. setState = can.route.setState = function() { var hash = can.route._call("matchingPartOfURL"); curParams = can.route.deparam(hash); // if the hash data is currently changing, or // the hash is what we set it to anyway, do NOT change the hash if (!changingData || hash !== lastHash) { can.route.attr(curParams, true); } }; return can.route; })(__m2, __m16, __m19, __m32); // ## control/route/route.js var __m33 = (function(can) { // ## control/route.js // _Controller route integration._ can.Control.processors.route = function(el, event, selector, funcName, controller) { selector = selector || ""; if (!can.route.routes[selector]) { if (selector[0] === '/') { selector = selector.substring(1); } can.route(selector); } var batchNum, check = function(ev, attr, how) { if (can.route.attr('route') === (selector) && (ev.batchNum === undefined || ev.batchNum !== batchNum)) { batchNum = ev.batchNum; var d = can.route.attr(); delete d.route; if (can.isFunction(controller[funcName])) { controller[funcName](d); } else { controller[controller[funcName]](d); } } }; can.route.bind('change', check); return function() { can.route.unbind('change', check); }; }; return can; })(__m2, __m31, __m12); window['can'] = __m3; })();
describe("CDWidget", () => { let widget, module, hideMessageDelay; var setFixture = () => { document.body.innerHTML = '<div w-type="countdown"></div>'; }; beforeAll(() => { window.__VERSION__ = 'mockedVersion'; setFixture(); module = require('products-and-docs/widgets/countdown/1.0.0/src/main-widget.es6'); widget = new module.TicketmasterCountdownWidget(document.querySelector('div[w-type="countdown"]')); }); beforeEach(function() { spyOn(widget, 'toggleSecondsVisibility'); spyOn(widget, 'clear'); spyOn(widget, 'hideMessage'); spyOn(widget, 'showMessage'); spyOn(widget, 'publishEvent'); }); it('widget should be BeDefined', () => { expect(widget).toBeDefined(); }); it('#eventUrl should be "http://www.ticketmaster.com/event/"', () => { expect(widget.eventUrl).toBe("http://www.ticketmaster.com/event/"); }); it('#formatDate should return result', () => { let noneResult = widget.formatDate('date'); expect(noneResult).toBe(''); let noneTimeResult = widget.formatDate({day : "2017-03-17"}); expect(noneTimeResult).toEqual("Fri, Mar 17, 2017"); let mockDate = { dateTime : "2017-03-18T00:30:00Z", day : "2017-03-17", time : "20:30:00" }; let okResult = widget.formatDate(mockDate); expect(okResult).toEqual("Fri, Mar 17, 2017 08:30 PM"); }); it('#showStatusMessage should show event status message', () => { widget.eventResponce = { date: { dateTime :'Tue Apr 11 2017 15:48:06 GMT+0300 (FLE Daylight Time)' , dateTimeEnd: 'Tue Apr 11 2018 15:48:06 GMT+0300 (FLE Daylight Time)' } }; widget.showStatusMessage(); expect(widget.showMessage).toHaveBeenCalledWith(`Event is in progress`, false , "event-message-started"); widget.eventResponce = { date: { dateTime :'not valid', dateTimeEnd: 'not valid' } }; widget.showStatusMessage(); expect(widget.showMessage).toHaveBeenCalledWith(`This event has taken place`, false , "event-message-started"); }); it('#updateTransition should manage class appear', () => { widget.clearEvents = function () { return this.eventsRoot.innerHTML = ""; }; let elem = document.querySelector(".event-logo.centered-logo"); widget.updateTransition('url'); expect(elem.classList).toContain("event-logo"); widget.updateTransition(false); expect(widget.updateTransition(false)).toBe(undefined); widget.updateTransition(''); expect(elem.classList).toContain("centered-logo") }); it('#hideMessageDelay should be integer', () => { expect(widget.hideMessageDelay).toBe(5000); }); it('#updateExceptions should be array of string', () => { expect(widget.updateExceptions).toEqual(jasmine.arrayContaining(["width", "height", "border", "borderradius", "layout", "propotion", "seconds"])); }); it('#tmWidgetWhiteList should contain string', () => { expect(widget.tmWidgetWhiteList).toContain("1B005068DB60687F"); }); it('#isConfigAttrExistAndNotEmpty should be Undefined', () => { expect(widget.config.id).toBeUndefined(); widget.config.id = 'someID'; expect(widget.config.id).toBeDefined(); expect(widget.isConfigAttrExistAndNotEmpty('id')).toBe(true); }); it('#constructor should be showMessage', () => { setTimeout(function() { widget.countDownMonth = {}; widget.countDownMonth.innerHTML = '888'; console.log('1 innerHTML', widget.countDownMonth.innerHTML); widget.toggleSecondsVisibility(); expect(widget.toggleSecondsVisibility).toHaveBeenCalled(); done(); }, 200); }); it('#update should be called with FullWidthTheme', () => { let isFullWidth = true; widget.update(isFullWidth); widget.clear(); expect(widget.clear).toHaveBeenCalled(); }); it('#getImageForEvent should return the second smallest img', () => { var images = [ { width : '100', height :'200', url:"img-01.bmp"}, { width : '400', height :'300', url:"img-02.bmp"}, { width : '50', height :'50', url:"img-03.bmp"}, { width : '10', height :'10', url:"img-04.bmp"} ]; expect(widget.getImageForEvent(images)).toBe("img-03.bmp"); }); it('#initPretendedLink should return element', () => { var el = { setAttribute: ()=>{true}, getAttribute: ()=>{false}, classList: {add:()=>{true}}, addEventListener: (event,fn)=>{ // fn.getAttribute = function(){return false} // fn().bind(this) } }, url ="img-01.bmp", isBlank=true; expect(widget.initPretendedLink(el, url, isBlank)).toBe(el); }); it('#parseEvent should return currentEvent', () => { var eventSet = { id:'porky', url:'pie', name: 'Tanok na maydani Kongo', address:{name:''}, images : [ { width : '100', height :'200', url:"img-01.bmp"}, { width : '400', height :'300', url:"img-02.bmp"}, { width : '50', height :'50', url:"img-03.bmp"}, { width : '10', height :'10', url:"img-04.bmp"} ], dates : { start : { localDate: '23.09.83', localTime: '12:00', dateTime: '11:00' }, end : { localDate: '23.09.99', localTime: '19:00', dateTime: '18:00' } }, _embedded: { venues: [ { name: 'one address' } ] } }; var currentEvent = widget.parseEvent(eventSet); var generatedObj = { address: {"name": "one address"}, date: {"dateTime": "11:00", "dateTimeEnd": "18:00", "day": "23.09.83", "dayEnd": "23.09.99", "time": "12:00", "timeEnd": "19:00"}, id: "porky", img: "img-03.bmp", name: "Tanok na maydani Kongo", url: "pie" }; expect(currentEvent).toEqual(generatedObj); var generatedObjNoVenueName = { id: 'porky', url: 'pie', name: 'Tanok na maydani Kongo', date: { day: '23.09.83', time: '12:00', dateTime: '11:00', dayEnd: '23.09.99', timeEnd: '19:00', dateTimeEnd: '18:00' }, address: 'one address', img: 'img-03.bmp' }; eventSet._embedded.venues[0]={ address: 'one address' }; let currentEventNoVenueName = widget.parseEvent(eventSet); expect(currentEventNoVenueName).toEqual(generatedObjNoVenueName); }); it('#initFullWidth should return set width=100%', () => { var config = { width: '100%', height : 700 }, widgetRoot ={ style : { width: '100%', height : '700px', display: 'block' } }, eventsRootContainer ={ style : { width: '100%', height : '700px' } }; widget.initFullWidth(); expect(widget.config.width).toBe(config.width); expect(widget.config.height ).toBe(config.height ); expect(widget.widgetRoot.style.width).toBe(widgetRoot.style.width); expect(widget.widgetRoot.style.height).toBe(widgetRoot.style.height); expect(widget.widgetRoot.style.display).toBe(widgetRoot.style.display); expect(widget.eventsRootContainer.style.width ).toBe(eventsRootContainer.style.width); expect(widget.eventsRootContainer.style.height ).toBe(eventsRootContainer.style.height); }); it('#createDOMItem should create element', () => { var itemConfig = { name: 'some mock text', address: { name: 'vinnica', line1: '700', line2: '700' }, date: 'Wed Oct 23 2013 00:00:00 GMT+0300 (FLE Daylight Time)', categories : ['boo','foo'] }; var domElement = widget.createDOMItem(itemConfig); expect(domElement.localName).toEqual("li"); expect(domElement.children[0].nodeName).toEqual("SPAN"); expect(domElement.children[0].className).toEqual("bg-cover"); expect(domElement.children[1].className).toEqual("event-content-wraper"); expect(domElement.children[1].children.length).toEqual(4); expect(domElement.children[1].children[0].localName).toEqual("span"); expect(domElement.children[1].children[0].className).toContain("event-name"); expect(domElement.children[1].children[0].textContent).toEqual('some mock text'); expect(domElement.children[1].children[1].className).toContain("event-date-wraper"); expect(domElement.children[1].children[2].className).toContain("address-wrapper"); expect(domElement.children[1].children[3].className).toContain("category-wrapper"); }); });
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2897',"Tlece.Recruitment.Models.TleceAccount Namespace","topic_00000000000009CC.html"],['2913',"RecaptchaResponse Class","topic_00000000000009D9.html"],['2914',"Properties","topic_00000000000009D9_props--.html"],['2915',"ErrorCodes Property","topic_00000000000009DB.html"]];
'use strict' /** * Methods that model a hierarchical timing system, allowing objects to map time between their parent and local time. * @interface * @see https://developer.apple.com/documentation/quartzcore/camediatiming */ export default class CAMediaTiming { /** * constructor * @access public * @constructor */ constructor() { // Animation Start Time /** * Required. Specifies the begin time of the receiver in relation to its parent object, if applicable. * @type {number} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427654-begintime */ this.beginTime = 0 /** * Required. Specifies an additional time offset in active local time. * @type {number} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427650-timeoffset */ this.timeOffset = 0 // Repeating Animations /** * Required. Determines the number of times the animation will repeat. * @type {number} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427666-repeatcount */ this.repeatCount = 0 /** * Required. Determines how many seconds the animation will repeat for. * @type {number} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427643-repeatduration */ this.repeatDuration = 0 // Duration and Speed /** * Required. Specifies the basic duration of the animation, in seconds. * @type {number} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427652-duration */ this.duration = 0 /** * Required. Specifies how time is mapped to receiver’s time space from the parent time space. * @type {number} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427647-speed */ this.speed = 0 // Playback Modes /** * Required. Determines if the receiver plays in the reverse upon completion. * @type {boolean} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427645-autoreverses */ this.autoreverses = false /** * Required. Determines if the receiver’s presentation is frozen or removed once its active duration has completed. * @type {string} * @see https://developer.apple.com/documentation/quartzcore/camediatiming/1427656-fillmode */ this.fillMode = '' } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=WordCorrection.js.map
/* eslint no-magic-numbers: ["error", { "ignore": [-1] }] */ import PropTypes from 'prop-types'; import React, { forwardRef, useRef } from 'react'; const PREVENT_DEFAULT_HANDLER = event => event.preventDefault(); // Differences between <button> and <AccessibleButton>: // - Disable behavior // - When the widget is disabled // - Set "aria-disabled" attribute to "true" // - Set "readonly" attribute // - Set "tabIndex" to -1 // - Remove "onClick" handler // - Why this is needed // - Browser compatibility: when the widget is disabled, different browser send focus to different places // - When the widget become disabled, it's reasonable to keep the focus on the same widget for an extended period of time // - When the user presses TAB after the current widget is disabled, it should jump to the next non-disabled widget // Developers using this accessible widget will need to: // - Style the disabled widget themselves, using CSS query `:disabled, [aria-disabled="true"] {}` // - Modify all code that check disabled through "disabled" attribute to use aria-disabled="true" instead // - aria-disabled="true" is the source of truth // - If the widget is contained by a <form>, the developer need to filter out some `onSubmit` event caused by this widget const AccessibleButton = forwardRef(({ disabled, onClick, tabIndex, ...props }, forwardedRef) => { const targetRef = useRef(); const ref = forwardedRef || targetRef; return ( <button aria-disabled={disabled || undefined} onClick={disabled ? PREVENT_DEFAULT_HANDLER : onClick} ref={ref} tabIndex={disabled ? -1 : tabIndex} {...props} type="button" /> ); }); AccessibleButton.defaultProps = { disabled: undefined, onClick: undefined, tabIndex: undefined }; AccessibleButton.displayName = 'AccessibleButton'; AccessibleButton.propTypes = { disabled: PropTypes.bool, onClick: PropTypes.func, tabIndex: PropTypes.number, type: PropTypes.oneOf(['button']).isRequired }; export default AccessibleButton;
'use strict'; /* * Setting up users route. */ angular.module('users').config(['$stateProvider', function($stateProvider) { $stateProvider. // User profile state routing. state('profile', { url: '/:username', templateUrl: '/modules/users/views/profile/profile.client.view.html' }). state('profilefriends', { url: '/:username/friends', templateUrl: '/modules/users/views/friends/friends.client.view.html' }). // User friends state routing. state('friends', { abstract: true, url: '/friends', template: '<ui-view/>' }). state('friends.search', { url: '/search', templateUrl: '/modules/users/views/friends/find-friends.client.view.html' }). state('friends.requests', { url: '/requests', templateUrl: '/modules/users/views/friends/friend-requests.client.view.html' }). // User settings state routing. state('settings', { abstract: true, url: '/settings', templateUrl: '/modules/users/views/settings/settings.client.view.html' }). state('settings.profile', { url: '/profile', templateUrl: '/modules/users/views/settings/manage-profile.client.view.html' }). state('settings.credentials', { url: '/credentials', templateUrl: '/modules/users/views/settings/manage-credentials.client.view.html' }). state('settings.accounts', { url: '/accounts', templateUrl: '/modules/users/views/settings/manage-social-accounts.client.view.html' }). // User password state routing. state('password', { abstract: true, url: '/password', template: '<ui-view/>' }). state('password.forgot', { url: '/forgot', templateUrl: '/modules/users/views/password/forgot-password.client.view.html' }). state('password.reset', { abstract: true, url: '/reset', template: '<ui-view/>' }). state('password.reset.invalid', { url: '/invalid', templateUrl: '/modules/users/views/password/reset-password-invalid.client.view.html' }). state('password.reset.success', { url: '/success', templateUrl: '/modules/users/views/password/reset-password-success.client.view.html' }). state('password.reset.form', { url: '/:token', templateUrl: '/modules/users/views/password/reset-password.client.view.html' }); } ]);
var searchData= [ ['eta',['Eta',['../d1/d03/structproperties.html#abd91deb543a31a6a1f75892af7cf95c8',1,'properties']]], ['exec_2dbudgeted_2dtrain_2ec',['Exec-budgeted-train.c',['../d5/d89/Exec-budgeted-train_8c.html',1,'']]], ['exec_2dfull_2dtrain_2ec',['Exec-full-train.c',['../d3/d54/Exec-full-train_8c.html',1,'']]] ];
function euler153() { // Good luck! return true } euler153()
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import configureStore from '../store/configure_store'; import { syncHistoryWithStore } from 'react-router-redux'; import { observeStore } from '../ddp_observer'; import routes from '../routes'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); class App extends Component { talk() { ipcRenderer.send('asynchronous-message', { slug: 'start-ddp-server' }); } listen() { ipcRenderer.send('asynchronous-message', { slug: 'start-ddp-client' }); } render(){ return ( <Provider store={store}> <Router history={history} routes={routes} /> </Provider> ); } } var main = document.getElementById('main'); ReactDOM.render(<App />, main); // const { ipcRenderer } = window.require('electron'); // ipcRenderer.on('ddp-receive', (event, state) => { // console.log('sent to dispatcher', state) // store.dispatch({ type: 'DDP_RECEIVE', payload: state }) // }) // function onChange(state) { // ipcRenderer.send('asynchronous-message', { slug: 'ddp-send', payload: state }) // } // let observer = observeStore(store, onChange);