code
stringlengths
2
1.05M
'use strict'; var _ = require('lodash'); var Q = require('q'); var Page = require('../../../../base/Page'); var deserialize = require('../../../../base/deserialize'); var values = require('../../../../base/values'); var ValidationRequestPage; var ValidationRequestList; var ValidationRequestInstance; var ValidationRequestContext; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.ValidationRequestPage * @augments Page * @description Initialize the ValidationRequestPage * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} response - Response from the API * @param {string} accountSid - The account_sid * * @returns ValidationRequestPage */ /* jshint ignore:end */ function ValidationRequestPage(version, response, accountSid) { Page.prototype.constructor.call(this, version, response); // Path Solution this._solution = { accountSid: accountSid }; } _.extend(ValidationRequestPage.prototype, Page.prototype); ValidationRequestPage.prototype.constructor = ValidationRequestPage; /* jshint ignore:start */ /** * Build an instance of ValidationRequestInstance * * @function getInstance * @memberof Twilio.Api.V2010.AccountContext.ValidationRequestPage * @instance * * @param {object} payload - Payload response from the API * * @returns ValidationRequestInstance */ /* jshint ignore:end */ ValidationRequestPage.prototype.getInstance = function getInstance(payload) { return new ValidationRequestInstance( this._version, payload, this._solution.accountSid ); }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.ValidationRequestList * @description Initialize the ValidationRequestList * * @param {Twilio.Api.V2010} version - Version of the resource * @param {string} accountSid - The account_sid */ /* jshint ignore:end */ function ValidationRequestList(version, accountSid) { /* jshint ignore:start */ /** * @function validationRequests * @memberof Twilio.Api.V2010.AccountContext * @instance * * @param {string} sid - sid of instance * * @returns {Twilio.Api.V2010.AccountContext.ValidationRequestContext} */ /* jshint ignore:end */ function ValidationRequestListInstance(sid) { return ValidationRequestListInstance.get(sid); } ValidationRequestListInstance._version = version; // Path Solution ValidationRequestListInstance._solution = { accountSid: accountSid }; ValidationRequestListInstance._uri = _.template( '/Accounts/<%= accountSid %>/OutgoingCallerIds.json' // jshint ignore:line )(ValidationRequestListInstance._solution); /* jshint ignore:start */ /** * create a ValidationRequestInstance * * @function create * @memberof Twilio.Api.V2010.AccountContext.ValidationRequestList * @instance * * @param {object} opts - ... * @param {string} opts.accountSid - The account_sid * @param {string} opts.phoneNumber - The phone_number * @param {string} [opts.friendlyName] - The friendly_name * @param {number} [opts.callDelay] - The call_delay * @param {string} [opts.extension] - The extension * @param {string} [opts.statusCallback] - The status_callback * @param {string} [opts.statusCallbackMethod] - The status_callback_method * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ValidationRequestInstance */ /* jshint ignore:end */ ValidationRequestListInstance.create = function create(opts, callback) { if (_.isUndefined(opts)) { throw new Error('Required parameter "opts" missing.'); } if (_.isUndefined(opts.phoneNumber)) { throw new Error('Required parameter "opts.phoneNumber" missing.'); } var deferred = Q.defer(); var data = values.of({ 'PhoneNumber': opts.phoneNumber, 'FriendlyName': opts.friendlyName, 'CallDelay': opts.callDelay, 'Extension': opts.extension, 'StatusCallback': opts.statusCallback, 'StatusCallbackMethod': opts.statusCallbackMethod }); var promise = this._version.create({ uri: this._uri, method: 'POST', data: data }); promise = promise.then(function(payload) { deferred.resolve(new ValidationRequestInstance( this._version, payload )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; return ValidationRequestListInstance; } /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.ValidationRequestInstance * @description Initialize the ValidationRequestContext * * @property {string} accountSid - The account_sid * @property {string} phoneNumber - The phone_number * @property {string} friendlyName - The friendly_name * @property {number} validationCode - The validation_code * @property {string} callSid - The call_sid * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} payload - The instance payload */ /* jshint ignore:end */ function ValidationRequestInstance(version, payload, accountSid) { this._version = version; // Marshaled Properties this.accountSid = payload.account_sid; // jshint ignore:line this.phoneNumber = payload.phone_number; // jshint ignore:line this.friendlyName = payload.friendly_name; // jshint ignore:line this.validationCode = deserialize.integer(payload.validation_code); // jshint ignore:line this.callSid = payload.call_sid; // jshint ignore:line // Context this._context = undefined; this._solution = { accountSid: accountSid, }; } module.exports = { ValidationRequestPage: ValidationRequestPage, ValidationRequestList: ValidationRequestList, ValidationRequestInstance: ValidationRequestInstance, ValidationRequestContext: ValidationRequestContext };
/** * Simple function to set the focus to the element with autofocus in the dialog template * @param templateInstance */ Dialog = {}; Dialog.autoFocus = function(templateInstance) { templateInstance.$('.modal').first().on('shown.bs.modal', function () { templateInstance.$('[autofocus]').focus(); }); }
import { t } from '../../../polyglot-modules/polyglot.js' import Github from '../components/Github' const data = [0, 1] const data2 = [0] const items = [0, 1, 2, 3,4] const DemocracyOs = () => ( <div className='democracy-os-container'> <img src={t('what-we-do.democracyOs.img')} alt='Democracy OS' className='democracy-os-logo'/> <div className='democracy-os-text'> {data.map((i)=> { return <p key={i}>{t(`what-we-do.democracyOs.text.${i}`)}</p> })} </div> <ul className='democracy-os-list'> {items.map((i)=>{ return <li key={i}>{t(`what-we-do.democracyOs.list.${i}`)}</li> })} </ul> <div className='democracy-os-text'> {data2.map((i)=> { return <p key={i}>{t(`what-we-do.democracyOs.text-2.${i}`)}</p> })} </div> <div className='buttons-container'> <a href={t('what-we-do.democracyOs.repourl')} target='_blank' rel='external'> <button className='btn'> <Github /> <span className='action-text'>{t('what-we-do.democracyOs.repo')}</span> </button> </a> <a href={t('what-we-do.democracyOs.href')} target='_blank' rel='external'> <button className='btn'> <span className='action-text'>{t('what-we-do.democracyOs.callToAction')}</span> </button> </a> </div> <style jsx>{` .democracy-os-container { align-items: center; display: flex; flex-direction: column; justify-content: center; padding-bottom: 100px; padding-top: 100px; } .democracy-os-logo { margin-bottom: 38px; } p{ font-size: 2rem; letter-spacing: 0.13rem; text-align: center; } p:nth-child(2) { margin: 40px 0; } .democracy-os-list { list-style: disc; font-size: 2.0rem; letter-spacing: 0.13rem; padding-bottom:3rem; } .buttons-container { display: flex; flex-wrap: wrap; justify-content: space-between; margin-top: 45px; width: 511px; } .btn { margin-top: -3px; } @media (max-width: 768px) { .democracy-os-list { margin-left: 24px; margin-right: 0; } } @media (min-width: 1441px) { .democracy-os-text, .democracy-os-list { max-width: 1270px; } } @media (max-width: 520px) { .buttons-container { align-items: center; flex-direction: column; width: 100%; } .buttons-container .btn:first-child { margin-bottom: 20px; } } @media (max-width: 375px) { .democracy-os-logo { width: 300px; } } `}</style> </div> ) export default DemocracyOs
userIndex *= 123
var React = require('react'); module.exports = React.createClass({ render() { return ( <div className="item-title-row"> {this.props.children} </div> ); } });
/** * Select2 Georgian (Kartuli) translation. * * Author: Dimitri Kurashvili dimakura@gmail.com */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "ვერ მოიძებნა"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "გთხოვთ შეიყვანოთ კიდევ " + n + " სიმბოლო"; }, formatInputTooLong: function (input, max) { var n = input.length - max; return "გთხოვთ წაშალოთ " + n + " სიმბოლო"; }, formatSelectionTooBig: function (limit) { return "თქვენ შეგიძლიათ მხოლოდ " + limit + " ჩანაწერის მონიშვნა"; }, formatLoadMore: function (pageNumber) { return "შედეგის ჩატვირთვა…"; }, formatSearching: function () { return "ძებნა…"; } }); })(jQuery);
import Popper from "popper.js" export class InfoBox { constructor(container) { this._container = container; this._initGui(); } _updatePosition(selector=null, popperOptions={}) { if (selector) { let referenceTag = document.querySelector( selector ); var options = Object.assign({ gpuAcceleration: false, placement: "bottom", flipBehavior: ["right", "bottom", "top"] // offset: 60, // boundariesPadding: 100, // boundariesElement: document.querySelector("body"), }, popperOptions); if (!this._popper) { this._popper = new Popper( referenceTag, this._tag, options ); } else { Object.assign(this._popper._options, options); this._popper._reference = referenceTag; this._popper.update(); } return this._popper._getOffsets(this._popper._popper, this._popper._reference, this._popper._options.placement); } const centerTag = document.querySelector("#maindiv"); const clientHeight = this._tag.clientHeight || 0, clientWidth = this._tag.clientWidth || 0, innerWidth = window.innerWidth || document.documentElement.clientWidth || 0, innerHeight = window.innerHeight || document.documentElement.clientHeight || 0; // console.log(`${clientHeight} ${clientWidth} ${innerWidth} ${innerHeight}`); this._tag.style.left = (innerWidth / 2 - clientWidth / 2) + "px"; this._tag.style.top = (innerHeight / 2 - clientHeight / 2) + "px"; return null; } updateGui(title, description, selector=null, popperOptions={}) { var header = this._tag.querySelector(".ig-infobox-header"); if (header.childNodes.length) { header.removeChild( header.childNodes[0] ); } header.appendChild( document.createTextNode(title) ); var section = this._tag.querySelector(".ig-infobox-section"); if (section.childNodes.length) { section.removeChild( section.childNodes[0] ); } section.appendChild( document.createTextNode(description) ); return this._updatePosition( selector, popperOptions ); } _initGui() { this._tag = document.createElement("div"); this._tag.id = "ig-infobox"; this._tag.className = "ig-infobox"; let header = document.createElement("h3"); header.className = "ig-infobox-header"; let section = document.createElement("section"); section.className = "ig-infobox-section"; this._tag.appendChild(header); this._tag.appendChild(section); this._container.appendChild(this._tag); } }
/** * Myjson API bridge * Database in [http://myjson.com/5953q] */ var MyjsonBridge = new Sgfd.Bridge({ metaName: 'MyjsonBridge', type: 'json', base: 'https://api.myjson.com/bins', paths: { all: '5953q', }, bridgeTo: (to) => { with (MyjsonBridge) { return base + '/' + paths[to] } } })
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'EQUINOX', classes: 'home' }); }); /* GET clubs page. */ router.get('/clubs', function(req, res) { res.render('clubs', { title: 'EQUINOX | Fitness Clubs', classes: 'clubs' }); }); /* GET clubs region page. */ router.get('/clubs/:region', function(req, res) { res.render('region', { title: 'EQUINOX | Fitness Clubs Region', classes: 'clubs clubs-region', urlName: req.params.region }); }); /* GET club page. */ router.get('/clubs/:region/:club', function(req, res) { res.render('club', { title: 'EQUINOX | Fitness Club', classes: 'club-detail', urlName: req.params.club }); }); router.get('/clubs/:region/:subregion/:club', function(req, res) { res.render('club', { title: 'EQUINOX | Fitness Club', classes: 'club-detail', urlName: req.params.club }); }); module.exports = router;
// @flow import { getGameById } from 'api/models/game' const game = async (_: any, args: { id: string }, _ctx: Object) => { const { id } = args return getGameById(id) } export default game
PagesTrainsView = Backbone.View.extend({ events: { }, initialize: function () { this.trains = $('#data').data('response'); this.render(); }, render: function () { this.$el.html(render('pages/trains', { trains: this.trains })); } });
// @flow import { SurveySubmission } from './ActionTypes'; import callAPI from 'app/actions/callAPI'; import { surveySubmissionSchema } from 'app/reducers'; import type { Thunk } from 'app/types'; export function fetchSubmissions(surveyId: number): Thunk<*> { return callAPI({ types: SurveySubmission.FETCH_ALL, endpoint: `/surveys/${surveyId}/submissions/`, schema: [surveySubmissionSchema], meta: { errorMessage: 'Henting av svar på spørreundersøkelse feilet', }, propagateError: true, }); } export function fetchUserSubmission( surveyId: number, user: number ): Thunk<any> { return callAPI({ types: SurveySubmission.FETCH, endpoint: `/surveys/${surveyId}/submissions/?user=${user}`, method: 'GET', schema: [surveySubmissionSchema], meta: { surveyId, user, errorMessage: 'Noe gikk galt i sjekking av hvorvidt brukeren allerede har svart', }, }); } export function addSubmission({ surveyId, ...data }: Object): Thunk<*> { return callAPI({ types: SurveySubmission.ADD, endpoint: `/surveys/${surveyId}/submissions/`, method: 'POST', body: data, schema: surveySubmissionSchema, meta: { errorMessage: 'Legg til svar feilet', successMessage: 'Undersøkelse besvart!', surveyId, }, }); } export function deleteSubmission( surveyId: number, submissionId: number ): Thunk<any> { return callAPI({ types: SurveySubmission.DELETE, endpoint: `/surveys/${surveyId}/submissions/${submissionId}/`, method: 'DELETE', meta: { surveyId, id: submissionId, errorMessage: 'Sletting av svar feilet', successMessage: 'Svar slettet.', }, }); } export function hideAnswer( surveyId: number, submissionId: number, answerId: number ): Thunk<any> { return callAPI({ types: SurveySubmission.HIDE_ANSWER, endpoint: `/surveys/${surveyId}/submissions/${submissionId}/hide/?answer=${answerId}`, schema: surveySubmissionSchema, method: 'POST', meta: { surveyId, submissionId, answerId, errorMessage: 'Skjuling av kommentar feilet', successMessage: 'Kommentar skjult.', }, }); } export function showAnswer( surveyId: number, submissionId: number, answerId: number ): Thunk<any> { return callAPI({ types: SurveySubmission.SHOW_ANSWER, endpoint: `/surveys/${surveyId}/submissions/${submissionId}/show/?answer=${answerId}`, schema: surveySubmissionSchema, method: 'POST', meta: { surveyId, submissionId, answerId, errorMessage: 'Avslutning av skjuling feilet', successMessage: 'Skjuling av kommentar avsluttet.', }, }); }
"use strict"; const IconTables = require("../../icons/icon-tables.js"); const Strategy = require("../strategy.js"); class PathStrategy extends Strategy { constructor(){ super({ priority: 1, matchesFiles: true, matchesDirs: true, noSetting: true, ignoreVirtual: false, }); } registerResource(resource){ if(super.registerResource(resource)){ const disposables = this.resourceEvents.get(resource); disposables.add(resource.onDidMove(() => this.check(resource, false))); this.resourceEvents.set(resource, disposables); return true; } else return false; } matchIcon(resource){ let icon = null; if(resource.isDirectory) return icon = IconTables.matchPath(resource.path, true) || IconTables.matchName(resource.name, true) || null; else{ let {name} = resource; let path = resource.realPath || resource.path; let isFiltered = false; const filtered = this.filter(name) || name; if(filtered !== name){ isFiltered = true; name = filtered; path = this.filter(path); } icon = IconTables.matchPath(path) || IconTables.matchName(name) || null; if(isFiltered && (null === icon || icon.priority < 1)) icon = IconTables.matchName(resource.name); return icon || null; } } filter(path){ return path .replace(/~(?:orig|previous)$/, "") .replace(/^([^.]*\.[^.]+)\.(?:inc?|dist|tm?pl|te?mp|ti?dy)$/i, "$1"); } } module.exports = new PathStrategy();
/*!banner: c6896d8a*/var a = function() { return true; }; /*!c6896d8a*/
import mongoose from 'mongoose'; import express from 'express'; import session from 'express-session'; import bodyParser from 'body-parser'; import config from '../src/config'; import * as actions from './actions/index'; import {mapUrl} from 'utils/url.js'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; const pretty = new PrettyError(); const app = express(); const server = new http.Server(app); const io = new SocketIo(server); io.path('/ws'); app.use(session({ secret: 'react and redux rule!!!!', resave: false, saveUninitialized: false, cookie: { maxAge: 60000 } })); app.use(bodyParser.json()); app.use((req, res) => { const splittedUrlPath = req.url.split('?')[0].split('/').slice(1); const {action, params} = mapUrl(actions, splittedUrlPath); if (action) { action(req, params) .then((result) => { if (result instanceof Function) { result(res); } else { res.json(result); } }, (reason) => { if (reason && reason.redirect) { res.redirect(reason.redirect); } else { console.error('API ERROR:', pretty.render(reason)); res.status(reason.status || 500).json(reason); } }); } else { res.status(404).end('NOT FOUND'); } }); // MONGO DB let maxRetries = 5; let retries = 0; function connect() { mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://heroku_pjg80b3j:egrn9o86an0ktpgcjqkvn3vi6h@ds023603.mlab.com:23603/heroku_pjg80b3j'); } // Error handler mongoose.connection.on('error', (err) => { console.info('Mongo Error: ' + err); }); // Error handler mongoose.connection.on('connected', () => { console.info('==> 💻Mongo connected'); }); // Reconnect when closed mongoose.connection.on('disconnected', () => { console.log('Mongo disconnected'); if (retries < maxRetries) { connect(); retries++; } }); connect(); // SOCKET const bufferSize = 100; const messageBuffer = new Array(bufferSize); let messageIndex = 0; if (config.apiPort) { const runnable = app.listen(config.apiPort, (err) => { if (err) { console.error(err); } console.info('----\n==> 🌎 API is running on port %s', config.apiPort); console.info('==> 💻 Send requests to http://%s:%s', config.apiHost, config.apiPort); }); io.on('connection', (socket) => { socket.emit('news', {msg: `'Hello World!' from server`}); socket.on('history', () => { for (let index = 0; index < bufferSize; index++) { const msgNo = (messageIndex + index) % bufferSize; const msg = messageBuffer[msgNo]; if (msg) { socket.emit('msg', msg); } } }); socket.on('msg', (data) => { data.id = messageIndex; messageBuffer[messageIndex % bufferSize] = data; messageIndex++; io.emit('msg', data); }); }); io.listen(runnable); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
const assert = chai.assert; const Workbook = xmind.Workbook; const options = { firstSheetId: 'firstSheet', rootTopicId: 'rootTopic', firstSheetName: 'sheet 1', rootTopicName: 'root topic' }; const workbook = new Workbook(options); // first sheet added const sheet = workbook.getPrimarySheet(); const rootTopic = sheet.rootTopic; const secondTopicOptions = { id: 'secondTopic', title: 'second topic' }; rootTopic.addChild(secondTopicOptions); const thirdTopicOptions = { id: 'thirdTopic', title: 'third topic' }; rootTopic.addChild(thirdTopicOptions); const relationship = sheet.addRelationship({ sourceId: options.rootTopicId, targetId: secondTopicOptions.id }); describe('Relationship', () => { it('relationship.getSource()', () => { assert.equal( relationship.getSource(), options.rootTopicId, 'relationship.getSource() not working: sourceId not correct' ); }); it('relationship.setSource(value)', () => { assert.doesNotThrow(() => { relationship.setSource(thirdTopicOptions.id); }, 'failed to execute relationship.setSource(value)'); assert.equal( relationship.getSource(), thirdTopicOptions.id, 'relationship.setSource(value) not working: source not correct' ); assert.throws(() => { relationship.setSource(secondTopicOptions.id); }, 'source & target should not be the same'); }); it('relationship.getTarget()', () => { assert.equal( relationship.getTarget(), secondTopicOptions.id, 'relationship.getTarget() not working: targetId not correct' ); }); it('relationship.setTarget(value)', () => { assert.doesNotThrow(() => { relationship.setTarget(options.rootTopicId); }, 'failed to execute relationship.setTarget(value)'); assert.equal( relationship.getTarget(), options.rootTopicId, 'relationship.setTarget(value) not working: target not correct' ); assert.throws(() => { relationship.setTarget(thirdTopicOptions.id); }, 'source & target should not be the same'); }); it('relationship.getTitle()', () => { assert.equal( relationship.getTitle(), '', 'relationship.getTitle() not working: title not correct' ); }); it('relationship.setTitle(value)', () => { const title = 'strange relationship'; assert.doesNotThrow(() => { relationship.setTitle(title); }, 'failed to execute relationship.setTitle(value)'); assert.equal( relationship.getTitle(), title, 'relationship.setTitle(value) not working: title not correct' ); }); it('relationship.toPlainObject()', () => { relationship.setModifiedTime(1); assert.deepEqual( relationship.toPlainObject(), { id: relationship.id, sheetId: sheet.id, sourceId: relationship.getSource(), targetId: relationship.getTarget(), modifiedTime: 1, title: relationship.getTitle() }, 'relationship.setTitle(value) not working: title not correct' ); }); });
export { default } from 'ember-fhir/models/process-response';
function solve() { return function (selector, isCaseSensitive) { isCaseSensitive = isCaseSensitive || false; // Creating the structure var root = document.querySelector(selector); root.className += ' items-control'; var addControls = document.createElement('div'); var searchControls = addControls.cloneNode(true); var resultControls = addControls.cloneNode(true); var itemsList = addControls.cloneNode(true); addControls.className += ' add-controls'; searchControls.className += ' search-controls'; resultControls.className += ' result-controls'; var addInput = document.createElement('input'); var addButton = document.createElement('button'); var searchInput = addInput.cloneNode(true); addButton.innerHTML = 'Add'; addButton.className += ' button'; addControls.innerHTML += 'Enter text'; addControls.appendChild(addInput); addControls.appendChild(addButton); searchControls.innerHTML += 'Search'; searchControls.appendChild(searchInput); itemsList.className += ' items-list'; resultControls.appendChild(itemsList); // Adding event listeners addButton.addEventListener('click', function (e) { var text = document.createElement('h3'); text.innerHTML = addInput.value; var listItem = document.createElement('div'); listItem.className += ' list-item'; var xButton = addButton.cloneNode(true); xButton.innerHTML = 'X'; listItem.appendChild(xButton); listItem.appendChild(text); itemsList.appendChild(listItem); }); resultControls.addEventListener('click', function (e) { var target = e.target; if(target.tagName === 'BUTTON') { var parent = target.parentNode; parent.parentNode.removeChild(parent); } }); var items = resultControls.getElementsByClassName('list-item'); searchInput.addEventListener('input', function (e) { var text = e.target.value; for(var i = 0, len = items.length; i < len; i += 1) { var itemText = items[i].getElementsByTagName('h3')[0].innerHTML; if(!isCaseSensitive) { text = text.toLowerCase(); itemText = itemText.toLowerCase(); //console.log(text); } if(itemText.indexOf(text) === -1) { items[i].style.display = 'none'; } else { items[i].style.display = ''; } } }); root.appendChild(addControls); root.appendChild(searchControls); root.appendChild(resultControls); }; } module.exports = solve;
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('value-set-expansion', 'Unit | Model | ValueSet_Expansion', { needs: [ 'model:meta', 'model:narrative', 'model:resource', 'model:extension', 'model:value-set-parameter', 'model:value-set-contains', 'model:value-set-contain' ] }); test('it exists', function(assert) { const model = this.subject(); assert.ok(!!model); });
'use strict'; const express = require('express'); const User = require('../model/user'); const jwtAuth = require('../lib/jwt'); const userRouter = module.exports = exports = express.Router(); userRouter.get('/:id/', jwtAuth, (req, res, next) => { User.findOne({_id: req.params.id}, (err, user) => { user.password = null; if (err || !user) return next(err); res.json(user); }); }); userRouter.delete('/:id', jwtAuth, (req, res, next) => { let _id = req.params.id; User.findOneAndRemove({_id}, (err, user) => { if(err || !user) return next(err); let message = 'successfully deleted'; res.json({message}); }); });
import 'aurelia-polyfills'; import { Options } from 'aurelia-loader-nodejs'; import { globalize } from 'aurelia-pal-nodejs'; import * as path from 'path'; Options.relativeToDir = path.join(__dirname, 'unit'); globalize(); //# sourceMappingURL=jest-pretest.js.map
define(['dispatcher'], function(dispatcher) { "use strict"; var initialized = false; var step1counter = 0; var step2counter = 0; var step1total = 2; var step2total = 3; var step1ready = false; var step2ready = false; var animation = false; var scheme = 'light'; var pageNameId = false; var text = ''; var projectText = ''; var color = 'ffffff'; var id = false; var _handleEvent = function(e) { if (e.type === 'transition-step-1') { step1counter++; if (e.hasOwnProperty('animation') && e.animation !== false) { animation = e.animation; } if (e.hasOwnProperty('id') && e.id !== false) { id = e.id; } if (step1counter >= step1total) { step1ready = true; eventEmitter.dispatch(); } } if (e.type === 'transition-step-2') { if (step1counter < step1total) return; step2counter++; if (e.hasOwnProperty('animation') && e.animation !== false) { animation = e.animation; } if (e.hasOwnProperty('scheme') && e.scheme !== false) { scheme = e.scheme; } if (e.hasOwnProperty('pageNameId') && e.pageNameId !== false) { pageNameId = e.pageNameId; } if (e.hasOwnProperty('text') && e.pageNameId !== text) { text = e.text; } if (e.hasOwnProperty('color') && e.color !== false) { color = e.color; } if (e.hasOwnProperty('projectText') && e.projectText !== false) { projectText = e.projectText; } if (e.hasOwnProperty('id') && e.id !== false) { id = e.id; } if (step2counter >= step2total) { step2ready = true; eventEmitter.dispatch(); } } if (e.type === 'transition-step-reset') { step1counter = 0; step2counter = 0; step1ready = false; step2ready = false; animation = false; scheme = 'light'; text = ''; projectText = ''; color = 'ffffff'; pageNameId = false; id = false; } } var _init = function() { dispatcher.subscribe(_handleEvent); } var eventEmitter = function() { var _handlers = []; var dispatch = function(event) { for (var i = _handlers.length - 1; i >= 0; i--) { _handlers[i](event); } } var subscribe = function(handler) { _handlers.push(handler); } var unsubscribe = function(handler) { for (var i = 0; i <= _handlers.length - 1; i++) { if (_handlers[i] == handler) { _handlers.splice(i--, 1); } } } return { dispatch: dispatch, subscribe: subscribe, unsubscribe: unsubscribe } }(); var getData = function() { return { step1ready: step1ready, step2ready: step2ready, animation: animation, scheme: scheme, pageNameId: pageNameId, text: text, color: color, projectText: projectText } } if (!initialized) { initialized = true; _init(); } return { eventEmitter: eventEmitter, getData: getData } });
/*global html,isHostMethod */ /* Description: Relies on W3C compliant `e.stopPropagation()` */ /* Degrades: IE8, IE7, IE6, IE5.5, IE5, IE4, IE3, Opera 7.6 */ /* Author: Adam Silver */ var cancelPropagation; if(html && isHostMethod(html, 'addEventListener')) { cancelPropagation = function(e) { e.stopPropagation(); }; }
/** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var egret; (function (egret) { var gui; (function (gui) { /** * @class egret.gui.ListEvent * @classdesc * 列表事件 * @extends egret.TouchEvent */ var ListEvent = (function (_super) { __extends(ListEvent, _super); /** * @method egret.gui.ListEvent#constructor * @param type {string} * @param bubbles {boolean} * @param cancelable {boolean} * @param touchPointID {number} * @param stageX {number} * @param stageY {number} * @param ctrlKey {boolean} * @param altKey {boolean} * @param shiftKey {boolean} * @param buttonDown {boolean} * @param itemIndex {number} * @param item {any} * @param itemRenderer {IItemRenderer} */ function ListEvent(type, bubbles, cancelable, touchPointID, stageX, stageY, ctrlKey, altKey, shiftKey, buttonDown, itemIndex, item, itemRenderer) { if (bubbles === void 0) { bubbles = true; } if (cancelable === void 0) { cancelable = true; } if (touchPointID === void 0) { touchPointID = 0; } if (stageX === void 0) { stageX = 0; } if (stageY === void 0) { stageY = 0; } if (ctrlKey === void 0) { ctrlKey = false; } if (altKey === void 0) { altKey = false; } if (shiftKey === void 0) { shiftKey = false; } if (buttonDown === void 0) { buttonDown = false; } if (itemIndex === void 0) { itemIndex = -1; } if (item === void 0) { item = null; } if (itemRenderer === void 0) { itemRenderer = null; } _super.call(this, type, bubbles, cancelable, touchPointID, stageX, stageY, ctrlKey, altKey, shiftKey, buttonDown); /** * 触发鼠标事件的项呈示器数据源项。 * @member egret.gui.ListEvent#item */ this.item = null; /** * 触发鼠标事件的项呈示器。 * @member egret.gui.ListEvent#itemRenderer */ this.itemRenderer = null; /** * 触发鼠标事件的项索引 * @member egret.gui.ListEvent#itemIndex */ this.itemIndex = NaN; this.itemIndex = itemIndex; this.item = item; this.itemRenderer = itemRenderer; } /** * 使用指定的EventDispatcher对象来抛出事件对象。抛出的对象将会缓存在对象池上,供下次循环复用。 * @method egret.gui.ListEvent.dispatchListEvent */ ListEvent.dispatchListEvent = function (target, type, touchEvent, itemIndex, item, itemRenderer) { if (touchEvent === void 0) { touchEvent = null; } if (itemIndex === void 0) { itemIndex = -1; } if (item === void 0) { item = null; } if (itemRenderer === void 0) { itemRenderer = null; } var eventClass = ListEvent; var props = egret.Event._getPropertyData(eventClass); props.touchPointID = touchEvent.touchPointID; props._stageX = touchEvent.stageX; props._stageY = touchEvent.stageY; props.ctrlKey = touchEvent.ctrlKey; props.altKey = touchEvent.altKey; props.shiftKey = touchEvent.shiftKey; props.touchDown = touchEvent.touchDown; props.itemIndex = itemIndex; props.item = item; props.itemRenderer = itemRenderer; egret.Event._dispatchByTarget(eventClass, target, type, props); }; /** * 指示用户执行了将鼠标指针从控件中某个项呈示器上移开的操作 * @constant egret.gui.ListEvent.ITEM_ROLL_OUT */ ListEvent.ITEM_ROLL_OUT = "itemRollOut"; /** * 指示用户执行了将鼠标指针滑过控件中某个项呈示器的操作。 * @constant egret.gui.ListEvent.ITEM_ROLL_OVER */ ListEvent.ITEM_ROLL_OVER = "itemRollOver"; /** * 指示用户执行了将鼠标在某个项呈示器上单击的操作。 * @constant egret.gui.ListEvent.ITEM_CLICK */ ListEvent.ITEM_CLICK = "itemClick"; return ListEvent; })(egret.TouchEvent); gui.ListEvent = ListEvent; ListEvent.prototype.__class__ = "egret.gui.ListEvent"; })(gui = egret.gui || (egret.gui = {})); })(egret || (egret = {}));
import { $, getStyle, isVoidElement, promise } from '../util/index'; var storage = window.sessionStorage || {}, svgs = {}, parser = new DOMParser(); export default function (UIkit) { UIkit.component('svg', { props: { id: String, icon: String, src: String, class: String, style: String, width: Number, height: Number, ratio: Number }, defaults: { ratio: 1, id: false, class: '', exclude: ['src'] }, init() { this.class += ' uk-svg'; }, connected() { this.svg = promise((resolve, reject) => { this._resolver = resolve; this._rejecter = reject; }).catch(() => {}); this.$emitSync(); }, disconnected() { this.isSet = false; if (isVoidElement(this.$el)) { this.$el.attr({hidden: null, id: this.id || null}); } if (this.svg) { this.svg.then(svg => svg && svg.remove()); this.svg = null; } }, update: { read() { if (!this.src) { this.src = getSrc(this.$el); } if (!this.src || this.isSet) { return; } this.isSet = true; if (!this.icon && ~this.src.indexOf('#')) { var parts = this.src.split('#'); if (parts.length > 1) { this.src = parts[0]; this.icon = parts[1]; } } getSvg(this.src).then(doc => { this._svg = doc; this.$emit(); }, e => console.log(e)); }, write() { if (!this._svg) { return; } var doc = this._svg, svg, el; this._svg = null; if (!this.icon) { el = doc.documentElement.cloneNode(true); } else { svg = doc.getElementById(this.icon); if (!svg) { // fallback if SVG has no symbols if (!doc.querySelector('symbol')) { el = doc.documentElement.cloneNode(true); } } else { var html = svg.outerHTML; // IE workaround if (!html) { var div = document.createElement('div'); div.appendChild(svg.cloneNode(true)); html = div.innerHTML; } html = html .replace(/<symbol/g, `<svg${!~html.indexOf('xmlns') ? ' xmlns="http://www.w3.org/2000/svg"' : ''}`) .replace(/symbol>/g, 'svg>'); el = parser.parseFromString(html, 'image/svg+xml').documentElement; } } if (!el) { this._rejecter('SVG not found.'); return; } var dimensions = el.getAttribute('viewBox'); // jQuery workaround, el.attr('viewBox') if (dimensions) { dimensions = dimensions.split(' '); this.width = this.width || dimensions[2]; this.height = this.height || dimensions[3]; } el = $(el); this.width *= this.ratio; this.height *= this.ratio; for (var prop in this.$options.props) { if (this[prop] && !~this.exclude.indexOf(prop)) { el.attr(prop, this[prop]); } } if (!this.id) { el.removeAttr('id'); } if (this.width && !this.height) { el.removeAttr('height'); } if (this.height && !this.width) { el.removeAttr('width'); } if (isVoidElement(this.$el) || this.$el[0].tagName === 'CANVAS') { this.$el.attr({hidden: true, id: null}); el.insertAfter(this.$el); } else { el.appendTo(this.$el); } this._resolver(el); }, events: ['load'] } }); function getSrc(el) { var image = getBackgroundImage(el); if (!image) { el = el.clone().empty() .attr({'uk-no-boot': '', style: `${el.attr('style')};display:block !important;`}) .appendTo(document.body); image = getBackgroundImage(el); // safari workaround if (!image && el[0].tagName === 'CANVAS') { var span = $(el[0].outerHTML.replace(/canvas/g, 'span')).insertAfter(el); image = getBackgroundImage(span); span.remove(); } el.remove(); } return image && image.slice(4, -1).replace(/"/g, ''); } function getBackgroundImage(el) { var image = getStyle(el[0], 'backgroundImage', '::before'); return image !== 'none' && image; } function getSvg(src) { if (!svgs[src]) { svgs[src] = promise((resolve, reject) => { if (src.lastIndexOf('data:', 0) === 0) { resolve(parse(decodeURIComponent(src.split(',')[1]))); } else { var key = `${UIkit.data}${UIkit.version}_${src}`; if (storage[key]) { resolve(parse(storage[key])); } else { $.ajax(src, {dataType: 'html'}).then(doc => { storage[key] = doc; resolve(parse(doc)); }, () => { reject('SVG not found.'); }); } } }); } return svgs[src]; } function parse(doc) { return parser.parseFromString(doc, 'image/svg+xml'); } // workaround for Safari's private browsing mode try { var key = `${UIkit.data}test`; storage[key] = 1; delete storage[key]; } catch (e) { storage = {}; } }
'use strict'; /** * @param {*} subject * @param {*} target * @returns {Boolean} */ module.exports.isStrictlyEqual = function (subject, target) { return subject === target; }; /** * @param {*} subject * @param {*} target * @returns {Boolean} */ module.exports.isEqual = function (subject, target) { return subject == target; }; /** * @param {*} subject * @param {*} target * @returns {Boolean} */ module.exports.isStrictlyNotEqual = function (subject, target) { return subject !== target; }; /** * @param {*} subject * @param {*} target * @returns {Boolean} */ module.exports.isNotEqual = function (subject, target) { return subject != target; };
const initialState = { client: { state: { tool: 'move', color: '#222222', size: 4, opacity: 1 }, x: 0, y: 0, m1Down: false, offsetX: 0, offsetY: 0, points: [], pointCount: 0 }, clientStates: {} /* network clients */ } export function udrawAppReducer(state, action) { if (typeof state === 'undefined') { return initialState } // For now, don’t handle any actions // and just return the state given to us. return state }
'use strict'; /** * Module dependencies. */ var assert = require('assert'); var includes = require('../'); /** * Detects and disables ES5-only tests in non-ES5 environments. */ var es5It = typeof Object.create === 'function' ? it : xit; /** * Tests. */ describe('includes', function() { it('should be a function', function() { assert(typeof includes === 'function'); }); it('should have an arity of 2', function() { assert(includes.length === 2); }); it('should work on arrays', function() { var numbers = [1, 2, 3]; assert(includes(1, numbers) === true); assert(includes(2, numbers) === true); assert(includes(3, numbers) === true); assert(includes(0, numbers) === false); }); it('should work on objects', function() { var person = { name: 'Bob', age: 23 }; assert(includes(23, person) === true); assert(includes('Bob', person) === true); assert(includes('name', person) === false); }); it('should work on strings', function() { var string = 'xyz for y o u'; assert(includes('you', string) === false); assert(includes('or y', string) === true); }); es5It('should ignore inherited properties', function() { var parent = { ignore: 'zyx' }; var child = Object.create(parent); child.a = 'aaa'; child.b = 'bbb'; child.c = 'ccc'; assert(includes('aaa', child) === true); assert(includes('bbb', child) === true); assert(includes('ccc', child) === true); assert(includes('zyx', child) === false); }); es5It('should ignore non-enumerable properties', function() { var secrets = Object.create({}, { notSecret: { value: 'not a secret', enumerable: true }, secret: { value: 'secret', enumerable: false } }); assert(includes('not a secret', secrets) === true); assert(includes('secret', secrets) === false); }); });
/*! * 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.ui.ux3.ExactAttribute. sap.ui.define(['jquery.sap.global', 'sap/ui/core/Element', './library'], function(jQuery, Element, library) { "use strict"; /** * Constructor for a new ExactAttribute. * * @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 * An element for defining attributes and sub-attributes used within the Exact pattern. * @extends sap.ui.core.Element * * @author SAP SE * @version 1.38.4 * * @constructor * @public * @deprecated Since version 1.38. * @alias sap.ui.ux3.ExactAttribute * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ExactAttribute = Element.extend("sap.ui.ux3.ExactAttribute", /** @lends sap.ui.ux3.ExactAttribute.prototype */ { metadata : { library : "sap.ui.ux3", properties : { /** * The attribute name */ text : {type : "string", group : "Misc", defaultValue : null}, /** * Specifies whether the attribute shall be selected */ selected : {type : "boolean", group : "Misc", defaultValue : null}, /** * Specifies the width of the corresponding list in pixels. The value must be between 70 and 500. * @since 1.7.0 */ width : {type : "int", group : "Misc", defaultValue : 168}, /** * The order how the sublists of this attribute should be displayed. * @since 1.7.1 */ listOrder : {type : "sap.ui.ux3.ExactOrder", defaultValue : sap.ui.ux3.ExactOrder.Select}, /** * Specifies whether the attribute shall have sub values for visual purposes. * The indicator which is a little arrow beside an attribute in the list is computed automatically * (getShowSubAttributesIndicator_Computed() of sap.ui.ux3.ExactAttribute). * In the case that a supply function is attached, and the supplyActive attribute has value 'true', * then the Exact pattern needs a hint if sub attributes are available. The showSubAttributesIndicator attribute is * considered then and has to be maintained. If the back-end does not support count-calls, for example, * showSubAttributesIndicator should be set to true. */ showSubAttributesIndicator : {type : "boolean", group : "Misc", defaultValue : true}, /** * An example for additional data are database keys */ additionalData : {type : "object", group : "Misc", defaultValue : null}, /** * The supplyAttributes event is only fired if supplyActive has value true which is the default. After firing the event, the attribute is automatically set to false. * The idea is that a supply function is called only once when the data is requested. To enable the event again it is possible to manually set the attribute back to true. */ supplyActive : {type : "boolean", group : "Misc", defaultValue : true}, /** * If you want the supply function to be called on every select, you can set the autoActivateSupply attribute to true. In this case, supplyActive is automatically * set to true on every unselect. */ autoActivateSupply : {type : "boolean", group : "Misc", defaultValue : false} }, defaultAggregation : "attributes", aggregations : { /** * Values (sub attributes) of this attribute */ attributes : {type : "sap.ui.ux3.ExactAttribute", multiple : true, singularName : "attribute"} }, events : { /** * A supply function is a handler which is attached to the supplyAttributes event. The event is fired when the corresponding ExactAttribute is selected, it was already selected when a handler is attached or function getAttributes() is called. */ supplyAttributes : { parameters : { /** * The ExactAttribute */ attribute : {type : "sap.ui.ux3.ExactAttribute"} } } } }}); (function() { ExactAttribute._MINWIDTH = 70; ExactAttribute._MAXWIDTH = 500; ExactAttribute.prototype.onInit = function (){ this._getAttributesCallCount = 0; }; /** * Scrolls the corresponding list of this attribute until the given direct child attribute is visible. If the corresponding list is not yet visible the call is buffered until the list is available. * * @param {sap.ui.ux3.ExactAttribute} oOAttribute * The direct child attribute * @type void * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ ExactAttribute.prototype.scrollTo = function(oAttribute) { if (!(oAttribute instanceof ExactAttribute)) { this._scrollToAttributeId = undefined; return; } var oList = this.getChangeListener(); if (oList) { oList = sap.ui.getCore().byId(oList.id); if (oList && oList._lb) { var iIdx = this.indexOfAttribute(oAttribute); if (iIdx >= 0) { oList._lb.scrollToIndex(iIdx, true); } this._scrollToAttributeId = undefined; return; } } this._scrollToAttributeId = oAttribute.getId(); }; //*** Overridden API functions *** ExactAttribute.prototype.setText = function(sText) { this.setProperty("text", sText, true); this._handleChange(this, "text"); return this; }; ExactAttribute.prototype.setWidth = function(iWidth) { this._setWidth(iWidth); this._handleChange(this, "width"); return this; }; /** * @param {string|sap.ui.core.TooltipBase} oTooltip * @see sap.ui.core.Element.prototype.setTooltip * @public */ ExactAttribute.prototype.setTooltip = function(oTooltip) { Element.prototype.setTooltip.apply(this, arguments); this._handleChange(this, "tooltip", true); return this; }; ExactAttribute.prototype.setSelected = function(bSelected) { this.setProperty("selected", bSelected, true); if (!this.getSelected()) { this._clearSelection(); } this._handleChange(this, "selected"); return this; }; ExactAttribute.prototype.setSupplyActive = function(bSupplyActive) { this.setProperty("supplyActive", bSupplyActive, true); return this; }; ExactAttribute.prototype.setAutoActivateSupply = function(bAutoActivateSupply) { this.setProperty("autoActivateSupply", bAutoActivateSupply, true); return this; }; ExactAttribute.prototype.setAdditionalData = function(oAdditionalData) { this.setProperty("additionalData", oAdditionalData, true); return this; }; ExactAttribute.prototype.setListOrder = function(sListOrder) { this.setProperty("listOrder", sListOrder, true); this._handleChange(this, "order"); return this; }; ExactAttribute.prototype.getAttributes = function() { this._getAttributesCallCount++; if (this._getAttributesCallCount > 1){ this.setSupplyActive(false); } if (this.hasListeners("supplyAttributes") && this.getSupplyActive()) { this._bSuppressChange = true; this._bChangedHappenedDuringSuppress = false; this.fireSupplyAttributes({attribute: this}); this.setSupplyActive(false); this._bSuppressChange = undefined; if (this._bChangedHappenedDuringSuppress) { this._handleChange(this, "attributes"); } this._bChangedHappenedDuringSuppress = undefined; } this._getAttributesCallCount--; return this.getAttributesInternal(); }; ExactAttribute.prototype.insertAttribute = function(oAttribute, iIndex) { this.insertAggregation("attributes", oAttribute, iIndex, true); this._handleChange(this, "attributes"); this.setSupplyActive(false); return this; }; ExactAttribute.prototype.addAttribute = function(oAttribute) { this.addAggregation("attributes", oAttribute, true); this._handleChange(this, "attributes"); this.setSupplyActive(false); return this; }; ExactAttribute.prototype.removeAttribute = function(vElement) { var oAtt = this.removeAggregation("attributes", vElement, true); if (oAtt) { oAtt.setChangeListener(null); this._handleChange(this, "attributes"); } return oAtt; }; ExactAttribute.prototype.removeAllAttributes = function() { var aAtts = this.getAttributesInternal(); for (var idx = 0; idx < aAtts.length; idx++) { aAtts[idx].setChangeListener(null); } var aRes = this.removeAllAggregation("attributes", true); if (aAtts.length > 0) { this._handleChange(this, "attributes"); } return aRes; }; ExactAttribute.prototype.destroyAttributes = function() { var aAtts = this.getAttributesInternal(); for (var idx = 0; idx < aAtts.length; idx++) { aAtts[idx].setChangeListener(null); } this.destroyAggregation("attributes", true); if (aAtts.length > 0) { this._handleChange(this, "attributes"); } return this; }; /** * See attribute showSubAttributesIndicator * * @type void * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ ExactAttribute.prototype.getShowSubAttributesIndicator_Computed = function() { return this.hasListeners("supplyAttributes") && this.getSupplyActive() ? this.getShowSubAttributesIndicator() : this.getAttributesInternal().length > 0; }; ExactAttribute.prototype.attachSupplyAttributes = function(oData, fnFunction, oListener) { this.attachEvent("supplyAttributes", oData, fnFunction, oListener); if (this.getSelected()) { this.getAttributesInternal(true); //force init of attributes (e.g. call supply function)) } return this; }; //*** Internal (may also used by Exact Control) functions *** ExactAttribute.prototype._setProperty_Orig = ExactAttribute.prototype.setProperty; /** * @param {string} sPropertyName * @param {object} oValue * @param {boolean} bSuppressRerendering * @see sap.ui.core.Element.prototype.setProperty * @protected */ ExactAttribute.prototype.setProperty = function(sPropertyName, oValue, bSuppressRerendering) { this._setProperty_Orig(sPropertyName, oValue, bSuppressRerendering); if (sPropertyName == "selected") { if (oValue) { this.getAttributesInternal(true); //force init of attributes (e.g. call supply function) } else { if (this.getAutoActivateSupply()) { this.setSupplyActive(true); } } } return this; }; ExactAttribute.prototype.setChangeListener = function(oChangeListener) { this._oChangeListener = oChangeListener; }; ExactAttribute.prototype.getChangeListener = function(oChangeListener) { return this._oChangeListener; }; ExactAttribute.prototype.getAttributesInternal = function(bForceInit) { return bForceInit ? this.getAttributes() : this.getAggregation("attributes", []); }; ExactAttribute.prototype._handleChange = function(oSourceAttribute, sType) { if (this._bSuppressChange) { this._bChangedHappenedDuringSuppress = true; return; } if (this.getChangeListener()) { //Change is handled by the change listener this.getChangeListener()._notifyOnChange(sType, oSourceAttribute); } else if (this.getParent() && this.getParent()._handleChange) { //Bubble Change to next change listener this.getParent()._handleChange(oSourceAttribute, sType); } }; //Sets the selection property of the attribute and all its sub-attributes to false. ExactAttribute.prototype._clearSelection = function(){ this.setProperty("selected", false, true); var aVals = this.getAttributesInternal(); for (var idx = 0; idx < aVals.length; idx++) { aVals[idx]._clearSelection(); } }; //Setter of the width property without invalidate and change notification ExactAttribute.prototype._setWidth = function(iWidth) { iWidth = Math.round(ExactAttribute._checkWidth(iWidth)); this.setProperty("width", iWidth, true); }; //Checks whether the given width is within the allowed boundaries ExactAttribute._checkWidth = function(iWidth) { iWidth = Math.max(iWidth, ExactAttribute._MINWIDTH); iWidth = Math.min(iWidth, ExactAttribute._MAXWIDTH); return iWidth; }; }()); return ExactAttribute; }, /* bExport= */ true);
/*jslint plusplus: true, nomen: true, indent: 4 */ /*globals define */ define(function (require, exports, module) { 'use strict'; var AbstractCommand = require('./../../core/mvc/abstract-command'), Command = AbstractCommand.extend({}, { execute: function () {} }); module.exports = Command; });
const webpack = require("webpack"); const { serverConfig, clientConfig, outputMessages } = require("./webpack-config"); webpack([serverConfig, clientConfig]).run((err, stats) => { if (err) { console.log(err); } else { outputMessages(stats); } });
'use strict'; const tessel = require('tessel'), accelLib = require('accel-mma84'); let accel; const init = () => { initAccel(); }; const initAccel = () => { accel = accelLib.use(tessel.port['A']); accel.on('ready', accelReady); }; const accelReady = () => { accel.on('data', (xyz) => { console.log('x:', xyz[0].toFixed(2), 'y:', xyz[1].toFixed(2), 'z:', xyz[2].toFixed(2)); }); }; init();
import path from 'path'; // app export const APP = { NAME: 'xixi', SESSION_SECRET: 'xixi' }; // server export const SERVER = { PORT: 9876 }; export const SESSION = { SECRET: 'xixi' }; export const REDIS = { host: 'redis', port: '6379' }; // paths const LOG_DIR = path.resolve(__dirname, '../logs'); export const PATHS = { LOG_DIR, ERR_LOG: path.resolve(LOG_DIR, 'error.log'), INFO_LOG: path.resolve(LOG_DIR, 'info.log') };
#!/usr/bin/env node // // bin/fenearplayer.js // // The main fenear player cli entry point. // // Note that this file is in JavaScript because CoffeeScript is currently // unable to properly add hashbangs as this file has. // // Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com> // MIT Licensed // require('../lib/bin');
/* global QUnit */ import { runStdGeometryTests } from '../../utils/qunit-utils'; import { RingBufferGeometry } from '../../../../src/geometries/RingGeometry'; export default QUnit.module( 'Geometries', () => { QUnit.module( 'RingBufferGeometry', ( hooks ) => { var geometries = undefined; hooks.beforeEach( function () { const parameters = { innerRadius: 10, outerRadius: 60, thetaSegments: 12, phiSegments: 14, thetaStart: 0.1, thetaLength: 2.0 }; geometries = [ new RingBufferGeometry(), new RingBufferGeometry( parameters.innerRadius ), new RingBufferGeometry( parameters.innerRadius, parameters.outerRadius ), new RingBufferGeometry( parameters.innerRadius, parameters.outerRadius, parameters.thetaSegments ), new RingBufferGeometry( parameters.innerRadius, parameters.outerRadius, parameters.thetaSegments, parameters.phiSegments ), new RingBufferGeometry( parameters.innerRadius, parameters.outerRadius, parameters.thetaSegments, parameters.phiSegments, parameters.thetaStart ), new RingBufferGeometry( parameters.innerRadius, parameters.outerRadius, parameters.thetaSegments, parameters.phiSegments, parameters.thetaStart, parameters.thetaLength ), ]; } ); // INHERITANCE QUnit.todo( "Extending", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // INSTANCING QUnit.todo( "Instancing", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // OTHERS QUnit.test( 'Standard geometry tests', ( assert ) => { runStdGeometryTests( assert, geometries ); } ); } ); } );
/** * The controller for the main app * @param {object} $scope - The $scope * @param {object} AuthService - The auth service * @param {object} AUTH_EVENTS - The auth events constants */ function mainApp($scope, AuthService, AUTH_EVENTS) { 'ngInject'; $scope.currentUser = null; $scope.isAuthenticated = AuthService.isAuthenticated; $scope.setCurrentUser = (user) => { $scope.currentUser = user; }; $scope.clearCurrentUser = () => { $scope.currentUser = null; }; $scope.$on(AUTH_EVENTS.loginSuccess, (event, user) => { $scope.setCurrentUser(user); }); $scope.$on(AUTH_EVENTS.logoutSuccess, () => { $scope.clearCurrentUser(); }); $scope.login = () => { AuthService.login({ userName: 'admin', password: 'admin', }); }; $scope.logout = AuthService.logout; } module.exports = { name: 'mainCtrl', fn: mainApp, };
import expect from 'expect'; import multiplexSubscriber from '../src/multiplexSubscriber'; describe('multiplexSubscriber', () => { it('returns a multiplex subscriber that ' + 'will be notified once a tag of target has been changed', () => { let traceState = []; const tracer = expect.createSpy((state) => { traceState.push(state); }).andCallThrough(); const subscriber = multiplexSubscriber({ foo: 'fooTag', bar: { bar: { bar: 'barTag' } } }, tracer); subscriber({ foo: 4 }); expect(tracer.calls.length).toEqual(1); expect(traceState).toEqual([{ fooTag: 4 }]); subscriber({ foo: 4, bar: { bar: { bar: 6 } } }); expect(tracer.calls.length).toEqual(2); expect(traceState).toEqual([ { fooTag: 4 }, { fooTag: 4, barTag: 6 } ]); subscriber({ bar: { bar: { bar: 6 } } }); expect(tracer.calls.length).toEqual(3); expect(traceState).toEqual([ { fooTag: 4 }, { fooTag: 4, barTag: 6 }, { barTag: 6 } ]); }); it('will not be notified ' + 'if target has not been changed', () => { let traceState = []; const tracer = expect.createSpy(({ fooTag, barTag }) => { traceState.push({ fooTag, barTag }); }).andCallThrough(); const subscriber = multiplexSubscriber({ foo: 'fooTag', bar: 'barTag' }, tracer); subscriber({ foo: 4, bar: 5 }); expect(tracer.calls.length).toEqual(1); expect(traceState).toEqual([{ fooTag: 4, barTag: 5 }]); subscriber({ foo: 4, bar: 5 }); expect(tracer.calls.length).toEqual(1); expect(traceState).toEqual([{ fooTag: 4, barTag: 5 }]); subscriber({ foo: 4, bar: 5 }); expect(tracer.calls.length).toEqual(1); expect(traceState).toEqual([{ fooTag: 4, barTag: 5 }]); }); it('throws error if subscriber is not function', () => { expect(() => { multiplexSubscriber({ foo: 'fooTag' }, 'bar'); }).toThrow(/Expected subscriber/); expect(() => { multiplexSubscriber({ foo: 'fooTag' }, 233); }).toThrow(/Expected subscriber/); expect(() => { multiplexSubscriber({ foo: 'fooTag' }, {}); }).toThrow(/Expected subscriber/); }); it('throws error if target is not a tree with string type leaves', () => { expect(() => { multiplexSubscriber(233, function() {}); }).toThrow(/Expected target/); expect(() => { multiplexSubscriber([], function() {}); }).toThrow(/Expected target/); expect(() => { multiplexSubscriber(function() {}, function() {}); }).toThrow(/Expected target/); expect(() => { multiplexSubscriber({ foo: 233 }, function() {}); }).toThrow(/Expected target.*foo/); expect(() => { multiplexSubscriber({ foo: [ '233' ] }, function() {}); }).toThrow(/Expected target.*foo/); expect(() => { multiplexSubscriber({ foo: function() {} }, function() {}); }).toThrow(/Expected target.*foo/); }); it('throws error when checking duplicate tag', () => { expect(() => { multiplexSubscriber({ foo: 'fooTag', bar: { foo: 'fooTag' } }, function() {}); }).toThrow(/Duplicate tag/); }); it('throws error if subscriber shape does not match state shape', () => { const subscriber = multiplexSubscriber({ foo: { bar: 'fooTag' } }, function() {}); expect(() => { subscriber({ foo: 233 }); }).toThrow(/state foo.*type "number"/); }); });
var Deletion = require('./delete'); module.exports = Marionette.View.extend({ template: '#tpl-blog', tagName: 'li', events: { 'click .delete': 'showDeletion', }, showDeletion: function() { var that = this; this.deletion = new Deletion(); this.deletion.on('delete', this.delete.bind(this)); this.deletion.on('cancel', function() { that.deletion.remove(); }); return this.deletion.render(); }, delete: function() { var that = this; return q.fcall(function() { var defer = q.defer(); that.model.destroy({ success: defer.resolve, error: defer.reject }); return defer.promise; }) .then(function(res) { that.deletion.remove(); return that.render(); }) }, render: function() { var html = $(this.template).html(); var template = _.template(html); this.$el.html(template({ blog: this.model })); return this; } });
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Malay language. */ /**#@+ @type String @example */ /** * Contains the dictionary of language entries. * @namespace */ CKEDITOR.lang['ms'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'Rich text editor, %1, press ALT 0 for help.', // MISSING // ARIA descriptions. toolbars : 'Editor toolbars', // MISSING editor : 'Rich Text Editor', // MISSING // Toolbar buttons without dialogs. source : 'Sumber', newPage : 'Helaian Baru', save : 'Simpan', preview : 'Prebiu', cut : 'Potong', copy : 'Salin', paste : 'Tampal', print : 'Cetak', underline : 'Underline', bold : 'Bold', italic : 'Italic', selectAll : 'Pilih Semua', removeFormat : 'Buang Format', strike : 'Strike Through', subscript : 'Subscript', superscript : 'Superscript', horizontalrule : 'Masukkan Garisan Membujur', pagebreak : 'Insert Page Break for Printing', // MISSING pagebreakAlt : 'Page Break', // MISSING unlink : 'Buang Sambungan', undo : 'Batalkan', redo : 'Ulangkan', // Common messages and labels. common : { browseServer : 'Browse Server', url : 'URL', protocol : 'Protokol', upload : 'Muat Naik', uploadSubmit : 'Hantar ke Server', image : 'Gambar', flash : 'Flash', // MISSING form : 'Borang', checkbox : 'Checkbox', radio : 'Butang Radio', textField : 'Text Field', textarea : 'Textarea', hiddenField : 'Field Tersembunyi', button : 'Butang', select : 'Field Pilihan', imageButton : 'Butang Bergambar', notSet : '<tidak di set>', id : 'Id', name : 'Nama', langDir : 'Arah Tulisan', langDirLtr : 'Kiri ke Kanan (LTR)', langDirRtl : 'Kanan ke Kiri (RTL)', langCode : 'Kod Bahasa', longDescr : 'Butiran Panjang URL', cssClass : 'Kelas-kelas Stylesheet', advisoryTitle : 'Tajuk Makluman', cssStyle : 'Stail', ok : 'OK', cancel : 'Batal', close : 'Close', // MISSING preview : 'Preview', // MISSING generalTab : 'General', // MISSING advancedTab : 'Advanced', validateNumberFailed : 'This value is not a number.', // MISSING confirmNewPage : 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING options : 'Options', // MISSING target : 'Target', // MISSING targetNew : 'New Window (_blank)', // MISSING targetTop : 'Topmost Window (_top)', // MISSING targetSelf : 'Same Window (_self)', // MISSING targetParent : 'Parent Window (_parent)', // MISSING langDirLTR : 'Left to Right (LTR)', // MISSING langDirRTL : 'Right to Left (RTL)', // MISSING styles : 'Style', // MISSING cssClasses : 'Stylesheet Classes', // MISSING width : 'Lebar', height : 'Tinggi', align : 'Jajaran', alignLeft : 'Kiri', alignRight : 'Kanan', alignCenter : 'Tengah', alignTop : 'Atas', alignMiddle : 'Pertengahan', alignBottom : 'Bawah', invalidHeight : 'Height must be a number.', // MISSING invalidWidth : 'Width must be a number.', // MISSING invalidCssLength : 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING invalidHtmlLength : 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING invalidInlineStyle : 'Value specified for the inline style must consist of one or more tuples with the format of "name : value", separated by semi-colons.', // MISSING cssLengthTooltip : 'Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, unavailable</span>' // MISSING }, contextmenu : { options : 'Context Menu Options' // MISSING }, // Special char dialog. specialChar : { toolbar : 'Masukkan Huruf Istimewa', title : 'Sila pilih huruf istimewa', options : 'Special Character Options' // MISSING }, // Link dialog. link : { toolbar : 'Masukkan/Sunting Sambungan', other : '<lain>', menu : 'Sunting Sambungan', title : 'Sambungan', info : 'Butiran Sambungan', target : 'Sasaran', upload : 'Muat Naik', advanced : 'Advanced', type : 'Jenis Sambungan', toUrl : 'URL', // MISSING toAnchor : 'Pautan dalam muka surat ini', toEmail : 'E-Mail', targetFrame : '<bingkai>', targetPopup : '<tetingkap popup>', targetFrameName : 'Nama Bingkai Sasaran', targetPopupName : 'Nama Tetingkap Popup', popupFeatures : 'Ciri Tetingkap Popup', popupResizable : 'Resizable', // MISSING popupStatusBar : 'Bar Status', popupLocationBar: 'Bar Lokasi', popupToolbar : 'Toolbar', popupMenuBar : 'Bar Menu', popupFullScreen : 'Skrin Penuh (IE)', popupScrollBars : 'Bar-bar skrol', popupDependent : 'Bergantungan (Netscape)', popupLeft : 'Posisi Kiri', popupTop : 'Posisi Atas', id : 'Id', // MISSING langDir : 'Arah Tulisan', langDirLTR : 'Kiri ke Kanan (LTR)', langDirRTL : 'Kanan ke Kiri (RTL)', acccessKey : 'Kunci Akses', name : 'Nama', langCode : 'Arah Tulisan', tabIndex : 'Indeks Tab ', advisoryTitle : 'Tajuk Makluman', advisoryContentType : 'Jenis Kandungan Makluman', cssClasses : 'Kelas-kelas Stylesheet', charset : 'Linked Resource Charset', styles : 'Stail', rel : 'Relationship', // MISSING selectAnchor : 'Sila pilih pautan', anchorName : 'dengan menggunakan nama pautan', anchorId : 'dengan menggunakan ID elemen', emailAddress : 'Alamat E-Mail', emailSubject : 'Subjek Mesej', emailBody : 'Isi Kandungan Mesej', noAnchors : '(Tiada pautan terdapat dalam dokumen ini)', noUrl : 'Sila taip sambungan URL', noEmail : 'Sila taip alamat e-mail' }, // Anchor dialog anchor : { toolbar : 'Masukkan/Sunting Pautan', menu : 'Ciri-ciri Pautan', title : 'Ciri-ciri Pautan', name : 'Nama Pautan', errorName : 'Sila taip nama pautan', remove : 'Remove Anchor' // MISSING }, // List style dialog list: { numberedTitle : 'Numbered List Properties', // MISSING bulletedTitle : 'Bulleted List Properties', // MISSING type : 'Type', // MISSING start : 'Start', // MISSING validateStartNumber :'List start number must be a whole number.', // MISSING circle : 'Circle', // MISSING disc : 'Disc', // MISSING square : 'Square', // MISSING none : 'None', // MISSING notset : '<not set>', // MISSING armenian : 'Armenian numbering', // MISSING georgian : 'Georgian numbering (an, ban, gan, etc.)', // MISSING lowerRoman : 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING upperRoman : 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING lowerAlpha : 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING upperAlpha : 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING lowerGreek : 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING decimal : 'Decimal (1, 2, 3, etc.)', // MISSING decimalLeadingZero : 'Decimal leading zero (01, 02, 03, etc.)' // MISSING }, // Find And Replace Dialog findAndReplace : { title : 'Find and Replace', // MISSING find : 'Cari', replace : 'Ganti', findWhat : 'Perkataan yang dicari:', replaceWith : 'Diganti dengan:', notFoundMsg : 'Text yang dicari tidak dijumpai.', findOptions : 'Find Options', // MISSING matchCase : 'Padanan case huruf', matchWord : 'Padana Keseluruhan perkataan', matchCyclic : 'Match cyclic', // MISSING replaceAll : 'Ganti semua', replaceSuccessMsg : '%1 occurrence(s) replaced.' // MISSING }, // Table Dialog table : { toolbar : 'Jadual', title : 'Ciri-ciri Jadual', menu : 'Ciri-ciri Jadual', deleteTable : 'Delete Table', // MISSING rows : 'Barisan', columns : 'Jaluran', border : 'Saiz Border', widthPx : 'piksel-piksel', widthPc : 'peratus', widthUnit : 'width unit', // MISSING cellSpace : 'Ruangan Antara Sel', cellPad : 'Tambahan Ruang Sel', caption : 'Keterangan', summary : 'Summary', // MISSING headers : 'Headers', // MISSING headersNone : 'None', // MISSING headersColumn : 'First column', // MISSING headersRow : 'First Row', // MISSING headersBoth : 'Both', // MISSING invalidRows : 'Number of rows must be a number greater than 0.', // MISSING invalidCols : 'Number of columns must be a number greater than 0.', // MISSING invalidBorder : 'Border size must be a number.', // MISSING invalidWidth : 'Table width must be a number.', // MISSING invalidHeight : 'Table height must be a number.', // MISSING invalidCellSpacing : 'Cell spacing must be a positive number.', // MISSING invalidCellPadding : 'Cell padding must be a positive number.', // MISSING cell : { menu : 'Cell', // MISSING insertBefore : 'Insert Cell Before', // MISSING insertAfter : 'Insert Cell After', // MISSING deleteCell : 'Buangkan Sel-sel', merge : 'Cantumkan Sel-sel', mergeRight : 'Merge Right', // MISSING mergeDown : 'Merge Down', // MISSING splitHorizontal : 'Split Cell Horizontally', // MISSING splitVertical : 'Split Cell Vertically', // MISSING title : 'Cell Properties', // MISSING cellType : 'Cell Type', // MISSING rowSpan : 'Rows Span', // MISSING colSpan : 'Columns Span', // MISSING wordWrap : 'Word Wrap', // MISSING hAlign : 'Horizontal Alignment', // MISSING vAlign : 'Vertical Alignment', // MISSING alignBaseline : 'Baseline', // MISSING bgColor : 'Background Color', // MISSING borderColor : 'Border Color', // MISSING data : 'Data', // MISSING header : 'Header', // MISSING yes : 'Yes', // MISSING no : 'No', // MISSING invalidWidth : 'Cell width must be a number.', // MISSING invalidHeight : 'Cell height must be a number.', // MISSING invalidRowSpan : 'Rows span must be a whole number.', // MISSING invalidColSpan : 'Columns span must be a whole number.', // MISSING chooseColor : 'Choose' // MISSING }, row : { menu : 'Row', // MISSING insertBefore : 'Insert Row Before', // MISSING insertAfter : 'Insert Row After', // MISSING deleteRow : 'Buangkan Baris' }, column : { menu : 'Column', // MISSING insertBefore : 'Insert Column Before', // MISSING insertAfter : 'Insert Column After', // MISSING deleteColumn : 'Buangkan Lajur' } }, // Button Dialog. button : { title : 'Ciri-ciri Butang', text : 'Teks (Nilai)', type : 'Jenis', typeBtn : 'Button', // MISSING typeSbm : 'Submit', // MISSING typeRst : 'Reset' // MISSING }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'Ciri-ciri Checkbox', radioTitle : 'Ciri-ciri Butang Radio', value : 'Nilai', selected : 'Dipilih' }, // Form Dialog. form : { title : 'Ciri-ciri Borang', menu : 'Ciri-ciri Borang', action : 'Tindakan borang', method : 'Cara borang dihantar', encoding : 'Encoding' // MISSING }, // Select Field Dialog. select : { title : 'Ciri-ciri Selection Field', selectInfo : 'Select Info', // MISSING opAvail : 'Pilihan sediada', value : 'Nilai', size : 'Saiz', lines : 'garisan', chkMulti : 'Benarkan pilihan pelbagai', opText : 'Teks', opValue : 'Nilai', btnAdd : 'Tambah Pilihan', btnModify : 'Ubah Pilihan', btnUp : 'Naik ke atas', btnDown : 'Turun ke bawah', btnSetValue : 'Set sebagai nilai terpilih', btnDelete : 'Padam' }, // Textarea Dialog. textarea : { title : 'Ciri-ciri Textarea', cols : 'Lajur', rows : 'Baris' }, // Text Field Dialog. textfield : { title : 'Ciri-ciri Text Field', name : 'Nama', value : 'Nilai', charWidth : 'Lebar isian', maxChars : 'Isian Maksimum', type : 'Jenis', typeText : 'Teks', typePass : 'Kata Laluan' }, // Hidden Field Dialog. hidden : { title : 'Ciri-ciri Field Tersembunyi', name : 'Nama', value : 'Nilai' }, // Image Dialog. image : { title : 'Ciri-ciri Imej', titleButton : 'Ciri-ciri Butang Bergambar', menu : 'Ciri-ciri Imej', infoTab : 'Info Imej', btnUpload : 'Hantar ke Server', upload : 'Muat Naik', alt : 'Text Alternatif', lockRatio : 'Tetapkan Nisbah', resetSize : 'Saiz Set Semula', border : 'Border', hSpace : 'Ruang Melintang', vSpace : 'Ruang Menegak', alertUrl : 'Sila taip URL untuk fail gambar', linkTab : 'Sambungan', button2Img : 'Do you want to transform the selected image button on a simple image?', // MISSING img2Button : 'Do you want to transform the selected image on a image button?', // MISSING urlMissing : 'Image source URL is missing.', // MISSING validateBorder : 'Border must be a whole number.', // MISSING validateHSpace : 'HSpace must be a whole number.', // MISSING validateVSpace : 'VSpace must be a whole number.' // MISSING }, // Flash Dialog flash : { properties : 'Flash Properties', // MISSING propertiesTab : 'Properties', // MISSING title : 'Flash Properties', // MISSING chkPlay : 'Auto Play', // MISSING chkLoop : 'Loop', // MISSING chkMenu : 'Enable Flash Menu', // MISSING chkFull : 'Allow Fullscreen', // MISSING scale : 'Scale', // MISSING scaleAll : 'Show all', // MISSING scaleNoBorder : 'No Border', // MISSING scaleFit : 'Exact Fit', // MISSING access : 'Script Access', // MISSING accessAlways : 'Always', // MISSING accessSameDomain: 'Same domain', // MISSING accessNever : 'Never', // MISSING alignAbsBottom : 'Bawah Mutlak', alignAbsMiddle : 'Pertengahan Mutlak', alignBaseline : 'Garis Dasar', alignTextTop : 'Atas Text', quality : 'Quality', // MISSING qualityBest : 'Best', // MISSING qualityHigh : 'High', // MISSING qualityAutoHigh : 'Auto High', // MISSING qualityMedium : 'Medium', // MISSING qualityAutoLow : 'Auto Low', // MISSING qualityLow : 'Low', // MISSING windowModeWindow: 'Window', // MISSING windowModeOpaque: 'Opaque', // MISSING windowModeTransparent : 'Transparent', // MISSING windowMode : 'Window mode', // MISSING flashvars : 'Variables for Flash', // MISSING bgcolor : 'Warna Latarbelakang', hSpace : 'Ruang Melintang', vSpace : 'Ruang Menegak', validateSrc : 'Sila taip sambungan URL', validateHSpace : 'HSpace must be a number.', // MISSING validateVSpace : 'VSpace must be a number.' // MISSING }, // Speller Pages Dialog spellCheck : { toolbar : 'Semak Ejaan', title : 'Spell Check', // MISSING notAvailable : 'Sorry, but service is unavailable now.', // MISSING errorLoading : 'Error loading application service host: %s.', // MISSING notInDic : 'Tidak terdapat didalam kamus', changeTo : 'Tukarkan kepada', btnIgnore : 'Biar', btnIgnoreAll : 'Biarkan semua', btnReplace : 'Ganti', btnReplaceAll : 'Gantikan Semua', btnUndo : 'Batalkan', noSuggestions : '- Tiada cadangan -', progress : 'Pemeriksaan ejaan sedang diproses...', noMispell : 'Pemeriksaan ejaan siap: Tiada salah ejaan', noChanges : 'Pemeriksaan ejaan siap: Tiada perkataan diubah', oneChange : 'Pemeriksaan ejaan siap: Satu perkataan telah diubah', manyChanges : 'Pemeriksaan ejaan siap: %1 perkataan diubah', ieSpellDownload : 'Pemeriksa ejaan tidak dipasang. Adakah anda mahu muat turun sekarang?' }, smiley : { toolbar : 'Smiley', title : 'Masukkan Smiley', options : 'Smiley Options' // MISSING }, elementsPath : { eleLabel : 'Elements path', // MISSING eleTitle : '%1 element' // MISSING }, numberedlist : 'Senarai bernombor', bulletedlist : 'Senarai tidak bernombor', indent : 'Tambahkan Inden', outdent : 'Kurangkan Inden', justify : { left : 'Jajaran Kiri', center : 'Jajaran Tengah', right : 'Jajaran Kanan', block : 'Jajaran Blok' }, blockquote : 'Block Quote', // MISSING clipboard : { title : 'Tampal', cutError : 'Keselamatan perisian browser anda tidak membenarkan operasi suntingan text/imej. Sila gunakan papan kekunci (Ctrl/Cmd+X).', copyError : 'Keselamatan perisian browser anda tidak membenarkan operasi salinan text/imej. Sila gunakan papan kekunci (Ctrl/Cmd+C).', pasteMsg : 'Please paste inside the following box using the keyboard (<strong>Ctrl/Cmd+V</strong>) and hit OK', // MISSING securityMsg : 'Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.', // MISSING pasteArea : 'Paste Area' // MISSING }, pastefromword : { confirmCleanup : 'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?', // MISSING toolbar : 'Tampal dari Word', title : 'Tampal dari Word', error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING }, pasteText : { button : 'Tampal sebagai text biasa', title : 'Tampal sebagai text biasa' }, templates : { button : 'Templat', title : 'Templat Kandungan', options : 'Template Options', // MISSING insertOption : 'Replace actual contents', // MISSING selectPromptMsg : 'Sila pilih templat untuk dibuka oleh editor<br>(kandungan sebenar akan hilang):', emptyListMsg : '(Tiada Templat Disimpan)' }, showBlocks : 'Show Blocks', // MISSING stylesCombo : { label : 'Stail', panelTitle : 'Formatting Styles', // MISSING panelTitle1 : 'Block Styles', // MISSING panelTitle2 : 'Inline Styles', // MISSING panelTitle3 : 'Object Styles' // MISSING }, format : { label : 'Format', panelTitle : 'Format', tag_p : 'Normal', tag_pre : 'Telah Diformat', tag_address : 'Alamat', tag_h1 : 'Heading 1', tag_h2 : 'Heading 2', tag_h3 : 'Heading 3', tag_h4 : 'Heading 4', tag_h5 : 'Heading 5', tag_h6 : 'Heading 6', tag_div : 'Perenggan (DIV)' }, div : { title : 'Create Div Container', // MISSING toolbar : 'Create Div Container', // MISSING cssClassInputLabel : 'Stylesheet Classes', // MISSING styleSelectLabel : 'Style', // MISSING IdInputLabel : 'Id', // MISSING languageCodeInputLabel : ' Language Code', // MISSING inlineStyleInputLabel : 'Inline Style', // MISSING advisoryTitleInputLabel : 'Advisory Title', // MISSING langDirLabel : 'Language Direction', // MISSING langDirLTRLabel : 'Left to Right (LTR)', // MISSING langDirRTLLabel : 'Right to Left (RTL)', // MISSING edit : 'Edit Div', // MISSING remove : 'Remove Div' // MISSING }, iframe : { title : 'IFrame Properties', // MISSING toolbar : 'IFrame', // MISSING noUrl : 'Please type the iframe URL', // MISSING scrolling : 'Enable scrollbars', // MISSING border : 'Show frame border' // MISSING }, font : { label : 'Font', voiceLabel : 'Font', // MISSING panelTitle : 'Font' }, fontSize : { label : 'Saiz', voiceLabel : 'Font Size', // MISSING panelTitle : 'Saiz' }, colorButton : { textColorTitle : 'Warna Text', bgColorTitle : 'Warna Latarbelakang', panelTitle : 'Colors', // MISSING auto : 'Otomatik', more : 'Warna lain-lain...' }, colors : { '000' : 'Black', // MISSING '800000' : 'Maroon', // MISSING '8B4513' : 'Saddle Brown', // MISSING '2F4F4F' : 'Dark Slate Gray', // MISSING '008080' : 'Teal', // MISSING '000080' : 'Navy', // MISSING '4B0082' : 'Indigo', // MISSING '696969' : 'Dark Gray', // MISSING 'B22222' : 'Fire Brick', // MISSING 'A52A2A' : 'Brown', // MISSING 'DAA520' : 'Golden Rod', // MISSING '006400' : 'Dark Green', // MISSING '40E0D0' : 'Turquoise', // MISSING '0000CD' : 'Medium Blue', // MISSING '800080' : 'Purple', // MISSING '808080' : 'Gray', // MISSING 'F00' : 'Red', // MISSING 'FF8C00' : 'Dark Orange', // MISSING 'FFD700' : 'Gold', // MISSING '008000' : 'Green', // MISSING '0FF' : 'Cyan', // MISSING '00F' : 'Blue', // MISSING 'EE82EE' : 'Violet', // MISSING 'A9A9A9' : 'Dim Gray', // MISSING 'FFA07A' : 'Light Salmon', // MISSING 'FFA500' : 'Orange', // MISSING 'FFFF00' : 'Yellow', // MISSING '00FF00' : 'Lime', // MISSING 'AFEEEE' : 'Pale Turquoise', // MISSING 'ADD8E6' : 'Light Blue', // MISSING 'DDA0DD' : 'Plum', // MISSING 'D3D3D3' : 'Light Grey', // MISSING 'FFF0F5' : 'Lavender Blush', // MISSING 'FAEBD7' : 'Antique White', // MISSING 'FFFFE0' : 'Light Yellow', // MISSING 'F0FFF0' : 'Honeydew', // MISSING 'F0FFFF' : 'Azure', // MISSING 'F0F8FF' : 'Alice Blue', // MISSING 'E6E6FA' : 'Lavender', // MISSING 'FFF' : 'White' // MISSING }, scayt : { title : 'Spell Check As You Type', // MISSING opera_title : 'Not supported by Opera', // MISSING enable : 'Enable SCAYT', // MISSING disable : 'Disable SCAYT', // MISSING about : 'About SCAYT', // MISSING toggle : 'Toggle SCAYT', // MISSING options : 'Options', // MISSING langs : 'Languages', // MISSING moreSuggestions : 'More suggestions', // MISSING ignore : 'Ignore', // MISSING ignoreAll : 'Ignore All', // MISSING addWord : 'Add Word', // MISSING emptyDic : 'Dictionary name should not be empty.', // MISSING optionsTab : 'Options', // MISSING allCaps : 'Ignore All-Caps Words', // MISSING ignoreDomainNames : 'Ignore Domain Names', // MISSING mixedCase : 'Ignore Words with Mixed Case', // MISSING mixedWithDigits : 'Ignore Words with Numbers', // MISSING languagesTab : 'Languages', // MISSING dictionariesTab : 'Dictionaries', // MISSING dic_field_name : 'Dictionary name', // MISSING dic_create : 'Create', // MISSING dic_restore : 'Restore', // MISSING dic_delete : 'Delete', // MISSING dic_rename : 'Rename', // MISSING dic_info : 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING aboutTab : 'About' // MISSING }, about : { title : 'About CKEditor', // MISSING dlgTitle : 'About CKEditor', // MISSING help : 'Check $1 for help.', // MISSING userGuide : 'CKEditor User\'s Guide', // MISSING moreInfo : 'For licensing information please visit our web site:', // MISSING copy : 'Copyright &copy; $1. All rights reserved.' // MISSING }, maximize : 'Maximize', // MISSING minimize : 'Minimize', // MISSING fakeobjects : { anchor : 'Anchor', // MISSING flash : 'Flash Animation', // MISSING iframe : 'IFrame', // MISSING hiddenfield : 'Hidden Field', // MISSING unknown : 'Unknown Object' // MISSING }, resize : 'Drag to resize', // MISSING colordialog : { title : 'Select color', // MISSING options : 'Color Options', // MISSING highlight : 'Highlight', // MISSING selected : 'Selected Color', // MISSING clear : 'Clear' // MISSING }, toolbarCollapse : 'Collapse Toolbar', // MISSING toolbarExpand : 'Expand Toolbar', // MISSING toolbarGroups : { document : 'Document', // MISSING clipboard : 'Clipboard/Undo', // MISSING editing : 'Editing', // MISSING forms : 'Forms', // MISSING basicstyles : 'Basic Styles', // MISSING paragraph : 'Paragraph', // MISSING links : 'Links', // MISSING insert : 'Insert', // MISSING styles : 'Styles', // MISSING colors : 'Colors', // MISSING tools : 'Tools' // MISSING }, bidi : { ltr : 'Text direction from left to right', // MISSING rtl : 'Text direction from right to left' // MISSING }, docprops : { label : 'Ciri-ciri dokumen', title : 'Ciri-ciri dokumen', design : 'Design', // MISSING meta : 'Data Meta', chooseColor : 'Choose', // MISSING other : '<lain>', docTitle : 'Tajuk Muka Surat', charset : 'Enkod Set Huruf', charsetOther : 'Enkod Set Huruf yang Lain', charsetASCII : 'ASCII', // MISSING charsetCE : 'Central European', // MISSING charsetCT : 'Chinese Traditional (Big5)', // MISSING charsetCR : 'Cyrillic', // MISSING charsetGR : 'Greek', // MISSING charsetJP : 'Japanese', // MISSING charsetKR : 'Korean', // MISSING charsetTR : 'Turkish', // MISSING charsetUN : 'Unicode (UTF-8)', // MISSING charsetWE : 'Western European', // MISSING docType : 'Jenis Kepala Dokumen', docTypeOther : 'Jenis Kepala Dokumen yang Lain', xhtmlDec : 'Masukkan pemula kod XHTML', bgColor : 'Warna Latarbelakang', bgImage : 'URL Gambar Latarbelakang', bgFixed : 'Imej Latarbelakang tanpa Skrol', txtColor : 'Warna Text', margin : 'Margin Muka Surat', marginTop : 'Atas', marginLeft : 'Kiri', marginRight : 'Kanan', marginBottom : 'Bawah', metaKeywords : 'Kata Kunci Indeks Dokumen (dipisahkan oleh koma)', metaDescription : 'Keterangan Dokumen', metaAuthor : 'Penulis', metaCopyright : 'Hakcipta', previewHtml : '<p>This is some <strong>sample text</strong>. You are using <a href="javascript:void(0)">CKEditor</a>.</p>' // MISSING } };
// * ben - non dropdown select version. ----------------// (function($){ $.fn.custom_mobileMenu = function() { //attach the down arrow for submenu $( "#mobile-menu > ul li" ).has( "ul" ).prepend("<span class='submenu-slide' href='#'><i class='fa fa-angle-down fa-6'></i></span>"); /* toggle nav */ $("#mobile-icon").on("click", function(){ $("#mobile-menu > ul").slideToggle('fast'); $(this).toggleClass("active"); }); /* toggle submenu items*/ $("#mobile-menu > ul li span.submenu-slide").on("click", function(){ $(this).siblings( "ul.sub-menu" ).slideToggle('fast'); }); }; })(jQuery);
/*! * inputmask.phone.extensions.js * https://github.com/RobinHerbots/Inputmask * Copyright (c) 2010 - 2018 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 4.0.0-beta.9 */ !function(factory) { "function" == typeof define && define.amd ? define([ "./dependencyLibs/inputmask.dependencyLib", "./inputmask" ], factory) : "object" == typeof exports ? module.exports = factory(require("./dependencyLibs/inputmask.dependencyLib"), require("./inputmask")) : factory(window.dependencyLib || jQuery, window.Inputmask); }(function($, Inputmask) { function maskSort(a, b) { var maska = (a.mask || a).replace(/#/g, "0").replace(/\)/, "0").replace(/[+()#-]/g, ""), maskb = (b.mask || b).replace(/#/g, "0").replace(/\)/, "0").replace(/[+()#-]/g, ""); return maska.localeCompare(maskb); } var analyseMaskBase = Inputmask.prototype.analyseMask; return Inputmask.prototype.analyseMask = function(mask, regexMask, opts) { var maskGroups = {}; return opts.phoneCodes && (opts.phoneCodes && opts.phoneCodes.length > 1e3 && (function reduceVariations(masks, previousVariation, previousmaskGroup) { previousVariation = previousVariation || "", previousmaskGroup = previousmaskGroup || maskGroups, "" !== previousVariation && (previousmaskGroup[previousVariation] = {}); for (var variation = "", maskGroup = previousmaskGroup[previousVariation] || previousmaskGroup, i = masks.length - 1; i >= 0; i--) maskGroup[variation = (mask = masks[i].mask || masks[i]).substr(0, 1)] = maskGroup[variation] || [], maskGroup[variation].unshift(mask.substr(1)), masks.splice(i, 1); for (var ndx in maskGroup) maskGroup[ndx].length > 500 && reduceVariations(maskGroup[ndx].slice(), ndx, maskGroup); }((mask = mask.substr(1, mask.length - 2)).split(opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0])), mask = function rebuild(maskGroup) { var mask = "", submasks = []; for (var ndx in maskGroup) $.isArray(maskGroup[ndx]) ? 1 === maskGroup[ndx].length ? submasks.push(ndx + maskGroup[ndx]) : submasks.push(ndx + opts.groupmarker[0] + maskGroup[ndx].join(opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0]) + opts.groupmarker[1]) : submasks.push(ndx + rebuild(maskGroup[ndx])); return 1 === submasks.length ? mask += submasks[0] : mask += opts.groupmarker[0] + submasks.join(opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0]) + opts.groupmarker[1], mask; }(maskGroups)), mask = mask.replace(/9/g, "\\9")), analyseMaskBase.call(this, mask, regexMask, opts); }, Inputmask.extendAliases({ abstractphone: { groupmarker: [ "<", ">" ], countrycode: "", phoneCodes: [], keepStatic: "auto", mask: function(opts) { return opts.definitions = { "#": Inputmask.prototype.definitions[9] }, opts.phoneCodes.sort(maskSort); }, onBeforeMask: function(value, opts) { var processedValue = value.replace(/^0{1,2}/, "").replace(/[\s]/g, ""); return (processedValue.indexOf(opts.countrycode) > 1 || -1 === processedValue.indexOf(opts.countrycode)) && (processedValue = "+" + opts.countrycode + processedValue), processedValue; }, onUnMask: function(maskedValue, unmaskedValue, opts) { return maskedValue.replace(/[()#-]/g, ""); }, inputmode: "tel" } }), Inputmask; });
'use strict'; eventsApp.factory('$exceptionHandler', function(){ return function(exception) { console.log("exeption handled: " + exception.message); }; });
var Validator, isValidator; Validator = require("../types/Validator"); module.exports = isValidator = function(value) { return value && value.constructor[Validator.type]; }; //# sourceMappingURL=../../../map/src/core/isValidator.map
(function() { "use strict"; var TemperatureReadingService = function($http) { var getAllTemperatures = function() { return $http.get("/api/readings"); }; var getTemperaturesForLastHours = function (hours) { return $http.get("/api/readings?lastHours=" + hours); }; return { getAllTemperatures: getAllTemperatures, getTemperaturesForLastHours: getTemperaturesForLastHours } }; angular.module("app").service("TemperatureReadingService", ["$http", TemperatureReadingService]); })();
function fetchAsync (url, timeout, onData, onError) { onData(); return url; } let fetchPromised = (url, timeout) => { return new Promise((resolve, reject) => { fetchAsync(url, timeout, resolve, reject) }) } Promise.all([ fetchPromised("http://backend/foo.txt", 500), fetchPromised("http://backend/bar.txt", 500), fetchPromised("http://backend/baz.txt", 500) ]).then((data) => { let [ foo, bar, baz ] = data console.log(`success: foo=${foo} bar=${bar} baz=${baz}`) }, (err) => { console.log(`error: ${err}`) })
var from = require('from'); var through2 = require('through2'); var through = require('through'); var streamworks = require('../src'); describe('streamworks', function(){ describe('constructor', function(){ it('should be a pipe and merge function', function(){ streamworks.pipe.should.be.type('function'); streamworks.merge.should.be.type('function'); }) it('should throw with no arguments to pipe', function(){ (function(){ streamworks.pipe(); }).should.throw() }) it('should throw with no arguments to merge', function(){ (function(){ streamworks.merge(); }).should.throw() }) }) describe('function streams', function(){ it('should run a buffer/string merge', function(done){ var p = streamworks.merge([ function(chunk, enc, callback){ this.push('a' + chunk); callback(); }, function(chunk, enc, callback){ this.push('b' + chunk); callback(); }, function(chunk, enc, callback){ this.push('c' + chunk); callback(); } ]) var arr = []; from(['red','green','blue']).pipe(p) .on('data', function(chunk){ arr.push(chunk.toString()) }) .on('end', function(){ arr.length.should.equal(9); arr[3].should.equal('agreen'); arr[8].should.equal('cblue'); done(); }) }) it('should run an object merge', function(done){ var p = streamworks.mergeObjects([ function(chunk, enc, callback){ chunk.section = 'a'; this.push(chunk); callback(); }, function(chunk, enc, callback){ chunk.section = 'b'; this.push(chunk); callback(); }, function(chunk, enc, callback){ chunk.section = 'c'; this.push(chunk); callback(); } ]) var map = {}; from([{ name:'a' },{ name:'b' },{ name:'c' }]).pipe(p) .on('data', function(chunk){ map[chunk.name + chunk.section] = true; }) .on('end', function(){ map.aa.should.equal(true); map.ab.should.equal(true); map.ac.should.equal(true); map.ba.should.equal(true); map.bb.should.equal(true); map.bc.should.equal(true); map.ca.should.equal(true); map.cb.should.equal(true); map.cc.should.equal(true); done(); }) }) it('should run a buffer/string pipe', function(done){ var p = streamworks.pipe([ function(chunk, enc, callback){ this.push(chunk + 'a'); callback(); }, function(chunk, enc, callback){ this.push('b' + chunk); callback(); }, function(chunk, enc, callback){ this.push('c' + chunk + 'c'); callback(); } ]) var arr = []; from(['hello','world','apple']).pipe(p) .on('data', function(chunk){ arr.push(chunk.toString()) }).on('end', function(){ arr.length.should.equal(3); arr[0].should.equal('cbhelloac'); arr[1].should.equal('cbworldac'); arr[2].should.equal('cbappleac'); done(); }) }) it('should run an object pipe', function(done){ var p = streamworks.pipeObjects([ // upercase name function(chunk, enc, callback){ chunk.name = chunk.name.toUpperCase(); this.push(chunk); callback(); }, // double price function(chunk, enc, callback){ chunk.price *= 2; this.push(chunk); callback(); }, // filter price function(chunk, enc, callback){ if(chunk.price<=24){ this.push(chunk); } callback(); } ]) var arr = []; from([{ name:'apples', price:10 },{ name:'pears', price:13 },{ name:'peaches', price:12 }]).pipe(p) .on('data', function(chunk){ arr.push(chunk) }).on('end', function(){ arr.length.should.equal(2); arr[0].name.should.equal('APPLES'); arr[0].price.should.equal(20); arr[1].name.should.equal('PEACHES'); arr[1].price.should.equal(24); done(); }) }) }) describe('existing streams', function(){ function testExistingStream(existingStream, done){ var p = streamworks.pipe([ // upercase name function(chunk, enc, callback){ this.push(chunk.toString().toUpperCase()); callback(); }, existingStream, function(chunk, enc, callback){ this.push('_' + chunk + '_'); callback(); } ]) var arr = []; from(['apple', 'orange', 'pear']).pipe(p) .on('data', function(chunk){ arr.push(chunk.toString()) }).on('end', function(){ arr.length.should.equal(3); arr[0].should.equal('_YOAPPLE_'); arr[1].should.equal('_YOORANGE_'); arr[2].should.equal('_YOPEAR_'); done(); }) } it('should pipe with an existing duplex v2 stream', function(done){ var otherstream = through2(function(chunk, enc, callback){ this.push('YO' + chunk) callback() }) testExistingStream(otherstream, done); }) it('should pipe with an existing duplex v1 stream', function(done){ var otherstream = through(function(chunk){ this.queue('YO' + chunk) }) testExistingStream(otherstream, done); }) }) describe('nesting', function(){ it('should combine a very complicated bunch of streams and get the expected answer (yo)', function(done){ var p = streamworks.pipe([ function(chunk, enc, callback){ if(chunk!='world'){ this.push(chunk); } callback(); }, streamworks.merge([ function(chunk, enc, callback){ this.push('A1:' + chunk); callback(); }, function(chunk, enc, callback){ this.push('A2:' + chunk); callback(); }, function(chunk, enc, callback){ this.push('A3:' + chunk); callback(); } ]), streamworks.pipe([ function(chunk, enc, callback){ if(chunk.toString().indexOf('A2')!=0){ this.push(chunk); } callback(); }, streamworks.merge([ function(chunk, enc, callback){ this.push('sub1:' + chunk); callback(); }, function(chunk, enc, callback){ this.push('sub2:' + chunk); callback(); } ]), function(chunk, enc, callback){ if(chunk.toString().indexOf('sub2:A1:')!=0){ this.push(chunk); } callback() }, ]) ]) var arr = []; from(['hello','world','apple']).pipe(p) .on('data', function(chunk){ arr.push(chunk.toString()) }).on('end', function(){ arr.length.should.equal(6); arr[0].should.equal('sub1:A1:hello'); arr[1].should.equal('sub1:A3:hello'); arr[2].should.equal('sub2:A3:hello'); arr[3].should.equal('sub1:A1:apple'); arr[4].should.equal('sub1:A3:apple'); arr[5].should.equal('sub2:A3:apple'); done(); }) }) }) })
// All symbols in the Specials block as per Unicode v3.2.0: [ '\uFFF0', '\uFFF1', '\uFFF2', '\uFFF3', '\uFFF4', '\uFFF5', '\uFFF6', '\uFFF7', '\uFFF8', '\uFFF9', '\uFFFA', '\uFFFB', '\uFFFC', '\uFFFD', '\uFFFE', '\uFFFF' ];
"use strict"; const gulp = require('gulp'), rename = require('gulp-rename'), concat = require('gulp-concat'), babel = require('gulp-babel'), ngAnnotate = require('gulp-ng-annotate'), sourcemaps = require('gulp-sourcemaps'), browserSync = require('browser-sync'), scripts = { landing: landing }; module.exports = scripts; function landing() { const src = [ 'landing/app.js', 'landing/config.js', 'landing/**/*.js', '!landing/static/**/*.js' ]; const dest = 'landing/static/vendor/js/.'; return gulp .src(src) .pipe(sourcemaps.init()) .pipe(rename({ dirname: '' })) .pipe(babel({ presets: ['es2015'] })) .on('error', function(e) { console.log('>>> ERROR', e.message); this.emit('end'); }) .pipe(ngAnnotate()) .pipe(concat('app.min.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest(dest)) .pipe(browserSync.reload({stream: true})) };
// Hlavní direktive sloupcového grafu v jQuery dashboardApp.directive('barchartJq', ['JsonChartResource', function(JsonChartResource) { return { restrict: 'E', replace: true, scope: { }, link: function(scope, elem, attrs) { /* Nutno obalit jQuery funkcionalitou aby fungovalo při testování karmou. Při klasickém spuštění dochází k obalení již na úrovni angularu. */ if(typeof elem.offset !== 'function') { elem = $(elem); } /* po http požadavku dojke k přidání grafu */ var addChart = function(opts) { correctOptsVal(opts); chartGrid(elem, opts); opts.nodeParent = elem; scope.opts = opts; }; attrs.$observe('relativeUrl', function (newRelativeUrl) { relativeUrl = newRelativeUrl; graphData = JsonChartResource.send(relativeUrl).get(); graphData.$promise.then(addChart); }); }, transclude: true, templateUrl: 'dashboard/widgets/barchartJQ/chart/template.html' }; }]);
var Lexer = module.exports = function Lexer(str) { this.tokens = []; this.line = 1; this.indented = 0; this.str = String(str) .trim() .replace(/\r\n|\r|\n *\n/g, '\n'); }; Lexer.prototype = { exec: function () { while (this.str.length) { this.next(); } this.push('eos', this.line); return this.tokens; }, token: function (type, line, match, value) { return { type: type , line: line , match: match , value: value }; }, push: function (type, line, match, value) { this.tokens.push(this.token(type, line, match, value)); }, scan: function (regexp, type, callback) { var captures , token; if (captures = regexp.exec(this.str)) { this.str = this.str.substr(captures[0].length); if (typeof callback == 'function') { callback.call(this, captures); } else { this.push(type, this.line, captures[0], captures[1]); } return true; } }, unknown: function () { throw new Error('Invalid text: ' + this.str.substr(0, 5)); }, next: function () { return this.scan(/^\n( *)(?! *-#)/, 'indent', this.indent) || this.scan(/^![]?([^\n]*)/, 'doctype') || this.scan(/^\- (\w+)*:/, 'block') || this.scan(/^\= \"(\w.*)\"/, 'include') || this.scan(/^\= (\w.*)!/, 'local') || this.scan(/^\= (\w.*)/, 'variable') || this.scan(/^\((.*)\)/, 'attrs') || this.scan(/^([a-zA-Z][a-zA-Z0-9:]*)/, 'tag') || this.scan(/^\.([\w\-]+)/, 'class') || this.scan(/^\#([\w\-]+)/, 'id') || this.scan(/^\./, 'dot') || this.scan(/^\/\/\s?(.*?)$/, 'comment') || this.scan(/^\//, 'close') || this.scan(/^(?:\| ?| )([^\n]+)/, 'text') || this.unknown(); }, indent: function (captures) { var indents = captures[1].length / 2; this.line++; if (indents % 1) { throw new Error('Invalid indentation at line ' + this.line); } else if (this.indented > indents) { while (this.indented-- > indents) { this.push("outdent", this.line); } } else if (this.indented !== indents) { this.push("indent", this.line); } else { this.push("newline", this.line); } this.indented = indents; } };
(function () { 'use strict'; angular.module('theometer.common') .service('modalService', Service); /** @ngInject */ function Service($ionicModal, $rootScope, $q, $injector, $controller) { var service = this; service.show = show; /** ---------------------------- private helper functions --------------------------- */ // Code found at https://forum.ionicframework.com/t/ionic-modal-service-with-extras/15357 function show(templateUrl, controller, parameters) { // Grab the injector and create a new scope var deferred = $q.defer(), ctrlInstance, modalScope = $rootScope.$new(), thisScopeId = modalScope.$id; $ionicModal.fromTemplateUrl(templateUrl, { scope: modalScope, animation: 'slide-in-up' }).then(function (modal) { modalScope.modal = modal; modalScope.openModal = function () { modalScope.modal.show(); }; modalScope.closeModal = function (result) { deferred.resolve(result); modalScope.modal.hide(); }; modalScope.$on('modal.hidden', function (thisModal) { if (thisModal.currentScope) { var modalScopeId = thisModal.currentScope.$id; if (thisScopeId === modalScopeId) { deferred.resolve(null); _cleanup(thisModal.currentScope); } } }); // Invoke the controller var locals = {'$scope': modalScope, 'parameters': parameters}; var ctrlEval = _evalController(controller); ctrlInstance = $controller(controller, locals); if (ctrlEval.isControllerAs) { ctrlInstance.openModal = modalScope.openModal; ctrlInstance.closeModal = modalScope.closeModal; } modalScope.modal.show(); }, function (err) { deferred.reject(err); }); return deferred.promise; } function _cleanup(scope) { scope.$destroy(); if (scope.modal) { scope.modal.remove(); } } function _evalController(ctrlName) { var result = { isControllerAs: false, controllerName: '', propName: '' }; var fragments = (ctrlName || '').trim().split(/\s+/); result.isControllerAs = fragments.length === 3 && (fragments[1] || '').toLowerCase() === 'as'; if (result.isControllerAs) { result.controllerName = fragments[0]; result.propName = fragments[2]; } else { result.controllerName = ctrlName; } return result; } } })();
var crypto = require('crypto'); var request = require('request'); var path = require('path'); var fs = require('fs'); var querystring = require('querystring'); var KdtApiProtocol = function() { } KdtApiProtocol.APP_ID_KEY = 'app_id'; KdtApiProtocol.METHOD_KEY = 'method'; KdtApiProtocol.TIMESTAMP_KEY = 'timestamp'; KdtApiProtocol.FORMAT_KEY = 'format'; KdtApiProtocol.VERSION_KEY = 'v'; KdtApiProtocol.SIGN_KEY = 'sign'; KdtApiProtocol.SIGN_METHOD_KEY = 'sign_method'; KdtApiProtocol.AllowedSignMethods = function() { return ['md5']; } KdtApiProtocol.AllowedFormats = function() { return ['json']; } KdtApiProtocol.Sign = function(app_secret, params, method) { method = method || 'md5'; params = params || {}; var keys = Object.keys(params).sort(); var text = ''; for (var i = 0; i < keys.length; i++) { var key = keys[i]; text += (key + params[key]); } return KdtApiProtocol.hash(method, [app_secret, text, app_secret].join('')); } KdtApiProtocol.hash = function(method, text) { var signature = ''; switch (method) { case 'md5': default: { var md5 = crypto.createHash('md5'); md5.update(new Buffer(text, 'utf8')); signature = md5.digest('hex'); } } return signature; } var KdtApiClient = function(app_id, app_secret) { if (!app_id || !app_secret) { throw 'app_id and app_secret is compulsory.'; } this.app_id = app_id; this.app_secret = app_secret; this.format = 'json'; this.sign_method = 'md5'; } KdtApiClient.version = '1.0'; KdtApiClient.apiEntry = 'https://open.koudaitong.com/api/entry'; KdtApiClient.prototype.Get = function(method, params, callback) { var path = KdtApiClient.apiEntry + '?' + querystring.stringify(this.build(method, params)); var data = ''; request.get(path, function(err, res, body) { var response; try { response = JSON.parse(body); } catch (e) { callback(err); return; } callback(err, response); }); } KdtApiClient.prototype.Post = function(method, params, files, callback) { params = this.build(method, params); console.log(params); var formData = {}; for (var key in params) { formData[key] = params[key]; } for (var i = 0; i < files.length; i++) { var file = files[i]; if (!file.path && !file.content) { continue; } var field = file.field || 'images[]'; var filename = 'file' + i + path.extname(file.path || 'a.png'); if (field in formData) { if (!(formData[field] instanceof Array)) { formData[field] = [formData[field]] } formData[field].push(fs.createReadStream(file.path)) continue; } formData[field] = fs.createReadStream(file.path); } request.post({ url: KdtApiClient.apiEntry, formData: formData }, function(err, res, body) { var response; try { response = JSON.parse(body); } catch (e) { callback(err); return; } callback(err, response); }); } KdtApiClient.prototype.SetFormat = function(format) { if (KdtApiProtocol.AllowedFormats().indexOf(format) < 0) { throw 'Invalid data format.'; } this.format = format; } KdtApiClient.prototype.SetSignMethod = function(method) { if (KdtApiProtocol.AllowedSignMethods().indexOf(method) < 0) { throw 'Invalid sign method.'; } this.sign_method = method; } KdtApiClient.prototype.build = function(method, api_params) { var params = {} params[KdtApiProtocol.APP_ID_KEY] = this.app_id; params[KdtApiProtocol.METHOD_KEY] = method; params[KdtApiProtocol.TIMESTAMP_KEY] = new Date(Date.now() + 8 * 3600000).toISOString().replace(/T/, ' ').replace(/\..+/, ''); params[KdtApiProtocol.FORMAT_KEY] = this.format; params[KdtApiProtocol.SIGN_METHOD_KEY] = this.sign_method; params[KdtApiProtocol.VERSION_KEY] = KdtApiClient.version; api_params = api_params || {} for (var key in api_params) { if (key in params) { throw 'Conflict parameters.' } params[key] = api_params[key]; } params[KdtApiProtocol.SIGN_KEY] = KdtApiProtocol.Sign(this.app_secret, params, this.sign_method); return params; } module.exports = KdtApiClient;
import { appleStock } from '../src'; describe('mocks/appleStock', () => { test('it should be defined', () => { expect(appleStock).toBeDefined() }) test('it should be an array', () => { expect(appleStock.length).toBeDefined() }) test('it should return [{ date, close }]', () => { const data = appleStock expect(data[0].date).toBeDefined() expect(data[0].close).toBeDefined() expect(typeof data[0].date).toEqual('string') expect(typeof data[0].close).toEqual('number') }) })
import React, { Component } from 'react'; import Target from './example1/target'; import Source from './example1/source'; class Example1 extends Component { getTarget = () => this.refs.target; render() { return ( <div style={{ background: 'red', position: 'relative', padding: '20px' }}> <Target ref="target"/> <Source target={this.getTarget}/> <div style={{ background: 'purple', height: '200px' }}/> </div> ); } } export default Example1;
angular.module('rmCornerstone').factory('rmCornerstone',[function(element){ var orthanc_url = 'http://test/'; var viewport = null; var rmCornerstone = { /** * [function description] * @param {[type]} element [description] * @param {[type]} image [description] * @return {[type]} [description] */ loadImage : function(element,image){ cornerstone.enable(element); cornerstone.loadImage('wadouri:'+orthanc_url+'/instances/'+image+'/file').then(function(image) { cornerstone.displayImage(element, image); }); }, /** * [loadViewPort description] * @param {[type]} element [description] * @param {[type]} image [description] * @return {[type]} [description] */ loadViewPort : function (element,stackImages){ viewport = element; var imageIds = []; stackImages.forEach(function(image){ imageIds.push('wadouri:'+orthanc_url+'/instances/'+image+'/file') }); var stack = { currentImageIdIndex : 0, imageIds: imageIds }; cornerstone.enable(viewport); cornerstone.loadImage('wadouri:'+orthanc_url+'/instances/'+stackImages[0]+'/file').then(function(image) { cornerstone.displayImage(viewport, image); // image enable the dicomImage element // Enable mouse and touch input cornerstoneTools.mouseInput.enable(viewport); cornerstoneTools.touchInput.enable(viewport); cornerstoneTools.addStackStateManager(element, ['stack', 'playClip']); cornerstoneTools.addToolState(element, 'stack', stack); // Enable all tools we want to use with this element cornerstoneTools.stackScroll.activate(element, 1); cornerstoneTools.stackScrollWheel.activate(element); cornerstoneTools.scrollIndicator.enable(element); }); rmCornerstone.magnifyConfig(element); rmCornerstone.handleTools(element); rmCornerstone.handleStack(element,stack,imageIds) }, /** * [function description] * @param {[type]} element [description] * @return {[type]} [description] */ resetViewPort: function(element){ cornerstone.reset(element) }, /** * [function description] * @param {[type]} element [description] * @return {[type]} [description] */ disableViewPort: function(element){ cornerstone.disable(element) }, /** * [function description] * @param {[type]} element [description] * @return {[type]} [description] */ magnifyConfig:function(element){ var magLevelRange = $("#magLevelRange") magLevelRange.on("change", function() { var config = cornerstoneTools.magnify.getConfiguration(); config.magnificationLevel = parseInt(magLevelRange.val(), 10); }); var magSizeRange = $("#magSizeRange") magSizeRange.on("change", function() { var config = cornerstoneTools.magnify.getConfiguration(); config.magnifySize = parseInt(magSizeRange.val(), 10) var magnify = $(".magnifyTool").get(0); magnify.width = config.magnifySize; magnify.height = config.magnifySize; }); var mag_config = { magnifySize: parseInt(magSizeRange.val(), 10), magnificationLevel: parseInt(magLevelRange.val(), 10) }; // cornerstoneTools.arrowAnnotate.setConfiguration(config); cornerstoneTools.magnify.setConfiguration(mag_config); }, /** * [disableTools description] * @param {[type]} element [description] * @return {[type]} [description] */ disableTools:function disableTools(element){ cornerstoneTools.zoomTouchDrag.disable(element); cornerstoneTools.rotate.disable(element, 1); cornerstoneTools.rotateTouchDrag.disable(element); cornerstoneTools.zoom.disable(element, 1); cornerstoneTools.length.disable(element, 1); cornerstoneTools.arrowAnnotate.disable(element, 1); cornerstoneTools.highlight.disable(element, 1); cornerstoneTools.simpleAngle.disable(element, 1); cornerstoneTools.simpleAngleTouch.disable(element); cornerstoneTools.dragProbe.disable(element); cornerstoneTools.dragProbeTouch.disable(element); cornerstoneTools.freehand.disable(element); cornerstoneTools.magnify.disable(element, 1); cornerstoneTools.magnifyTouchDrag.disable(element); // Enable all tools we want to use with this element cornerstoneTools.stackScroll.disable(element); cornerstoneTools.stackScrollWheel.disable(element); cornerstoneTools.scrollIndicator.enable(element); }, /** * [function description] * @param {[type]} element [description] * @return {[type]} [description] */ activateTools: function(element){ rmCornerstone.disableTools(viewport); $('.btn').removeClass('active'); $(element).addClass('active'); rmCornerstone.resetViewPort(viewport); }, /** * [function description] * @param {[type]} element [description] * @return {[type]} [description] */ handleTools: function(element){ // Zoom $('a#zoom').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.zoomTouchDrag.activate(element); cornerstoneTools.zoom.activate(element, 1); return false; }); $('a#rotate').on('click touchstart', function() { rmCornerstone.activateTools(this); // Enable all tools we want to use with this element cornerstoneTools.rotate.activate(element, 1); cornerstoneTools.rotateTouchDrag.activate(element); return false; }); $('a#length').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.length.activate(element, 1); return false; }); $('a#annotate').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.arrowAnnotate.activate(element, 1); cornerstoneTools.arrowAnnotateTouch.activate(element); return false; }); $('a#highlight').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.highlight.activate(element, 1); return false; }); $('a#save').on('click touchstart', function() { rmCornerstone.activateTools(this); var filename = $("#filename").val(); cornerstoneTools.saveAs(element, filename); return false; }); $('a#angle').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.simpleAngle.activate(element, 1); cornerstoneTools.simpleAngleTouch.activate(element); return false; }); $('a#dragProbe').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.dragProbe.activate(element,1); cornerstoneTools.dragProbeTouch.activate(element); return false; }); $('a#freehand').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.freehand.activate(element,1); return false; }); $('a#magnify').on('click touchstart', function() { rmCornerstone.activateTools(this); cornerstoneTools.magnify.activate(element, 1); cornerstoneTools.magnifyTouchDrag.activate(element); return false; }) }, handleStack : function(element, stack, imageIds){ function onViewportUpdated(e, data) { var viewport = data.viewport; $('#mrbottomleft').text("WW/WC: " + Math.round(viewport.voi.windowWidth) + "/" + Math.round(viewport.voi.windowCenter)); $('#zoomText').text("Zoom: " + viewport.scale.toFixed(2)); }; $(element).on("CornerstoneImageRendered", onViewportUpdated); function onNewImage(e, data) { var newImageIdIndex = stack.currentImageIdIndex; // Update the slider value var slider = document.getElementById('slice-range'); slider.value = newImageIdIndex; // Populate the current slice span var currentValueSpan = document.getElementById("sliceText"); currentValueSpan.textContent = "Image " + (newImageIdIndex + 1) + "/" + imageIds.length; // if we are currently playing a clip then update the FPS var playClipToolData = cornerstoneTools.getToolState(element, 'playClip'); if (playClipToolData !== undefined && !$.isEmptyObject(playClipToolData.data)) { $("#frameRate").text("FPS: " + Math.round(data.frameRate)); } else { if ($("#frameRate").text().length > 0) { $("#frameRate").text(""); } } } $(element).on("CornerstoneNewImage", onNewImage); var loopCheckbox = $("#loop"); loopCheckbox.on('change', function() { var playClipToolData = cornerstoneTools.getToolState(element, 'playClip'); playClipToolData.data[0].loop = loopCheckbox.is(":checked"); }) // Initialize range input var range, max, slice, currentValueSpan; range = document.getElementById('slice-range'); // Set minimum and maximum value range.min = 0; range.step = 1; range.max = stack.imageIds.length - 1; // Set current value range.value = stack.currentImageIdIndex; function selectImage(event){ var targetElement = document.getElementById("dicomImage"); // Get the range input value var newImageIdIndex = parseInt(event.currentTarget.value, 10); // Get the stack data var stackToolDataSource = cornerstoneTools.getToolState(targetElement, 'stack'); if (stackToolDataSource === undefined) { return; } var stackData = stackToolDataSource.data[0]; // Switch images, if necessary if(newImageIdIndex !== stackData.currentImageIdIndex && stackData.imageIds[newImageIdIndex] !== undefined) { cornerstone.loadAndCacheImage(stackData.imageIds[newImageIdIndex]).then(function(image) { var viewport = cornerstone.getViewport(targetElement); stackData.currentImageIdIndex = newImageIdIndex; cornerstone.displayImage(targetElement, image, viewport); }); } } // Bind the range slider events $("#slice-range").on("input", selectImage); }, playStack : function(element,button){ rmCornerstone.activateTools(button); // Enable all tools we want to use with this element cornerstoneTools.playClip(element, 3); return false; }, stopStack : function(element, button){ rmCornerstone.activateTools(button); cornerstoneTools.stopClip(element); $("#frameRate").text(""); return false; } } return rmCornerstone; }]);
/** * @author Mugen87 / https://github.com/Mugen87 */ const fs = require( 'fs' ); const path = require( 'path' ); const util = require( 'util' ); const expect = require( 'chai' ).expect; const fetch = require( 'node-fetch' ); // provide implementation of browser APIs used in NavMeshLoader global.fetch = fetch; global.TextDecoder = util.TextDecoder; const YUKA = require( '../../../../build/yuka.js' ); const NavMeshLoader = YUKA.NavMeshLoader; const NavMesh = YUKA.NavMesh; // describe( 'NavMeshLoader', function () { describe( '#load()', function () { it( 'should return a promise that resolves if the navigation mesh with the given URL is successfully loaded', function ( done ) { const loader = new NavMeshLoader(); const url = 'https://raw.githubusercontent.com/Mugen87/yuka/master/test/assets/navmesh/gltf/navmesh.gltf'; loader.load( url ).then( ( navMesh ) => { expect( navMesh ).is.an.instanceof( NavMesh ); expect( navMesh.regions ).to.have.lengthOf( 5 ); expect( navMesh.graph.getNodeCount() ).is.equal( 5 ); expect( navMesh.graph.getEdgeCount() ).is.equal( 8 ); done(); } ); } ); // it's not possible with node-fetch to load a glTF file with embedded buffers since this fetch // does not accept data URLs as input parameter. it( 'should be able to load a glb file', function ( done ) { const loader = new NavMeshLoader(); const url = 'https://raw.githubusercontent.com/Mugen87/yuka/master/test/assets/navmesh/glb/navmesh.glb'; loader.load( url ).then( ( navMesh ) => { expect( navMesh ).is.an.instanceof( NavMesh ); expect( navMesh.regions ).to.have.lengthOf( 5 ); expect( navMesh.graph.getNodeCount() ).is.equal( 5 ); expect( navMesh.graph.getEdgeCount() ).is.equal( 8 ); done(); } ); } ); // it's possible to test glb files with embedded buffers since NavMeshLoader // does not use fetch to return the buffer data in this case it( 'should be able to load a glb file with embedded buffer data', function ( done ) { const loader = new NavMeshLoader(); const url = 'https://raw.githubusercontent.com/Mugen87/yuka/master/test/assets/navmesh/glb-embedded/navmesh.glb'; loader.load( url ).then( ( navMesh ) => { expect( navMesh ).is.an.instanceof( NavMesh ); expect( navMesh.regions ).to.have.lengthOf( 5 ); expect( navMesh.graph.getNodeCount() ).is.equal( 5 ); expect( navMesh.graph.getEdgeCount() ).is.equal( 8 ); done(); } ); } ); it( 'should be able to load a gltf file with no primitive mode definition', function ( done ) { const loader = new NavMeshLoader(); const url = 'https://raw.githubusercontent.com/Mugen87/yuka/master/test/assets/navmesh/no-primitive-mode/navmesh.gltf'; loader.load( url ).then( ( navMesh ) => { expect( navMesh ).is.an.instanceof( NavMesh ); expect( navMesh.regions ).to.have.lengthOf( 2 ); done(); } ); } ); it( 'should use the options parameter to config the navmesh', function ( done ) { const loader = new NavMeshLoader(); const url = 'https://raw.githubusercontent.com/Mugen87/yuka/master/test/assets/navmesh/glb-embedded/navmesh.glb'; loader.load( url, { epsilonCoplanarTest: 0.5, mergeConvexRegions: false } ).then( ( navMesh ) => { expect( navMesh.epsilonCoplanarTest ).is.equal( 0.5 ); expect( navMesh.mergeConvexRegions ).to.be.false; done(); } ); } ); it( 'should reject the promise with an error if the URL das not exist', function ( done ) { const loader = new NavMeshLoader(); const url = 'https://raw.githubusercontent.com/Mugen87/yuka/master/test/assets/navmesh/glb-embedded/error'; YUKA.Logger.setLevel( YUKA.Logger.LEVEL.SILENT ); loader.load( url ).then( () => {}, ( err ) =>{ expect( err ).to.be.a( 'Error' ); expect( err.message ).to.be.equal( 'Not Found' ); done(); } ); } ); it( 'should reject the promise with an error if the asset version is not supported', function ( done ) { const loader = new NavMeshLoader(); const url = 'https://raw.githubusercontent.com/Mugen87/yuka/master/test/assets/navmesh/glb-embedded/navmeshUnsupportedAssetVersion.glb'; YUKA.Logger.setLevel( YUKA.Logger.LEVEL.SILENT ); loader.load( url ).then( ( ) => {}, ( err ) =>{ expect( err ).to.be.a( 'Error' ); expect( err.message ).to.be.equal( 'YUKA.NavMeshLoader: Unsupported asset version.' ); done(); } ); } ); } ); describe( '#parse()', function () { it( 'should parse the given array buffer without using NavMeshLoader.load()', function ( done ) { const data = fs.readFileSync( path.join( __dirname, '../../../assets/navmesh/glb-embedded/navmesh.glb' ) ); const loader = new NavMeshLoader(); loader.parse( data.buffer ).then( ( navMesh ) => { expect( navMesh ).is.an.instanceof( NavMesh ); expect( navMesh.regions ).to.have.lengthOf( 5 ); expect( navMesh.graph.getNodeCount() ).is.equal( 5 ); expect( navMesh.graph.getEdgeCount() ).is.equal( 8 ); done(); } ); } ); } ); } );
'use strict'; /** * Module dependencies. */ var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, mongoose = require('mongoose'), Admin = mongoose.model('Admin'), sha256 = require('sha256'), config = require('../env/all'); module.exports = function() { // Use local strategy passport.use(new LocalStrategy({ usernameField: 'username', passwordField: 'password' }, function(username, password, done) { Admin.findOne({ $or: [ { 'email' : username }, { 'username': username } ], password: sha256(password + config.salt) }, function(err, admin) { if (err) { return done(err); } if (!admin) { return done(null, false, { message: 'Usuário/senha inválida.' }); } if (!admin.authenticate(password)) { return done(null, false, { message: 'Usuário/senha inválida.' }); } return done(null, admin); }); } )); };
'use strict'; var MACROUTILS = require( 'osg/Utils' ); var StateAttribute = require( 'osg/StateAttribute' ); var Uniform = require( 'osg/Uniform' ); var Map = require( 'osg/Map' ); var Notify = require( 'osg/Notify' ); /** * ShadowReceiveAttribute encapsulate Shadow Main State object * @class ShadowReceiveAttribute * @inherits StateAttribute */ var ShadowReceiveAttribute = function ( lightNum, disable ) { StateAttribute.call( this ); this._lightNumber = lightNum; // see shadowSettings.js header for shadow algo param explanations // hash change var this._algoType = 'NONE'; // shadow depth bias as projected in shadow camera space texture // and viewer camera space projection introduce its bias this._bias = 0.001; // algo dependant // Exponential shadow maps use exponential // to allows fuzzy depth this._exponent0 = 0.001; this._exponent1 = 0.001; // Variance Shadow mapping use One more epsilon this._epsilonVSM = 0.001; // shader compilation different upon texture precision this._precision = 'UNSIGNED_BYTE'; // kernel size & type for pcf this._kernelSizePCF = undefined; this._fakePCF = true; this._rotateOffset = false; this._enable = !disable; }; ShadowReceiveAttribute.uniforms = {}; ShadowReceiveAttribute.prototype = MACROUTILS.objectLibraryClass( MACROUTILS.objectInherit( StateAttribute.prototype, { attributeType: 'ShadowReceive', cloneType: function () { return new ShadowReceiveAttribute( this._lightNumber, true ); }, getTypeMember: function () { return this.attributeType + this.getLightNumber(); }, getLightNumber: function () { return this._lightNumber; }, getUniformName: function ( name ) { var prefix = this.getType() + this.getLightNumber().toString(); return prefix + '_uniform_' + name; }, getRotateOffset: function () { return this._rotateOffset; }, setRotateOffset: function ( v ) { this._rotateOffset = v; }, setAlgorithm: function ( algo ) { this._algoType = algo; }, getAlgorithm: function () { return this._algoType; }, setBias: function ( bias ) { this._bias = bias; }, getBias: function () { return this._bias; }, setExponent0: function ( exp ) { this._exponent0 = exp; }, getExponent0: function () { return this._exponent0; }, setExponent1: function ( exp ) { this._exponent1 = exp; }, getExponent1: function () { return this._exponent1; }, setEpsilonVSM: function ( epsilon ) { this._epsilonVSM = epsilon; }, getEpsilonVSM: function () { return this._epsilonVSM; }, getKernelSizePCF: function () { return this._kernelSizePCF; }, setKernelSizePCF: function ( v ) { this._kernelSizePCF = v; }, getFakePCF: function () { return this._fakePCF; }, setFakePCF: function ( v ) { this._fakePCF = v; }, setPrecision: function ( precision ) { this._precision = precision; }, getPrecision: function () { return this._precision; }, setLightNumber: function ( lightNum ) { this._lightNumber = lightNum; }, getOrCreateUniforms: function () { // uniform are once per CLASS attribute, not per instance var obj = ShadowReceiveAttribute; var typeMember = this.getTypeMember(); if ( obj.uniforms[ typeMember ] ) return obj.uniforms[ typeMember ]; // Variance Shadow mapping use One more epsilon var uniformList = { bias: 'createFloat', exponent0: 'createFloat', exponent1: 'createFloat', epsilonVSM: 'createFloat' }; var uniforms = {}; window.Object.keys( uniformList ).forEach( function ( key ) { var type = uniformList[ key ]; var func = Uniform[ type ]; uniforms[ key ] = func( this.getUniformName( key ) ); }.bind( this ) ); obj.uniforms[ typeMember ] = new Map( uniforms ); return obj.uniforms[ typeMember ]; }, getExtensions: function () { var algo = this.getAlgorithm(); if ( algo === 'PCF' ) { return [ '#extension GL_OES_standard_derivatives : enable' ]; } return []; }, // Here to be common between caster and receiver // (used by shadowMap and shadow node shader) getDefines: function () { var textureType = this.getPrecision(); var algo = this.getAlgorithm(); var defines = []; var isFloat = false; var isLinearFloat = false; if ( textureType !== 'UNSIGNED_BYTE' ) isFloat = true; if ( isFloat && ( textureType === 'HALF_FLOAT_LINEAR' || textureType === 'FLOAT_LINEAR' ) ) isLinearFloat = true; if ( algo === 'ESM' ) { defines.push( '#define _ESM' ); } else if ( algo === 'NONE' ) { defines.push( '#define _NONE' ); } else if ( algo === 'PCF' ) { defines.push( '#define _PCF' ); var pcf = this.getKernelSizePCF(); if ( this._fakePCF ) { defines.push( '#define _FAKE_PCF 1' ); } switch ( pcf ) { case '4Poisson(16texFetch)': defines.push( '#define _POISSON_PCF' ); defines.push( '#define _PCFx4' ); break; case '8Poisson(32texFetch)': defines.push( '#define _POISSON_PCF' ); defines.push( '#define _PCFx9' ); break; case '16Poisson(64texFetch)': defines.push( '#define _POISSON_PCF' ); defines.push( '#define _PCFx16' ); break; case '25Poisson(100texFetch)': defines.push( '#define _POISSON_PCF' ); defines.push( '#define _PCFx25' ); break; case '32Poisson(128texFetch)': defines.push( '#define _POISSON_PCF' ); defines.push( '#define _PCFx32' ); break; case '1Band(1texFetch)': defines.push( '#define _NONE' ); defines.push( '#define _PCFx1' ); break; case '4Band(4texFetch)': defines.push( '#define _BAND_PCF' ); defines.push( '#define _PCFx4' ); break; case '9Band(9texFetch)': defines.push( '#define _BAND_PCF' ); defines.push( '#define _PCFx9' ); break; case '16Band(16texFetch)': defines.push( '#define _BAND_PCF' ); defines.push( '#define _PCFx16' ); break; case '4Tap(16texFetch)': defines.push( '#define _TAP_PCF' ); defines.push( '#define _PCFx4' ); break; case '9Tap(36texFetch)': defines.push( '#define _TAP_PCF' ); defines.push( '#define _PCFx9' ); break; case '16Tap(64texFetch)': defines.push( '#define _TAP_PCF' ); defines.push( '#define _PCFx25' ); break; default: case '1Tap(4texFetch)': defines.push( '#define _TAP_PCF' ); defines.push( '#define _PCFx1' ); break; } } else if ( algo === 'VSM' ) { defines.push( '#define _VSM' ); } else if ( algo === 'EVSM' ) { defines.push( '#define _EVSM' ); } if ( isFloat ) { defines.push( '#define _FLOATTEX' ); } if ( isLinearFloat ) { defines.push( '#define _FLOATLINEAR' ); } if ( this.getRotateOffset() ) { defines.push( '#define _ROTATE_OFFSET' ); } return defines; }, apply: function () { if ( !this._enable ) return; var uniformMap = this.getOrCreateUniforms(); uniformMap.bias.setFloat( this._bias ); uniformMap.exponent0.setFloat( this._exponent0 ); uniformMap.exponent1.setFloat( this._exponent1 ); uniformMap.epsilonVSM.setFloat( this._epsilonVSM ); }, // need a isEnabled to let the ShaderGenerator to filter // StateAttribute from the shader compilation isEnabled: function () { return this._enable; }, // Deprecated methods, should be removed in the future isEnable: function () { Notify.log( 'ShadowAttribute.isEnable() is deprecated, use isEnabled() instead' ); return this.isEnabled(); }, getHash: function () { return this.getTypeMember() + '_' + this.getAlgorithm() + '_' + this.getKernelSizePCF() + '_' + this.getFakePCF() + '_' + this.getRotateOffset(); } } ), 'osgShadow', 'ShadowReceiveAttribute' ); MACROUTILS.setTypeID( ShadowReceiveAttribute ); module.exports = ShadowReceiveAttribute;
/* */ export default async(type='GET',url = '', data = {}, method= 'fetch')=>{ type = type.toUpperCase(); if(type === 'GET'){ let dataStr = ''; Object.keys(data).forEach(key =>{ dataStr += key + '=' + data[key] + '&'; }); if (dataStr !== '') { dataStr = dataStr.substr(0,dataStr.lastIndexOf('&')); url = url + '?' + dataStr; } } if(window.fetch && method === 'fetch'){ let requestConfig = { credentials: 'include', method:type, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, mode: "cors", cache: "force-cache" }; if(type === 'POST'){ Object.defineProperty(requestConfig, 'body',{ value: JSON.stringify(data); }); } try{ var response = await fetch(url,requestConfig); var responseJson = await response.json(); }catch(error){ throw new Error(error); } return responseJson; }else{ let requestObj; if(window.XMLHttpRequest){ requestObj = new XMLHttpRequest(); }else{ requestObj = new ActiveXObject; } let sendData = ''; if(type == 'POST'){ sendData = JSON.stringify(data); } requestObj.open(type, url, true); requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); requestObj.send(sendData); requestObj.onreadystatechange = () => { if (requestObj.readyState == 4) { if (requestObj.status == 200) { let obj = requestObj.response if (typeof obj !== 'object') { obj = JSON.parse(obj); } return obj } else { throw new Error(requestObj) } } } } }
import {List, Map, fromJS} from 'immutable'; import {expect} from 'chai'; import reducer from '../src/reducer'; describe('reducer', () => { it('handles SET_STATE', () => { const initialState = Map(); const action = { type: 'SET_STATE', state: Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later'), tally: Map({Trainspotting: 1}) }) }) }; const nextState = reducer(initialState, action); expect(nextState).to.equal(fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } })); }); it('handles SET_STATE with plain JS payload', () => { const initialState = Map(); const action = { type: 'SET_STATE', state: { vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } } }; const nextState = reducer(initialState, action); expect(nextState).to.equal(fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } })); }); it('handles SET_STATE without initial state', () => { const action = { type: 'SET_STATE', state: { vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } } }; const nextState = reducer(undefined, action); expect(nextState).to.equal(fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } })); }); it('handles VOTE by setting hasVoted', () => { const state = fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } }); const action = {type: 'VOTE', entry: 'Trainspotting'}; const nextState = reducer(state, action); expect(nextState).to.equal(fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} }, hasVoted: 'Trainspotting' })); }); it('does not set hasVoted for VOTE on invalid entry', () => { const state = fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } }); const action = {type: 'VOTE', entry: 'Sunshine'}; const nextState = reducer(state, action); expect(nextState).to.equal(fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} } })); }); it ('removes hasVoted on SET_STATE if pair changes', () => { const initialState = fromJS({ vote: { pair: ['Trainspotting', '28 Days Later'], tally: {Trainspotting: 1} }, hasVoted: 'Trainspotting' }); const action = { type: 'SET_STATE', state: { vote: { pair: ['Sunshine', 'Slumdog Millionaire'] } } }; const nextState = reducer(initialState, action); expect(nextState).to.equal(fromJS({ vote: { pair: ['Sunshine', 'Slumdog Millionaire'] } })); }); });
'use strict'; module.exports = { up: function(queryInterface, DataTypes) { return queryInterface.createTable('Cards', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, number: DataTypes.STRING, token: DataTypes.STRING, serviceId: DataTypes.STRING, service: { type: DataTypes.STRING, defaultValue: 'stripe', }, data: DataTypes.JSON, createdAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW, }, updatedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW, }, confirmedAt: { type: DataTypes.DATE, }, deletedAt: { type: DataTypes.DATE, }, }); }, down: function(queryInterface) { return queryInterface.dropTable('Cards'); }, };
version https://git-lfs.github.com/spec/v1 oid sha256:e176c8b1c3f314a4e4813aa635ba29938d6bf19b0867ac6c0361e6c066f4f242 size 1087
import { Record } from 'immutable'; import { ACTIONS } from './constants'; export const AuthState = new Record({ authenticated: false, uid: null, user: null }); export function authReducer(state = new AuthState(), { payload, type }) { switch (type) { case ACTIONS.SIGN_IN_FULFILLED: return state.merge({ authenticated: true, uid: payload.uid, user: payload }); case ACTIONS.SIGN_OUT_FULFILLED: return state.merge({ authenticated: false, uid: null, user: null }); default: return state; } }
import React, { Component } from "react"; import TweetLiveCounter from "./TweetLiveCounter"; import Tweet from "./Tweet"; class Stream extends Component { constructor() { super(); this.state = { tweets: [], pending_tweets: [] }; } componentWillMount() { var self = this; var socket = io( "ws://" + window.location.hostname + ( window.location.port != "" ? ":" + window.location.port : "" ) + window.location.pathname ); socket.connect(); // Add a connect listener socket.on( "connect", function() { console.log( "Client has connected to the server!" ); } ); // Add a disconnect listener socket.on( "disconnect", function() { console.log( "The client has disconnected!" ); } ); // Recieve every new tweet socket.on( "new_tweet", function( data ) { if ( self.state.tweets.length > 20 ) { self.setState( function( state ) { state.pending_tweets.unshift( data ); return { pending_tweets: state.pending_tweets }; } ); } else { self.setState( function( state ) { state.tweets.unshift( data ); return { tweets: state.tweets }; } ); } } ); } updateTweets() { this.setState( function( state ) { state.pending_tweets.map( function( item ) { state.tweets.unshift( item ); } ); return { tweets: state.tweets, pending_tweets: [] }; } ); } render() { if ( this.state.tweets.length === 0 ) { return ( <div></div> ); } return ( <section className="cnnStream"> <header>CNN Tweet Stream</header> <div ref="indexList"> <div onClick={this.updateTweets.bind( this )}> <TweetLiveCounter counter={this.state.pending_tweets.length}/> </div> {this.state.tweets.map( ( item, index ) => { var profile_url = item.user ? item.user.profile_image_url : "http://findicons.com/files/icons/1072/face_avatars/300/i04.png"; return ( <Tweet key={index} profileImage={profile_url} tweet={item.text} favorite_count={item.favorite_count} retweet_count={item.retweet_count}> </Tweet> ); } )} </div> </section> ); } } Stream.defaultProps = { items: [] }; export default Stream;
/* global $ */ /* global GOVUK */ // Warn about using the kit in production if ( window.sessionStorage && window.sessionStorage.getItem('prototypeWarning') !== 'false' && window.console && window.console.info ) { window.console.info('GOV.UK Prototype Kit - do not use for production') window.sessionStorage.setItem('prototypeWarning', true) } $(document).ready(function () { // Use GOV.UK selection-buttons.js to set selected // and focused states for block labels var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']") new GOVUK.SelectionButtons($blockLabels) // eslint-disable-line // Use GOV.UK shim-links-with-button-role.js to trigger a link styled to look like a button, // with role="button" when the space key is pressed. GOVUK.shimLinksWithButtonRole.init() // Show and hide toggled content // Where .block-label uses the data-target attribute // to toggle hidden content var showHideContent = new GOVUK.ShowHideContent() showHideContent.init() if(window.location.href.indexOf("upload") > -1){ $('#photo').change(function(e){ // todo: check that file is actually chosen!! window.location.href = 'loading'; }); } if(window.location.href.indexOf("add-poa") > -1){ $('#file').change(function(e){ // todo: check that file is actually chosen!! window.location.href = 'loading-poa'; }); } if(window.location.href.indexOf("add-poage") > -1){ $('#file').change(function(e){ // todo: check that file is actually chosen!! window.location.href = 'loading-poage'; }); } if(window.location.href.indexOf("loading-poa") > -1){ setTimeout(function(){ window.location.href = 'document-accepted'; }, 2000) } if(window.location.href.indexOf("loading-poage") > -1){ setTimeout(function(){ window.location.href = 'eligible-nonverify'; }, 2000) } if(window.location.href.indexOf("loading") > -1){ setTimeout(function(){ window.location.href = 'good-photo'; }, 3000) } if(window.location.href.indexOf("upload") > -1){ $('.in-progress').click(function(e){ e.preventDefault(); window.alert("This feature is currently in progress."); }); } })
'use strict'; var tm = require( '../lib/index.js' ); var corpus = new tm.Corpus( [] ); corpus.addDoc( 'wat you cash money go to boots and cats and dogs with me' ); corpus.removeWords( tm.STOPWORDS.EN ) ; var terms = new tm.Terms( corpus ); console.log( terms );
import './main'; import './table'; import './form'; import './nestedForm';
import React from 'react'; export default class About extends React.Component { render() { return (<div className={'container'} style={{ maxWidth: '960px' }}> <section className={'section'}> <h1 className={'title'}>About</h1> <h2 className={'subtitle'}>AutoScout is a heavy work-in-progress website dedicated to data visualization of FIRST Robotics Competition (FRC). The goal of this site is to provide simple, yet meaningful, data visualization components to all members of the FRC community - mentors, students, and curious parents alike.</h2> </section> <section className={'section'}> <h1 className={'title'}>Open Source</h1> <h2 className={'subtitle'}>The project is hosted on GitHub in two separate repositories: <a href={'https://github.com/tervay/autoscout'}>front-end</a> and <a href={'https://github.com/tervay/autoscout-api'}>back-end</a>. The front-end is written in JavaScript (ES6) and uses React.js, among many other helpful libraries. The back-end is written in Python 3.6 and uses Django, also with lots of other libraries. Both projects are licensed under the MIT license. Feel free to open an issue or submit a pull request! <br /><br /> This project would certainly not be possible without the great people over at <a href={'https://www.thebluealliance.com/'}>TheBlueAlliance</a> and all the people in the FRC family. Thank you to everyone involved in FRC! </h2> </section> <section className={'section'}> <h1 className={'title'}>About the Author</h1> <h2 className={'subtitle'}>Hi, I'm Justin Tervay. I was a student on FRC Team 2791, Shaker Robotics, from 2012-15. After graduating, I was a remote mentor / adviser to the team in 2016 and 2017. Currently, I mentor team 340, Greater Rochester Robotics. </h2> </section> </div>); } }
// This module creates a digital timer that will run in sync with the clock // animation created by the clock.js module, with its output formatted as // hh:mm:ss (hh=hours, mm=minutes, ss= seconds). It also includes, with its // setDirection() and getDirection() methods, functionality to track the // forward vs. reverse direction of time-flow/clock-animation independently of // the clock.js module. const clockTime = function() { // Default time values let clockTime = 0; let formattedClockTime = { hours: "12", minutes: "00", seconds: "00" }; let timerDirection = "forward"; // Default time-flow direction // Set time-flow direction to either "forward" or "reverse" function setDirection(direction) { timerDirection = direction; } // Report currently-set time-flow direction function getDirection() { return timerDirection; } // Update clockTime variable by +1sec (forward direction) or -1sec (reverse // direction) for each elapsed tickInterval. function timer(increment) { // Add increment passed as argument (either +1sec or -1sec) to clockTime clockTime += increment; } // Reset the time when it passes 12:00:00 in either forward or reverse direction. function resetTime(reversingPastZero = false) { // Forward is default. // For forward direction, i.e. clock has run for 12 hours and is continuing. if(!reversingPastZero) { // Reset time to 0. clockTime = 0; formattedClockTime = { hours: "12", minutes: "00", seconds: "00" }; } else { // For reverse direction, i.e. clock has run backwards to "zero". // Reset time to 11:59:59. clockTime = 11*60*60 + 59*60 + 59; // 11hrs, 59min, 59sec in seconds. } } // Helper function used in getClockTime(), below. function formatTimeRange(unformatted) { // If less than 10 units of the given time Range have passed, e.g. hours < 10... if ( unformatted < 10 ) { // ...only change the 2nd digit return "0" + unformatted; } else { // Otherwise change both digits. return unformatted; } } // Get and convert current (unformatted) clockTime in seconds to hh:mm:ss // formattedClockTime. function getClockTime() { // If clockTime is negative (i.e. if the clock has been run reverse-direction // past zero), call resetTime() with its "reversingPastZero" argument set to // "true"... if( clockTime < 0 ) { resetTime(true); // ... and call the present function recursively. getClockTime(); } // A set of variables to help make the time-logic that follows easier to reason // about. let seconds = clockTime; let minutes = Math.floor( clockTime / 60 ); let hours = Math.floor( clockTime / ( 60*60 ) ); // console.log(hours + ", " + minutes + ", " + seconds); // (for debugging) // If less than one minute has passed, i.e. minutes < 1... if ( minutes < 1 ) { // ...only change the seconds formattedClockTime.seconds = formatTimeRange( seconds ); } // Otherwise, if less than one hour has passed, i.e. hours < 1... else if ( hours < 1) { // ...change the seconds seconds = seconds % 60; formattedClockTime.seconds = formatTimeRange( seconds ); // ...and change the minutes. formattedClockTime.minutes = formatTimeRange( minutes ); } // Otherwise, if less than 12 hours have passed, i.e. hours < 12... else if ( hours < 12 ) { // ...change the seconds seconds = seconds % 60; formattedClockTime.seconds = formatTimeRange( seconds ); // ...change the minutes minutes = minutes % 60; formattedClockTime.minutes = formatTimeRange( minutes ); // ...and change the hours formattedClockTime.hours = formatTimeRange( hours ); } // Otherwise, if 12 hours have passed, i.e. hours >= 12... else if ( hours >= 12 ) { // ...reset the clock to 0 resetTime(); // ...and get time again getClockTime(); } return formattedClockTime; } return { setDirection : setDirection, getDirection : getDirection, timer : timer, resetTime : resetTime, getClockTime : getClockTime }; }();
// gm - Copyright Aaron Heckmann <aaron.heckmann+github@gmail.com> (MIT Licensed) var assert = require('assert') module.exports = function (_, dir, finish, gm) { if (!gm.integration) return finish(); var filename = dir + '/autoOrient.jpg'; gm(dir + '/originalSideways.jpg').orientation(function (err, o) { if (err) return finish(err); assert.equal('RightTop', o); assert.ok(!! this.data['Profile-EXIF'], 'No Profile-EXIF data found'); assert.equal('155x460', this.data.Geometry); // this image is sideways, but may be auto-oriented by modern OS's // try opening it in a browser to see its true orientation gm(dir + '/originalSideways.jpg') .autoOrient() .stream(function (err, stream) { if (err) return finish(err); gm(stream).identify(function (err, data) { if (err) return finish(err); assert.equal('Unknown', data.Orientation); assert.ok(! this.data['Profile-EXIF'], 'Profile-EXIF still exists'); assert.equal('460x155', data.Geometry); finish(err); }) }) }); }
"use strict"; var BinaryTree = require('../basic/binarytree/simple'); require('should'); describe('binarytree', function() { it('traverse should get sequene in order', function() { var na = {left: null, right: null, value: 'A'}; var nb = {left: null, right: null, value: 'B'}; var nc = {left: na, right: nb, value: 'C'}; var tree = new BinaryTree(nc); var traverse_str = ''; tree.breadth_first_traverse(function(node) { traverse_str += node.value; }); traverse_str.should.be.eql('CAB'); }); });
import Vue from 'vue' import Vuex from 'vuex' import createLogger from 'vuex/dist/logger' import state from './state.js' import getters from './getters.js' import actions from './actions.js' import mutations from './mutations.js' Vue.use(Vuex) export default new Vuex.Store({ state, getters, actions, mutations, plugins: (process.env.NODE_ENV === "production") ? [] : [createLogger()] })
import parser from '../src/core/parser/parser'; const FormatJSON = (str) => JSON.stringify(str, null, 2); test('#parser - 1', () => { expect(FormatJSON(parser(`<div></div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [], "directives": {}, "children": [] } ] })); }); test('#parser - 2', () => { expect(FormatJSON(parser(`<img/>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "img", "attributes": [], "directives": {}, "children": [] } ] })); }); test('#parser - 3', () => { expect(FormatJSON(parser(`<img>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "img", "attributes": [], "directives": {}, "children": [] } ] })); }); test('#parser - 4', () => { expect(FormatJSON(parser(`<img></img>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "img", "attributes": [], "directives": {}, "children": [] } ] })); }); test('#parser - 5', () => { expect(FormatJSON(parser(`<div><img a=1>2</div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [], "directives": {}, "children": [ { "type": "Element", "name": "img", "attributes": [ { "type": "Attribute", "name": "a", "value": "1" } ], "directives": {}, "children": [] }, { "type": "Text", "value": "2" } ] } ] })); }); test('#parser - 6', () => { expect(FormatJSON(parser(`<div a=2></div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [ { "type": "Attribute", "name": "a", "value": "2" } ], "directives": {}, "children": [] } ] })); }); test('#parser - 7', () => { expect(FormatJSON(parser(`<div>1</div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } ] })); }); test('#parser - 8', () => { expect(FormatJSON(parser(`<block :if={a}>1</block>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "If", "test": "{a}", "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } } ] })); }); test('#parser - 9', () => { expect(FormatJSON(parser(`<div :for={list} :item="item" :itemIndex="i"></div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "For", "test": "{list}", "init": { "item": { "type": "Expression", "value": { "type": "Identifier", "name": "item" } }, "index": { "type": "Expression", "value": { "type": "Identifier", "name": "index" } } }, "body": { "type": "Element", "name": "div", "attributes": [], "directives": {}, "children": [] } } ] })); }); test('#parser - 10', () => { expect(FormatJSON(parser(`<div :for={list} :for-item="item" :for-index="i" class="a"></div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "For", "test": "{list}", "init": { "item": "item", "index": "i" }, "body": { "type": "Element", "name": "div", "attributes": [ { "type": "Attribute", "name": "class", "value": "a" } ], "directives": {}, "children": [] } } ] })); }); test('#parser - 11', () => { expect(FormatJSON(parser(` <div> <block :if={a}>1</block> <block :elif={b}> <block :if={c}>1</block> <block :elif={d}>1</block> </block> <block :else></block> </div> `))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Text", "value": "\n" }, { "type": "Element", "name": "div", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "\n " }, { "type": "If", "test": "{a}", "alternate": { "type": "If", "test": "{b}", "alternate": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [] }, "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "\n " }, { "type": "If", "test": "{c}", "alternate": { "type": "If", "test": "{d}", "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } }, "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } }, { "type": "Text", "value": "\n " } ] } }, "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } }, { "type": "Text", "value": "\n" } ] }, { "type": "Text", "value": "\n" } ] })); }); test('#parser - 12', () => { expect(FormatJSON(parser(`<div> <block :if={{a}>1</block> <block :elif={{b}}>1</block> <block :elif={{c}}>1</block> <block :else></block> </div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "\n" }, { "type": "If", "test": "{{a}", "alternate": { "type": "If", "test": { "type": "Expression", "value": { "type": "Identifier", "name": "b" } }, "alternate": { "type": "If", "test": { "type": "Expression", "value": { "type": "Identifier", "name": "c" } }, "alternate": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [] }, "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } }, "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } }, "consequent": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "1" } ] } }, { "type": "Text", "value": "\n" } ] } ] })); }); test('#parser - 13', () => { expect(FormatJSON(parser(` <div> <block :for="{{list}}" :for-item="item" :for-index="index"> <div @onClick={{this.onClick()}}> {{item.name}} </div>· </block> </div> `))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Text", "value": "\n" }, { "type": "Element", "name": "div", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "\n " }, { "type": "For", "test": { "type": "Expression", "value": { "type": "Identifier", "name": "list" } }, "init": { "item": "item", "index": "index" }, "body": { "type": "Element", "name": "block", "attributes": [], "directives": {}, "children": [ { "type": "Text", "value": "\n " }, { "type": "Element", "name": "div", "attributes": [], "directives": { "onClick": { "type": "Expression", "value": { "type": "CallExpression", "arguments": [], "callee": { "type": "MemberExpression", "computed": false, "object": { "type": "ThisExpression" }, "property": { "type": "Identifier", "name": "onClick" } } } } }, "children": [ { "type": "Text", "value": "\n " }, { "type": "Expression", "value": { "type": "MemberExpression", "computed": false, "object": { "type": "Identifier", "name": "item" }, "property": { "type": "Identifier", "name": "name" } } }, { "type": "Text", "value": "\n " } ] }, { "type": "Text", "value": "·\n " } ] } }, { "type": "Text", "value": "\n" } ] }, { "type": "Text", "value": "\n" } ] })); }); test('#parser - 14', () => { expect(FormatJSON(parser(` <Test/>122121 `))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Text", "value": "\n" }, { "type": "Element", "name": "Test", "attributes": [], "directives": {}, "children": [] }, { "type": "Text", "value": "122121\n" } ] })); }); test('#parser - 15', () => { expect(FormatJSON(parser(` <!-- a aaa `))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Text", "value": "\n" }, { "type": "Comment", "value": " a\n\naaa\n" } ] })); }); test('#parser - 16', () => { expect(FormatJSON(parser(`{ a`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Text", "value": "{ a" } ] })); }); test('#parser - 17', () => { expect(FormatJSON(parser(`<a <!-- a -->></a>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "a", "attributes": [ { "type": "Attribute", "name": "<!--", "value": { "type": "Expression", "value": { "type": "Compound", "body": [] } } }, { "type": "Attribute", "name": "a", "value": { "type": "Expression", "value": { "type": "Compound", "body": [] } } }, { "type": "Attribute", "name": "--", "value": { "type": "Expression", "value": { "type": "Compound", "body": [] } } } ], "directives": {}, "children": [ { "type": "Text", "value": ">" } ] } ] })); }); test('#parser - 18', () => { expect(FormatJSON(parser(`<a></a>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "a", "attributes": [], "directives": {}, "children": [] } ] })); }); test('#parser - 19', () => { expect(FormatJSON(parser(`<div class=1// />`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [ { "type": "Attribute", "name": "class", "value": "1//" } ], "directives": {}, "children": [] } ] })); }); test('#parser - 20', () => { expect(FormatJSON(parser(`<div @onClick={{fn(1, 2, 3)}}></div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [], "directives": { "onClick": { "type": "Expression", "value": { "type": "CallExpression", "arguments": [ { "type": "Literal", "value": 1, "raw": "1" }, { "type": "Literal", "value": 2, "raw": "2" }, { "type": "Literal", "value": 3, "raw": "3" } ], "callee": { "type": "Identifier", "name": "fn" } } } }, "children": [] } ] } )); }); test('#parser - 21', () => { expect(FormatJSON(parser(`{ {div`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Text", "value": "{ {div" } ] })); }); test('#parser - 22', () => { expect(FormatJSON(parser(`<div a=`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Text", "value": "<div a=" } ] })) }); test('#parser - 22', () => { expect(FormatJSON(parser(`<div @onClick={{fn(1, 2, 3)}}></div>`))).toBe(FormatJSON({ "type": "Program", "body": [ { "type": "Element", "name": "div", "attributes": [], "directives": { "onClick": { "type": "Expression", "value": { "type": "CallExpression", "arguments": [ { "type": "Literal", "value": 1, "raw": "1" }, { "type": "Literal", "value": 2, "raw": "2" }, { "type": "Literal", "value": 3, "raw": "3" } ], "callee": { "type": "Identifier", "name": "fn" } } } }, "children": [] } ] })) });
var textInput = document.querySelectorAll('input[type="text"]'); var currentIdx = 0; var limitIdx = textInput.length; chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { if (currentIdx==limitIdx) { currentIdx=0; }; var inputElement = textInput[currentIdx]; inputElement.focus(); currentIdx++; });
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M16 4H8c-.55 0-1 .45-1 1v13c0 .55.45 1 1 1h8c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM4 6c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1s1-.45 1-1V7c0-.55-.45-1-1-1zM20 6c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1s1-.45 1-1V7c0-.55-.45-1-1-1z" /> , 'AmpStoriesRounded');
exports.Class = require("./lib/class"); exports.createLimitter = require("./lib/limitter"); exports.StringUtil = require("./lib/string_util"); exports.DateTime = require("./lib/date_time");
// CodeMirror version 2.32 // // All functions that need access to the editor's state live inside // the CodeMirror function. Below that, at the bottom of the file, // some utilities are defined. // CodeMirror is the only global var we claim var CodeMirror = (function() { // This is the function that produces an editor instance. Its // closure is used to store the editor state. function CodeMirror(place, givenOptions) { // Determine effective options based on given values and defaults. var options = {}, defaults = CodeMirror.defaults; for (var opt in defaults) if (defaults.hasOwnProperty(opt)) options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt]; // The element in which the editor lives. var wrapper = document.createElement("div"); wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : ""); // This mess creates the base DOM structure for the editor. wrapper.innerHTML = '<div style="overflow: hidden; position: relative; width: 3px; height: 0px;">' + // Wraps and hides input textarea '<textarea style="position: absolute; padding: 0; width: 1px; height: 1em" wrap="off" ' + 'autocorrect="off" autocapitalize="off"></textarea></div>' + '<div class="CodeMirror-scrollbar">' + // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself. '<div class="CodeMirror-scrollbar-inner">' + // The empty scrollbar content, used solely for managing the scrollbar thumb. '</div></div>' + // This must be before the scroll area because it's float-right. '<div class="CodeMirror-scroll" tabindex="-1">' + '<div style="position: relative">' + // Set to the height of the text, causes scrolling '<div style="position: relative">' + // Moved around its parent to cover visible view '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' + // Provides positioning relative to (visible) text origin '<div class="CodeMirror-lines"><div style="position: relative; z-index: 0">' + // Used to measure text size '<div style="position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;"></div>' + '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor '<pre class="CodeMirror-cursor" style="visibility: hidden">&#160;</pre>' + // Used to force a width '<div style="position: relative; z-index: -1"></div><div></div>' + // DIVs containing the selection and the actual code '</div></div></div></div></div>'; if (place.appendChild) place.appendChild(wrapper); else place(wrapper); // I've never seen more elegant code in my life. var inputDiv = wrapper.firstChild, input = inputDiv.firstChild, scroller = wrapper.lastChild, code = scroller.firstChild, mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild, lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild, cursor = measure.nextSibling, widthForcer = cursor.nextSibling, selectionDiv = widthForcer.nextSibling, lineDiv = selectionDiv.nextSibling, scrollbar = inputDiv.nextSibling, scrollbarInner = scrollbar.firstChild; themeChanged(); keyMapChanged(); // Needed to hide big blue blinking cursor on Mobile Safari if (ios) input.style.width = "0px"; if (!webkit) scroller.draggable = true; lineSpace.style.outline = "none"; if (options.tabindex != null) input.tabIndex = options.tabindex; if (options.autofocus) focusInput(); if (!options.gutter && !options.lineNumbers) gutter.style.display = "none"; // Needed to handle Tab key in KHTML if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute"; // Check for OS X >= 10.7. If so, we need to force a width on the scrollbar, and // make it overlap the content. (But we only do this if the scrollbar doesn't already // have a natural width. If the mouse is plugged in or the user sets the system pref // to always show scrollbars, the scrollbar shouldn't overlap.) if (mac_geLion) { scrollbar.className += (overlapScrollbars() ? " cm-sb-overlap" : " cm-sb-nonoverlap"); } else if (ie_lt8) { // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). scrollbar.className += " cm-sb-ie7"; } // Check for problem with IE innerHTML not working when we have a // P (or similar) parent node. try { stringWidth("x"); } catch (e) { if (e.message.match(/runtime/i)) e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)"); throw e; } // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval. var poll = new Delayed(), highlight = new Delayed(), blinker; // mode holds a mode API object. doc is the tree of Line objects, // work an array of lines that should be parsed, and history the // undo history (instance of History constructor). var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused; loadMode(); // The selection. These are always maintained to point at valid // positions. Inverted is used to remember that the user is // selecting bottom-to-top. var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false}; // Selection-related flags. shiftSelecting obviously tracks // whether the user is holding shift. var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, lastScrollLeft = 0, draggingText, overwrite = false, suppressEdits = false; // Variables used by startOperation/endOperation to track what // happened during the operation. var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone, gutterDirty, callbacks; // Current visible range (may be bigger than the view window). var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0; // bracketHighlighted is used to remember that a bracket has been // marked. var bracketHighlighted; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. var maxLine = "", updateMaxLine = false, maxLineChanged = true; var tabCache = {}; // Initialize the content. operation(function(){setValue(options.value || ""); updateInput = false;})(); var history = new History(); // Register our event handlers. connect(scroller, "mousedown", operation(onMouseDown)); connect(scroller, "dblclick", operation(onDoubleClick)); connect(lineSpace, "selectstart", e_preventDefault); // Gecko browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for Gecko. if (!gecko) connect(scroller, "contextmenu", onContextMenu); connect(scroller, "scroll", onScroll); connect(scrollbar, "scroll", onScroll); connect(scrollbar, "mousedown", function() {if (focused) setTimeout(focusInput, 0);}); connect(scroller, "mousewheel", onMouseWheel); connect(scroller, "DOMMouseScroll", onMouseWheel); connect(window, "resize", function() {updateDisplay(true);}); connect(input, "keyup", operation(onKeyUp)); connect(input, "input", fastPoll); connect(input, "keydown", operation(onKeyDown)); connect(input, "keypress", operation(onKeyPress)); connect(input, "focus", onFocus); connect(input, "blur", onBlur); if (options.dragDrop) { connect(scroller, "dragstart", onDragStart); function drag_(e) { if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; e_stop(e); } connect(scroller, "dragenter", drag_); connect(scroller, "dragover", drag_); connect(scroller, "drop", operation(onDrop)); } connect(scroller, "paste", function(){focusInput(); fastPoll();}); connect(input, "paste", fastPoll); connect(input, "cut", operation(function(){ if (!options.readOnly) replaceSelection(""); })); // Needed to handle Tab key in KHTML if (khtml) connect(code, "mouseup", function() { if (document.activeElement == input) input.blur(); focusInput(); }); // IE throws unspecified error in certain cases, when // trying to access activeElement before onload var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { } if (hasFocus || options.autofocus) setTimeout(onFocus, 20); else onBlur(); function isLine(l) {return l >= 0 && l < doc.size;} // The instance object that we'll return. Mostly calls out to // local functions in the CodeMirror function. Some do some extra // range checking and/or clipping. operation is used to wrap the // call so that changes it makes are tracked, and the display is // updated afterwards. var instance = wrapper.CodeMirror = { getValue: getValue, setValue: operation(setValue), getSelection: getSelection, replaceSelection: operation(replaceSelection), focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();}, setOption: function(option, value) { var oldVal = options[option]; options[option] = value; if (option == "mode" || option == "indentUnit") loadMode(); else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();} else if (option == "readOnly" && !value) {resetInput(true);} else if (option == "theme") themeChanged(); else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)(); else if (option == "tabSize") updateDisplay(true); else if (option == "keyMap") keyMapChanged(); if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") { gutterChanged(); updateDisplay(true); } }, getOption: function(option) {return options[option];}, undo: operation(undo), redo: operation(redo), indentLine: operation(function(n, dir) { if (typeof dir != "string") { if (dir == null) dir = options.smartIndent ? "smart" : "prev"; else dir = dir ? "add" : "subtract"; } if (isLine(n)) indentLine(n, dir); }), indentSelection: operation(indentSelected), historySize: function() {return {undo: history.done.length, redo: history.undone.length};}, clearHistory: function() {history = new History();}, setHistory: function(histData) { history = new History(); history.done = histData.done; history.undone = histData.undone; }, getHistory: function() { history.time = 0; return {done: history.done.concat([]), undone: history.undone.concat([])}; }, matchBrackets: operation(function(){matchBrackets(true);}), getTokenAt: operation(function(pos) { pos = clipPos(pos); return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch); }), getStateAfter: function(line) { line = clipLine(line == null ? doc.size - 1: line); return getStateBefore(line + 1); }, cursorCoords: function(start, mode) { if (start == null) start = sel.inverted; return this.charCoords(start ? sel.from : sel.to, mode); }, charCoords: function(pos, mode) { pos = clipPos(pos); if (mode == "local") return localCoords(pos, false); if (mode == "div") return localCoords(pos, true); return pageCoords(pos); }, coordsChar: function(coords) { var off = eltOffset(lineSpace); return coordsChar(coords.x - off.left, coords.y - off.top); }, markText: operation(markText), setBookmark: setBookmark, findMarksAt: findMarksAt, setMarker: operation(addGutterMarker), clearMarker: operation(removeGutterMarker), setLineClass: operation(setLineClass), hideLine: operation(function(h) {return setLineHidden(h, true);}), showLine: operation(function(h) {return setLineHidden(h, false);}), onDeleteLine: function(line, f) { if (typeof line == "number") { if (!isLine(line)) return null; line = getLine(line); } (line.handlers || (line.handlers = [])).push(f); return line; }, lineInfo: lineInfo, addWidget: function(pos, node, scroll, vert, horiz) { pos = localCoords(clipPos(pos)); var top = pos.yBot, left = pos.x; node.style.position = "absolute"; code.appendChild(node); if (vert == "over") top = pos.y; else if (vert == "near") { var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()), hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft(); if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight) top = pos.y - node.offsetHeight; if (left + node.offsetWidth > hspace) left = hspace - node.offsetWidth; } node.style.top = (top + paddingTop()) + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = code.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") left = 0; else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2; node.style.left = (left + paddingLeft()) + "px"; } if (scroll) scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight); }, lineCount: function() {return doc.size;}, clipPos: clipPos, getCursor: function(start) { if (start == null) start = sel.inverted; return copyPos(start ? sel.from : sel.to); }, somethingSelected: function() {return !posEq(sel.from, sel.to);}, setCursor: operation(function(line, ch, user) { if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user); else setCursor(line, ch, user); }), setSelection: operation(function(from, to, user) { (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from)); }), getLine: function(line) {if (isLine(line)) return getLine(line).text;}, getLineHandle: function(line) {if (isLine(line)) return getLine(line);}, setLine: operation(function(line, text) { if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length}); }), removeLine: operation(function(line) { if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0})); }), replaceRange: operation(replaceRange), getRange: function(from, to, lineSep) {return getRange(clipPos(from), clipPos(to), lineSep);}, triggerOnKeyDown: operation(onKeyDown), execCommand: function(cmd) {return commands[cmd](instance);}, // Stuff used by commands, probably not much use to outside code. moveH: operation(moveH), deleteH: operation(deleteH), moveV: operation(moveV), toggleOverwrite: function() { if(overwrite){ overwrite = false; cursor.className = cursor.className.replace(" CodeMirror-overwrite", ""); } else { overwrite = true; cursor.className += " CodeMirror-overwrite"; } }, posFromIndex: function(off) { var lineNo = 0, ch; doc.iter(0, doc.size, function(line) { var sz = line.text.length + 1; if (sz > off) { ch = off; return true; } off -= sz; ++lineNo; }); return clipPos({line: lineNo, ch: ch}); }, indexFromPos: function (coords) { if (coords.line < 0 || coords.ch < 0) return 0; var index = coords.ch; doc.iter(0, coords.line, function (line) { index += line.text.length + 1; }); return index; }, scrollTo: function(x, y) { if (x != null) scroller.scrollLeft = x; if (y != null) scrollbar.scrollTop = y; updateDisplay([]); }, getScrollInfo: function() { return {x: scroller.scrollLeft, y: scrollbar.scrollTop, height: scrollbar.scrollHeight, width: scroller.scrollWidth}; }, setSize: function(width, height) { function interpret(val) { val = String(val); return /^\d+$/.test(val) ? val + "px" : val; } if (width != null) wrapper.style.width = interpret(width); if (height != null) scroller.style.height = interpret(height); }, operation: function(f){return operation(f)();}, compoundChange: function(f){return compoundChange(f);}, refresh: function(){ updateDisplay(true, null, lastScrollTop); if (scrollbar.scrollHeight > lastScrollTop) scrollbar.scrollTop = lastScrollTop; }, getInputField: function(){return input;}, getWrapperElement: function(){return wrapper;}, getScrollerElement: function(){return scroller;}, getGutterElement: function(){return gutter;} }; function getLine(n) { return getLineAt(doc, n); } function updateLineHeight(line, height) { gutterDirty = true; var diff = height - line.height; for (var n = line; n; n = n.parent) n.height += diff; } function setValue(code) { var top = {line: 0, ch: 0}; updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length}, splitLines(code), top, top); updateInput = true; } function getValue(lineSep) { var text = []; doc.iter(0, doc.size, function(line) { text.push(line.text); }); return text.join(lineSep || "\n"); } function onScroll(e) { if (scroller.scrollTop) { scrollbar.scrollTop += scroller.scrollTop; scroller.scrollTop = 0; } if (lastScrollTop != scrollbar.scrollTop || lastScrollLeft != scroller.scrollLeft) { lastScrollTop = scrollbar.scrollTop; lastScrollLeft = scroller.scrollLeft; updateDisplay([]); if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px"; if (options.onScroll) options.onScroll(instance); } } function onMouseDown(e) { setShift(e_prop(e, "shiftKey")); // Check whether this is a click in a widget for (var n = e_target(e); n != wrapper; n = n.parentNode) if (n.parentNode == code && n != mover) return; // See if this is a click in the gutter for (var n = e_target(e); n != wrapper; n = n.parentNode) if (n.parentNode == gutterText) { if (options.onGutterClick) options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e); return e_preventDefault(e); } var start = posFromMouse(e); switch (e_button(e)) { case 3: if (gecko) onContextMenu(e); return; case 2: if (start) setCursor(start.line, start.ch, true); setTimeout(focusInput, 20); e_preventDefault(e); return; } // For button 1, if it was clicked inside the editor // (posFromMouse returning non-null), we have to adjust the // selection. if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;} if (!focused) onFocus(); var now = +new Date, type = "single"; if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { type = "triple"; e_preventDefault(e); setTimeout(focusInput, 20); selectLine(start.line); } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { type = "double"; lastDoubleClick = {time: now, pos: start}; e_preventDefault(e); var word = findWordAt(start); setSelectionUser(word.from, word.to); } else { lastClick = {time: now, pos: start}; } var last = start, going; if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) && !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { // Let the drag handler handle this. if (webkit) scroller.draggable = true; function dragEnd(e2) { if (webkit) scroller.draggable = false; draggingText = false; up(); drop(); if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { e_preventDefault(e2); setCursor(start.line, start.ch, true); focusInput(); } } var up = connect(document, "mouseup", operation(dragEnd), true); var drop = connect(scroller, "drop", operation(dragEnd), true); draggingText = true; // IE's approach to draggable if (scroller.dragDrop) scroller.dragDrop(); return; } e_preventDefault(e); if (type == "single") setCursor(start.line, start.ch, true); var startstart = sel.from, startend = sel.to; function doSelect(cur) { if (type == "single") { setSelectionUser(start, cur); } else if (type == "double") { var word = findWordAt(cur); if (posLess(cur, startstart)) setSelectionUser(word.from, startend); else setSelectionUser(startstart, word.to); } else if (type == "triple") { if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({line: cur.line, ch: 0})); else setSelectionUser(startstart, clipPos({line: cur.line + 1, ch: 0})); } } function extend(e) { var cur = posFromMouse(e, true); if (cur && !posEq(cur, last)) { if (!focused) onFocus(); last = cur; doSelect(cur); updateInput = false; var visible = visibleLines(); if (cur.line >= visible.to || cur.line < visible.from) going = setTimeout(operation(function(){extend(e);}), 150); } } function done(e) { clearTimeout(going); var cur = posFromMouse(e); if (cur) doSelect(cur); e_preventDefault(e); focusInput(); updateInput = true; move(); up(); } var move = connect(document, "mousemove", operation(function(e) { clearTimeout(going); e_preventDefault(e); if (!ie && !e_button(e)) done(e); else extend(e); }), true); var up = connect(document, "mouseup", operation(done), true); } function onDoubleClick(e) { for (var n = e_target(e); n != wrapper; n = n.parentNode) if (n.parentNode == gutterText) return e_preventDefault(e); e_preventDefault(e); } function onDrop(e) { if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; e.preventDefault(); var pos = posFromMouse(e, true), files = e.dataTransfer.files; if (!pos || options.readOnly) return; if (files && files.length && window.FileReader && window.File) { function loadFile(file, i) { var reader = new FileReader; reader.onload = function() { text[i] = reader.result; if (++read == n) { pos = clipPos(pos); operation(function() { var end = replaceRange(text.join(""), pos, pos); setSelectionUser(pos, end); })(); } }; reader.readAsText(file); } var n = files.length, text = Array(n), read = 0; for (var i = 0; i < n; ++i) loadFile(files[i], i); } else { // Don't do a replace if the drop happened inside of the selected text. if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return; try { var text = e.dataTransfer.getData("Text"); if (text) { compoundChange(function() { var curFrom = sel.from, curTo = sel.to; setSelectionUser(pos, pos); if (draggingText) replaceRange("", curFrom, curTo); replaceSelection(text); focusInput(); }); } } catch(e){} } } function onDragStart(e) { var txt = getSelection(); e.dataTransfer.setData("Text", txt); // Use dummy image instead of default browsers image. if (gecko || chrome || opera) { var img = document.createElement('img'); img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image e.dataTransfer.setDragImage(img, 0, 0); } } function doHandleBinding(bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) return false; } var prevShift = shiftSelecting; try { if (options.readOnly) suppressEdits = true; if (dropShift) shiftSelecting = null; bound(instance); } catch(e) { if (e != Pass) throw e; return false; } finally { shiftSelecting = prevShift; suppressEdits = false; } return true; } function handleKeyBinding(e) { // Handle auto keymap transitions var startMap = getKeyMap(options.keyMap), next = startMap.auto; clearTimeout(maybeTransition); if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { if (getKeyMap(options.keyMap) == startMap) { options.keyMap = (next.call ? next.call(null, instance) : next); } }, 50); var name = keyNames[e_prop(e, "keyCode")], handled = false; if (name == null || e.altGraphKey) return false; if (e_prop(e, "altKey")) name = "Alt-" + name; if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name; if (e_prop(e, "metaKey")) name = "Cmd-" + name; var stopped = false; function stop() { stopped = true; } if (e_prop(e, "shiftKey")) { handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap, function(b) {return doHandleBinding(b, true);}, stop) || lookupKey(name, options.extraKeys, options.keyMap, function(b) { if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b); }, stop); } else { handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop); } if (stopped) handled = false; if (handled) { e_preventDefault(e); restartBlink(); if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } } return handled; } function handleCharBinding(e, ch) { var handled = lookupKey("'" + ch + "'", options.extraKeys, options.keyMap, function(b) { return doHandleBinding(b, true); }); if (handled) { e_preventDefault(e); restartBlink(); } return handled; } var lastStoppedKey = null, maybeTransition; function onKeyDown(e) { if (!focused) onFocus(); if (ie && e.keyCode == 27) { e.returnValue = false; } if (pollingFast) { if (readInput()) pollingFast = false; } if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; var code = e_prop(e, "keyCode"); // IE does strange things with escape. setShift(code == 16 || e_prop(e, "shiftKey")); // First give onKeyEvent option a chance to handle this. var handled = handleKeyBinding(e); if (opera) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey")) replaceSelection(""); } } function onKeyPress(e) { if (pollingFast) readInput(); if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return; var ch = String.fromCharCode(charCode == null ? keyCode : charCode); if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) { if (mode.electricChars.indexOf(ch) > -1) setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75); } if (handleCharBinding(e, ch)) return; fastPoll(); } function onKeyUp(e) { if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; if (e_prop(e, "keyCode") == 16) shiftSelecting = null; } function onFocus() { if (options.readOnly == "nocursor") return; if (!focused) { if (options.onFocus) options.onFocus(instance); focused = true; if (scroller.className.search(/\bCodeMirror-focused\b/) == -1) scroller.className += " CodeMirror-focused"; if (!leaveInputAlone) resetInput(true); } slowPoll(); restartBlink(); } function onBlur() { if (focused) { if (options.onBlur) options.onBlur(instance); focused = false; if (bracketHighlighted) operation(function(){ if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; } })(); scroller.className = scroller.className.replace(" CodeMirror-focused", ""); } clearInterval(blinker); setTimeout(function() {if (!focused) shiftSelecting = null;}, 150); } function chopDelta(delta) { // Make sure we always scroll a little bit for any nonzero delta. if (delta > 0.0 && delta < 1.0) return 1; else if (delta > -1.0 && delta < 0.0) return -1; else return Math.round(delta); } function onMouseWheel(e) { var deltaX = 0, deltaY = 0; if (e.type == "DOMMouseScroll") { // Firefox var delta = -e.detail * 8.0; if (e.axis == e.HORIZONTAL_AXIS) deltaX = delta; else if (e.axis == e.VERTICAL_AXIS) deltaY = delta; } else if (e.wheelDeltaX !== undefined && e.wheelDeltaY !== undefined) { // WebKit deltaX = e.wheelDeltaX / 3.0; deltaY = e.wheelDeltaY / 3.0; } else if (e.wheelDelta !== undefined) { // IE or Opera deltaY = e.wheelDelta / 3.0; } var scrolled = false; deltaX = chopDelta(deltaX); deltaY = chopDelta(deltaY); if ((deltaX > 0 && scroller.scrollLeft > 0) || (deltaX < 0 && scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth)) { scroller.scrollLeft -= deltaX; scrolled = true; } if ((deltaY > 0 && scrollbar.scrollTop > 0) || (deltaY < 0 && scrollbar.scrollTop + scrollbar.clientHeight < scrollbar.scrollHeight)) { scrollbar.scrollTop -= deltaY; scrolled = true; } if (scrolled) e_stop(e); } // Replace the range from from to to by the strings in newText. // Afterwards, set the selection to selFrom, selTo. function updateLines(from, to, newText, selFrom, selTo) { if (suppressEdits) return; if (history) { var old = []; doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); }); history.addChange(from.line, newText.length, old); while (history.done.length > options.undoDepth) history.done.shift(); } updateLinesNoUndo(from, to, newText, selFrom, selTo); } function unredoHelper(from, to) { if (!from.length) return; var set = from.pop(), out = []; for (var i = set.length - 1; i >= 0; i -= 1) { var change = set[i]; var replaced = [], end = change.start + change.added; doc.iter(change.start, end, function(line) { replaced.push(line.text); }); out.push({start: change.start, added: change.old.length, old: replaced}); var pos = {line: change.start + change.old.length - 1, ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])}; updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos); } updateInput = true; to.push(out); } function undo() {unredoHelper(history.done, history.undone);} function redo() {unredoHelper(history.undone, history.done);} function updateLinesNoUndo(from, to, newText, selFrom, selTo) { if (suppressEdits) return; var recomputeMaxLength = false, maxLineLength = maxLine.length; if (!options.lineWrapping) doc.iter(from.line, to.line + 1, function(line) { if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;} }); if (from.line != to.line || newText.length > 1) gutterDirty = true; var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line); // First adjust the line structure, taking some care to leave highlighting intact. if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. var added = [], prevLine = null; if (from.line) { prevLine = getLine(from.line - 1); prevLine.fixMarkEnds(lastLine); } else lastLine.fixMarkStarts(); for (var i = 0, e = newText.length - 1; i < e; ++i) added.push(Line.inheritMarks(newText[i], prevLine)); if (nlines) doc.remove(from.line, nlines, callbacks); if (added.length) doc.insert(from.line, added); } else if (firstLine == lastLine) { if (newText.length == 1) firstLine.replace(from.ch, to.ch, newText[0]); else { lastLine = firstLine.split(to.ch, newText[newText.length-1]); firstLine.replace(from.ch, null, newText[0]); firstLine.fixMarkEnds(lastLine); var added = []; for (var i = 1, e = newText.length - 1; i < e; ++i) added.push(Line.inheritMarks(newText[i], firstLine)); added.push(lastLine); doc.insert(from.line + 1, added); } } else if (newText.length == 1) { firstLine.replace(from.ch, null, newText[0]); lastLine.replace(null, to.ch, ""); firstLine.append(lastLine); doc.remove(from.line + 1, nlines, callbacks); } else { var added = []; firstLine.replace(from.ch, null, newText[0]); lastLine.replace(null, to.ch, newText[newText.length-1]); firstLine.fixMarkEnds(lastLine); for (var i = 1, e = newText.length - 1; i < e; ++i) added.push(Line.inheritMarks(newText[i], firstLine)); if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks); doc.insert(from.line + 1, added); } if (options.lineWrapping) { var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3); doc.iter(from.line, from.line + newText.length, function(line) { if (line.hidden) return; var guess = Math.ceil(line.text.length / perLine) || 1; if (guess != line.height) updateLineHeight(line, guess); }); } else { doc.iter(from.line, from.line + newText.length, function(line) { var l = line.text; if (!line.hidden && l.length > maxLineLength) { maxLine = l; maxLineLength = l.length; maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) updateMaxLine = true; } // Add these lines to the work array, so that they will be // highlighted. Adjust work lines if lines were added/removed. var newWork = [], lendiff = newText.length - nlines - 1; for (var i = 0, l = work.length; i < l; ++i) { var task = work[i]; if (task < from.line) newWork.push(task); else if (task > to.line) newWork.push(task + lendiff); } var hlEnd = from.line + Math.min(newText.length, 500); highlightLines(from.line, hlEnd); newWork.push(hlEnd); work = newWork; startWorker(100); // Remember that these lines changed, for updating the display changes.push({from: from.line, to: to.line + 1, diff: lendiff}); var changeObj = {from: from, to: to, text: newText}; if (textChanged) { for (var cur = textChanged; cur.next; cur = cur.next) {} cur.next = changeObj; } else textChanged = changeObj; // Update the selection function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;} setSelection(clipPos(selFrom), clipPos(selTo), updateLine(sel.from.line), updateLine(sel.to.line)); } function needsScrollbar() { if (options.hideVScroll) { var realHeight = doc.height * textHeight() + 2 * paddingTop(); return realHeight - 1 > scroller.offsetHeight ? realHeight : false; } else { return false; } } function updateVerticalScroll(scrollTop) { var scrollHeight = needsScrollbar(); scrollbar.style.display = scrollHeight ? "block" : "none"; if (scrollHeight) { scrollbarInner.style.height = scrollHeight + "px"; scrollbar.style.height = scroller.offsetHeight + "px"; if (scrollTop != null) scrollbar.scrollTop = scrollTop; } // Position the mover div to align with the current virtual scroll position mover.style.top = (displayOffset * textHeight() - scrollbar.scrollTop) + "px"; } // On Mac OS X Lion and up, detect whether the mouse is plugged in by measuring // the width of a div with a scrollbar in it. If the width is <= 1, then // the mouse isn't plugged in and scrollbars should overlap the content. function overlapScrollbars() { var tmpSb = document.createElement('div'), tmpSbInner = document.createElement('div'); tmpSb.className = "CodeMirror-scrollbar"; tmpSb.style.cssText = "position: absolute; left: -9999px; height: 100px;"; tmpSbInner.className = "CodeMirror-scrollbar-inner"; tmpSbInner.style.height = "200px"; tmpSb.appendChild(tmpSbInner); document.body.appendChild(tmpSb); var result = (tmpSb.offsetWidth <= 1); document.body.removeChild(tmpSb); return result; } function computeMaxLength() { var maxLineLength = 0; maxLine = ""; maxLineChanged = true; doc.iter(0, doc.size, function(line) { var l = line.text; if (!line.hidden && l.length > maxLineLength) { maxLineLength = l.length; maxLine = l; } }); updateMaxLine = false; } function replaceRange(code, from, to) { from = clipPos(from); if (!to) to = from; else to = clipPos(to); code = splitLines(code); function adjustPos(pos) { if (posLess(pos, from)) return pos; if (!posLess(to, pos)) return end; var line = pos.line + code.length - (to.line - from.line) - 1; var ch = pos.ch; if (pos.line == to.line) ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0)); return {line: line, ch: ch}; } var end; replaceRange1(code, from, to, function(end1) { end = end1; return {from: adjustPos(sel.from), to: adjustPos(sel.to)}; }); return end; } function replaceSelection(code, collapse) { replaceRange1(splitLines(code), sel.from, sel.to, function(end) { if (collapse == "end") return {from: end, to: end}; else if (collapse == "start") return {from: sel.from, to: sel.from}; else return {from: sel.from, to: end}; }); } function replaceRange1(code, from, to, computeSel) { var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length; var newSel = computeSel({line: from.line + code.length - 1, ch: endch}); updateLines(from, to, code, newSel.from, newSel.to); } function getRange(from, to, lineSep) { var l1 = from.line, l2 = to.line; if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch); var code = [getLine(l1).text.slice(from.ch)]; doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); code.push(getLine(l2).text.slice(0, to.ch)); return code.join(lineSep || "\n"); } function getSelection(lineSep) { return getRange(sel.from, sel.to, lineSep); } var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll function slowPoll() { if (pollingFast) return; poll.set(options.pollInterval, function() { startOperation(); readInput(); if (focused) slowPoll(); endOperation(); }); } function fastPoll() { var missed = false; pollingFast = true; function p() { startOperation(); var changed = readInput(); if (!changed && !missed) {missed = true; poll.set(60, p);} else {pollingFast = false; slowPoll();} endOperation(); } poll.set(20, p); } // Previnput is a hack to work with IME. If we reset the textarea // on every change, that breaks IME. So we look for changes // compared to the previous content instead. (Modern browsers have // events that indicate IME taking place, but these are not widely // supported or compatible enough yet to rely on.) var prevInput = ""; function readInput() { if (leaveInputAlone || !focused || hasSelection(input) || options.readOnly) return false; var text = input.value; if (text == prevInput) return false; shiftSelecting = null; var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput[same] == text[same]) ++same; if (same < prevInput.length) sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)}; else if (overwrite && posEq(sel.from, sel.to)) sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))}; replaceSelection(text.slice(same), "end"); if (text.length > 1000) { input.value = prevInput = ""; } else prevInput = text; return true; } function resetInput(user) { if (!posEq(sel.from, sel.to)) { prevInput = ""; input.value = getSelection(); selectInput(input); } else if (user) prevInput = input.value = ""; } function focusInput() { if (options.readOnly != "nocursor") input.focus(); } function scrollEditorIntoView() { var rect = cursor.getBoundingClientRect(); // IE returns bogus coordinates when the instance sits inside of an iframe and the cursor is hidden if (ie && rect.top == rect.bottom) return; var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); if (rect.top < 0 || rect.bottom > winH) scrollCursorIntoView(); } function scrollCursorIntoView() { var coords = calculateCursorCoords(); return scrollIntoView(coords.x, coords.y, coords.x, coords.yBot); } function calculateCursorCoords() { var cursor = localCoords(sel.inverted ? sel.from : sel.to); var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x; return {x: x, y: cursor.y, yBot: cursor.yBot}; } function scrollIntoView(x1, y1, x2, y2) { var scrollPos = calculateScrollPos(x1, y1, x2, y2), scrolled = false; if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft; scrolled = true;} if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scrollPos.scrollTop; scrolled = true;} if (scrolled && options.onScroll) options.onScroll(instance); } function calculateScrollPos(x1, y1, x2, y2) { var pl = paddingLeft(), pt = paddingTop(); y1 += pt; y2 += pt; x1 += pl; x2 += pl; var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {}; var docBottom = scroller.scrollHeight; var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;; if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen; var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft; var gutterw = options.fixedGutter ? gutter.clientWidth : 0; var atLeft = x1 < gutterw + pl + 10; if (x1 < screenleft + gutterw || atLeft) { if (atLeft) x1 = 0; result.scrollLeft = Math.max(0, x1 - 10 - gutterw); } else if (x2 > screenw + screenleft - 3) { result.scrollLeft = x2 + 10 - screenw; } return result; } function visibleLines(scrollTop) { var lh = textHeight(), top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop(); var fromHeight = Math.max(0, Math.floor(top / lh)); var toHeight = Math.ceil((top + scroller.clientHeight) / lh); return {from: lineAtHeight(doc, fromHeight), to: lineAtHeight(doc, toHeight)}; } // Uses a set of changes plus the current scroll position to // determine which DOM updates have to be made, and makes the // updates. function updateDisplay(changes, suppressCallback, scrollTop) { if (!scroller.clientWidth) { showingFrom = showingTo = displayOffset = 0; return; } // Compute the new visible window // If scrollTop is specified, use that to determine which lines // to render instead of the current scrollbar position. var visible = visibleLines(scrollTop); // Bail out if the visible area is already rendered and nothing changed. if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) { updateVerticalScroll(scrollTop); return; } var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100); if (showingFrom < from && from - showingFrom < 20) from = showingFrom; if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo); // Create a range of theoretically intact lines, and punch holes // in that using the change info. var intact = changes === true ? [] : computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes); // Clip off the parts that won't be visible var intactLines = 0; for (var i = 0; i < intact.length; ++i) { var range = intact[i]; if (range.from < from) {range.domStart += (from - range.from); range.from = from;} if (range.to > to) range.to = to; if (range.from >= range.to) intact.splice(i--, 1); else intactLines += range.to - range.from; } if (intactLines == to - from && from == showingFrom && to == showingTo) { updateVerticalScroll(scrollTop); return; } intact.sort(function(a, b) {return a.domStart - b.domStart;}); var th = textHeight(), gutterDisplay = gutter.style.display; lineDiv.style.display = "none"; patchDisplay(from, to, intact); lineDiv.style.display = gutter.style.display = ""; var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th; // This is just a bogus formula that detects when the editor is // resized or the font size changes. if (different) lastSizeC = scroller.clientHeight + th; showingFrom = from; showingTo = to; displayOffset = heightAtLine(doc, from); // Since this is all rather error prone, it is honoured with the // only assertion in the whole file. if (lineDiv.childNodes.length != showingTo - showingFrom) throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) + " nodes=" + lineDiv.childNodes.length); function checkHeights() { var curNode = lineDiv.firstChild, heightChanged = false; doc.iter(showingFrom, showingTo, function(line) { if (!line.hidden) { var height = Math.round(curNode.offsetHeight / th) || 1; if (line.height != height) { updateLineHeight(line, height); gutterDirty = heightChanged = true; } } curNode = curNode.nextSibling; }); return heightChanged; } if (options.lineWrapping) { checkHeights(); var scrollHeight = needsScrollbar(); var shouldHaveScrollbar = scrollHeight ? "block" : "none"; if (scrollbar.style.display != shouldHaveScrollbar) { scrollbar.style.display = shouldHaveScrollbar; if (scrollHeight) scrollbarInner.style.height = scrollHeight + "px"; checkHeights(); } } gutter.style.display = gutterDisplay; if (different || gutterDirty) { // If the gutter grew in size, re-check heights. If those changed, re-draw gutter. updateGutter() && options.lineWrapping && checkHeights() && updateGutter(); } updateVerticalScroll(scrollTop); updateSelection(); if (!suppressCallback && options.onUpdate) options.onUpdate(instance); return true; } function computeIntact(intact, changes) { for (var i = 0, l = changes.length || 0; i < l; ++i) { var change = changes[i], intact2 = [], diff = change.diff || 0; for (var j = 0, l2 = intact.length; j < l2; ++j) { var range = intact[j]; if (change.to <= range.from && change.diff) intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart}); else if (change.to <= range.from || change.from >= range.to) intact2.push(range); else { if (change.from > range.from) intact2.push({from: range.from, to: change.from, domStart: range.domStart}); if (change.to < range.to) intact2.push({from: change.to + diff, to: range.to + diff, domStart: range.domStart + (change.to - range.from)}); } } intact = intact2; } return intact; } function patchDisplay(from, to, intact) { // The first pass removes the DOM nodes that aren't intact. if (!intact.length) lineDiv.innerHTML = ""; else { function killNode(node) { var tmp = node.nextSibling; node.parentNode.removeChild(node); return tmp; } var domPos = 0, curNode = lineDiv.firstChild, n; for (var i = 0; i < intact.length; ++i) { var cur = intact[i]; while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;} for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;} } while (curNode) curNode = killNode(curNode); } // This pass fills in the lines that actually changed. var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from; var scratch = document.createElement("div"); doc.iter(from, to, function(line) { if (nextIntact && nextIntact.to == j) nextIntact = intact.shift(); if (!nextIntact || nextIntact.from > j) { if (line.hidden) var html = scratch.innerHTML = "<pre></pre>"; else { var html = '<pre' + (line.className ? ' class="' + line.className + '"' : '') + '>' + line.getHTML(makeTab) + '</pre>'; // Kludge to make sure the styled element lies behind the selection (by z-index) if (line.bgClassName) html = '<div style="position: relative"><pre class="' + line.bgClassName + '" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2">&#160;</pre>' + html + "</div>"; } scratch.innerHTML = html; lineDiv.insertBefore(scratch.firstChild, curNode); } else { curNode = curNode.nextSibling; } ++j; }); } function updateGutter() { if (!options.gutter && !options.lineNumbers) return; var hText = mover.offsetHeight, hEditor = scroller.clientHeight; gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px"; var html = [], i = showingFrom, normalNode; doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) { if (line.hidden) { html.push("<pre></pre>"); } else { var marker = line.gutterMarker; var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null; if (marker && marker.text) text = marker.text.replace("%N%", text != null ? text : ""); else if (text == null) text = "\u00a0"; html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text); for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;"); html.push("</pre>"); if (!marker) normalNode = i; } ++i; }); gutter.style.display = "none"; gutterText.innerHTML = html.join(""); // Make sure scrolling doesn't cause number gutter size to pop if (normalNode != null && options.lineNumbers) { var node = gutterText.childNodes[normalNode - showingFrom]; var minwidth = String(doc.size).length, val = eltText(node.firstChild), pad = ""; while (val.length + pad.length < minwidth) pad += "\u00a0"; if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild); } gutter.style.display = ""; var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2; lineSpace.style.marginLeft = gutter.offsetWidth + "px"; gutterDirty = false; return resized; } function updateSelection() { var collapsed = posEq(sel.from, sel.to); var fromPos = localCoords(sel.from, true); var toPos = collapsed ? fromPos : localCoords(sel.to, true); var headPos = sel.inverted ? fromPos : toPos, th = textHeight(); var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv); inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px"; inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px"; if (collapsed) { cursor.style.top = headPos.y + "px"; cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px"; cursor.style.display = ""; selectionDiv.style.display = "none"; } else { var sameLine = fromPos.y == toPos.y, html = ""; var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth; var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight; function add(left, top, right, height) { var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px" : "right: " + right + "px"; html += '<div class="CodeMirror-selected" style="position: absolute; left: ' + left + 'px; top: ' + top + 'px; ' + rstyle + '; height: ' + height + 'px"></div>'; } if (sel.from.ch && fromPos.y >= 0) { var right = sameLine ? clientWidth - toPos.x : 0; add(fromPos.x, fromPos.y, right, th); } var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0)); var middleHeight = Math.min(toPos.y, clientHeight) - middleStart; if (middleHeight > 0.2 * th) add(0, middleStart, 0, middleHeight); if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th) add(0, toPos.y, clientWidth - toPos.x, th); selectionDiv.innerHTML = html; cursor.style.display = "none"; selectionDiv.style.display = ""; } } function setShift(val) { if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from); else shiftSelecting = null; } function setSelectionUser(from, to) { var sh = shiftSelecting && clipPos(shiftSelecting); if (sh) { if (posLess(sh, from)) from = sh; else if (posLess(to, sh)) to = sh; } setSelection(from, to); userSelChange = true; } // Update the selection. Last two args are only used by // updateLines, since they have to be expressed in the line // numbers before the update. function setSelection(from, to, oldFrom, oldTo) { goalColumn = null; if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;} if (posEq(sel.from, from) && posEq(sel.to, to)) return; if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} // Skip over hidden lines. if (from.line != oldFrom) { var from1 = skipHidden(from, oldFrom, sel.from.ch); // If there is no non-hidden line left, force visibility on current line if (!from1) setLineHidden(from.line, false); else from = from1; } if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch); if (posEq(from, to)) sel.inverted = false; else if (posEq(from, sel.to)) sel.inverted = false; else if (posEq(to, sel.from)) sel.inverted = true; if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) { var head = sel.inverted ? from : to; if (head.line != sel.from.line && sel.from.line < doc.size) { var oldLine = getLine(sel.from.line); if (/^\s+$/.test(oldLine.text)) setTimeout(operation(function() { if (oldLine.parent && /^\s+$/.test(oldLine.text)) { var no = lineNo(oldLine); replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length}); } }, 10)); } } sel.from = from; sel.to = to; selectionChanged = true; } function skipHidden(pos, oldLine, oldCh) { function getNonHidden(dir) { var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1; while (lNo != end) { var line = getLine(lNo); if (!line.hidden) { var ch = pos.ch; if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length; return {line: lNo, ch: ch}; } lNo += dir; } } var line = getLine(pos.line); var toEnd = pos.ch == line.text.length && pos.ch != oldCh; if (!line.hidden) return pos; if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1); else return getNonHidden(-1) || getNonHidden(1); } function setCursor(line, ch, user) { var pos = clipPos({line: line, ch: ch || 0}); (user ? setSelectionUser : setSelection)(pos, pos); } function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));} function clipPos(pos) { if (pos.line < 0) return {line: 0, ch: 0}; if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length}; var ch = pos.ch, linelen = getLine(pos.line).text.length; if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; else if (ch < 0) return {line: pos.line, ch: 0}; else return pos; } function findPosH(dir, unit) { var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch; var lineObj = getLine(line); function findNextLine() { for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) { var lo = getLine(l); if (!lo.hidden) { line = l; lineObj = lo; return true; } } } function moveOnce(boundToLine) { if (ch == (dir < 0 ? 0 : lineObj.text.length)) { if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0; else return false; } else ch += dir; return true; } if (unit == "char") moveOnce(); else if (unit == "column") moveOnce(true); else if (unit == "word") { var sawWord = false; for (;;) { if (dir < 0) if (!moveOnce()) break; if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} if (dir > 0) if (!moveOnce()) break; } } return {line: line, ch: ch}; } function moveH(dir, unit) { var pos = dir < 0 ? sel.from : sel.to; if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit); setCursor(pos.line, pos.ch, true); } function deleteH(dir, unit) { if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to); else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to); else replaceRange("", sel.from, findPosH(dir, unit)); userSelChange = true; } var goalColumn = null; function moveV(dir, unit) { var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true); if (goalColumn != null) pos.x = goalColumn; if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight); else if (unit == "line") dist = textHeight(); var target = coordsChar(pos.x, pos.y + dist * dir + 2); if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y; setCursor(target.line, target.ch, true); goalColumn = pos.x; } function findWordAt(pos) { var line = getLine(pos.line).text; var start = pos.ch, end = pos.ch; var check = isWordChar(line.charAt(start < line.length ? start : start - 1)) ? isWordChar : function(ch) {return !isWordChar(ch);}; while (start > 0 && check(line.charAt(start - 1))) --start; while (end < line.length && check(line.charAt(end))) ++end; return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}}; } function selectLine(line) { setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0})); } function indentSelected(mode) { if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode); var e = sel.to.line - (sel.to.ch ? 0 : 1); for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode); } function indentLine(n, how) { if (!how) how = "add"; if (how == "smart") { if (!mode.indent) how = "prev"; else var state = getStateBefore(n); } var line = getLine(n), curSpace = line.indentation(options.tabSize), curSpaceString = line.text.match(/^\s*/)[0], indentation; if (how == "smart") { indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass) how = "prev"; } if (how == "prev") { if (n) indentation = getLine(n-1).indentation(options.tabSize); else indentation = 0; } else if (how == "add") indentation = curSpace + options.indentUnit; else if (how == "subtract") indentation = curSpace - options.indentUnit; indentation = Math.max(0, indentation); var diff = indentation - curSpace; var indentString = "", pos = 0; if (options.indentWithTabs) for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";} while (pos < indentation) {++pos; indentString += " ";} replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}); } function loadMode() { mode = CodeMirror.getMode(options, options.mode); doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); work = [0]; startWorker(); } function gutterChanged() { var visible = options.gutter || options.lineNumbers; gutter.style.display = visible ? "" : "none"; if (visible) gutterDirty = true; else lineDiv.parentNode.style.marginLeft = 0; } function wrappingChanged(from, to) { if (options.lineWrapping) { wrapper.className += " CodeMirror-wrap"; var perLine = scroller.clientWidth / charWidth() - 3; doc.iter(0, doc.size, function(line) { if (line.hidden) return; var guess = Math.ceil(line.text.length / perLine) || 1; if (guess != 1) updateLineHeight(line, guess); }); lineSpace.style.width = code.style.width = ""; widthForcer.style.left = ""; } else { wrapper.className = wrapper.className.replace(" CodeMirror-wrap", ""); maxLine = ""; maxLineChanged = true; doc.iter(0, doc.size, function(line) { if (line.height != 1 && !line.hidden) updateLineHeight(line, 1); if (line.text.length > maxLine.length) maxLine = line.text; }); } changes.push({from: 0, to: doc.size}); } function makeTab(col) { var w = options.tabSize - col % options.tabSize, cached = tabCache[w]; if (cached) return cached; for (var str = '<span class="cm-tab">', i = 0; i < w; ++i) str += " "; return (tabCache[w] = {html: str + "</span>", width: w}); } function themeChanged() { scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") + options.theme.replace(/(^|\s)\s*/g, " cm-s-"); } function keyMapChanged() { var style = keyMap[options.keyMap].style; wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + (style ? " cm-keymap-" + style : ""); } function TextMarker() { this.set = []; } TextMarker.prototype.clear = operation(function() { var min = Infinity, max = -Infinity; for (var i = 0, e = this.set.length; i < e; ++i) { var line = this.set[i], mk = line.marked; if (!mk || !line.parent) continue; var lineN = lineNo(line); min = Math.min(min, lineN); max = Math.max(max, lineN); for (var j = 0; j < mk.length; ++j) if (mk[j].marker == this) mk.splice(j--, 1); } if (min != Infinity) changes.push({from: min, to: max + 1}); }); TextMarker.prototype.find = function() { var from, to; for (var i = 0, e = this.set.length; i < e; ++i) { var line = this.set[i], mk = line.marked; for (var j = 0; j < mk.length; ++j) { var mark = mk[j]; if (mark.marker == this) { if (mark.from != null || mark.to != null) { var found = lineNo(line); if (found != null) { if (mark.from != null) from = {line: found, ch: mark.from}; if (mark.to != null) to = {line: found, ch: mark.to}; } } } } } return {from: from, to: to}; }; function markText(from, to, className) { from = clipPos(from); to = clipPos(to); var tm = new TextMarker(); if (!posLess(from, to)) return tm; function add(line, from, to, className) { getLine(line).addMark(new MarkedText(from, to, className, tm)); } if (from.line == to.line) add(from.line, from.ch, to.ch, className); else { add(from.line, from.ch, null, className); for (var i = from.line + 1, e = to.line; i < e; ++i) add(i, null, null, className); add(to.line, null, to.ch, className); } changes.push({from: from.line, to: to.line + 1}); return tm; } function setBookmark(pos) { pos = clipPos(pos); var bm = new Bookmark(pos.ch); getLine(pos.line).addMark(bm); return bm; } function findMarksAt(pos) { pos = clipPos(pos); var markers = [], marked = getLine(pos.line).marked; if (!marked) return markers; for (var i = 0, e = marked.length; i < e; ++i) { var m = marked[i]; if ((m.from == null || m.from <= pos.ch) && (m.to == null || m.to >= pos.ch)) markers.push(m.marker || m); } return markers; } function addGutterMarker(line, text, className) { if (typeof line == "number") line = getLine(clipLine(line)); line.gutterMarker = {text: text, style: className}; gutterDirty = true; return line; } function removeGutterMarker(line) { if (typeof line == "number") line = getLine(clipLine(line)); line.gutterMarker = null; gutterDirty = true; } function changeLine(handle, op) { var no = handle, line = handle; if (typeof handle == "number") line = getLine(clipLine(handle)); else no = lineNo(handle); if (no == null) return null; if (op(line, no)) changes.push({from: no, to: no + 1}); else return null; return line; } function setLineClass(handle, className, bgClassName) { return changeLine(handle, function(line) { if (line.className != className || line.bgClassName != bgClassName) { line.className = className; line.bgClassName = bgClassName; return true; } }); } function setLineHidden(handle, hidden) { return changeLine(handle, function(line, no) { if (line.hidden != hidden) { line.hidden = hidden; if (!options.lineWrapping) { var l = line.text; if (hidden && l.length == maxLine.length) { updateMaxLine = true; } else if (!hidden && l.length > maxLine.length) { maxLine = l; updateMaxLine = false; } } updateLineHeight(line, hidden ? 0 : 1); var fline = sel.from.line, tline = sel.to.line; if (hidden && (fline == no || tline == no)) { var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from; var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to; // Can't hide the last visible line, we'd have no place to put the cursor if (!to) return; setSelection(from, to); } return (gutterDirty = true); } }); } function lineInfo(line) { if (typeof line == "number") { if (!isLine(line)) return null; var n = line; line = getLine(line); if (!line) return null; } else { var n = lineNo(line); if (n == null) return null; } var marker = line.gutterMarker; return {line: n, handle: line, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName}; } function stringWidth(str) { measure.innerHTML = "<pre><span>x</span></pre>"; measure.firstChild.firstChild.firstChild.nodeValue = str; return measure.firstChild.firstChild.offsetWidth || 10; } // These are used to go from pixel positions to character // positions, taking varying character widths into account. function charFromX(line, x) { if (x <= 0) return 0; var lineObj = getLine(line), text = lineObj.text; function getX(len) { return measureLine(lineObj, len).left; } var from = 0, fromX = 0, to = text.length, toX; // Guess a suitable upper bound for our search. var estimated = Math.min(to, Math.ceil(x / charWidth())); for (;;) { var estX = getX(estimated); if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); else {toX = estX; to = estimated; break;} } if (x > toX) return to; // Try to guess a suitable lower bound as well. estimated = Math.floor(to * 0.8); estX = getX(estimated); if (estX < x) {from = estimated; fromX = estX;} // Do a binary search between these bounds. for (;;) { if (to - from <= 1) return (toX - x > x - fromX) ? from : to; var middle = Math.ceil((from + to) / 2), middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX;} else {from = middle; fromX = middleX;} } } var tempId = "CodeMirror-temp-" + Math.floor(Math.random() * 0xffffff).toString(16); function measureLine(line, ch) { if (ch == 0) return {top: 0, left: 0}; var wbr = options.lineWrapping && ch < line.text.length && spanAffectsWrapping.test(line.text.slice(ch - 1, ch + 1)); measure.innerHTML = "<pre>" + line.getHTML(makeTab, ch, tempId, wbr) + "</pre>"; var elt = document.getElementById(tempId); var top = elt.offsetTop, left = elt.offsetLeft; // Older IEs report zero offsets for spans directly after a wrap if (ie && top == 0 && left == 0) { var backup = document.createElement("span"); backup.innerHTML = "x"; elt.parentNode.insertBefore(backup, elt.nextSibling); top = backup.offsetTop; } return {top: top, left: left}; } function localCoords(pos, inLineWrap) { var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0)); if (pos.ch == 0) x = 0; else { var sp = measureLine(getLine(pos.line), pos.ch); x = sp.left; if (options.lineWrapping) y += Math.max(0, sp.top); } return {x: x, y: y, yBot: y + lh}; } // Coords must be lineSpace-local function coordsChar(x, y) { if (y < 0) y = 0; var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th); var lineNo = lineAtHeight(doc, heightPos); if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length}; var lineObj = getLine(lineNo), text = lineObj.text; var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0; if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0}; function getX(len) { var sp = measureLine(lineObj, len); if (tw) { var off = Math.round(sp.top / th); return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth); } return sp.left; } var from = 0, fromX = 0, to = text.length, toX; // Guess a suitable upper bound for our search. var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw)); for (;;) { var estX = getX(estimated); if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); else {toX = estX; to = estimated; break;} } if (x > toX) return {line: lineNo, ch: to}; // Try to guess a suitable lower bound as well. estimated = Math.floor(to * 0.8); estX = getX(estimated); if (estX < x) {from = estimated; fromX = estX;} // Do a binary search between these bounds. for (;;) { if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to}; var middle = Math.ceil((from + to) / 2), middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX;} else {from = middle; fromX = middleX;} } } function pageCoords(pos) { var local = localCoords(pos, true), off = eltOffset(lineSpace); return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot}; } var cachedHeight, cachedHeightFor, measureText; function textHeight() { if (measureText == null) { measureText = "<pre>"; for (var i = 0; i < 49; ++i) measureText += "x<br/>"; measureText += "x</pre>"; } var offsetHeight = lineDiv.clientHeight; if (offsetHeight == cachedHeightFor) return cachedHeight; cachedHeightFor = offsetHeight; measure.innerHTML = measureText; cachedHeight = measure.firstChild.offsetHeight / 50 || 1; measure.innerHTML = ""; return cachedHeight; } var cachedWidth, cachedWidthFor = 0; function charWidth() { if (scroller.clientWidth == cachedWidthFor) return cachedWidth; cachedWidthFor = scroller.clientWidth; return (cachedWidth = stringWidth("x")); } function paddingTop() {return lineSpace.offsetTop;} function paddingLeft() {return lineSpace.offsetLeft;} function posFromMouse(e, liberal) { var offW = eltOffset(scroller, true), x, y; // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX; y = e.clientY; } catch (e) { return null; } // This is a mess of a heuristic to try and determine whether a // scroll-bar was clicked or not, and to return null if one was // (and !liberal). if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight)) return null; var offL = eltOffset(lineSpace, true); return coordsChar(x - offL.left, y - offL.top); } function onContextMenu(e) { var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop; if (!pos || opera) return; // Opera is difficult. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) operation(setCursor)(pos.line, pos.ch); var oldCSS = input.style.cssText; inputDiv.style.position = "absolute"; input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " + "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; leaveInputAlone = true; var val = input.value = getSelection(); focusInput(); selectInput(input); function rehide() { var newVal = splitLines(input.value).join("\n"); if (newVal != val && !options.readOnly) operation(replaceSelection)(newVal, "end"); inputDiv.style.position = "relative"; input.style.cssText = oldCSS; if (ie_lt9) scrollbar.scrollTop = scrollPos; leaveInputAlone = false; resetInput(true); slowPoll(); } if (gecko) { e_stop(e); var mouseup = connect(window, "mouseup", function() { mouseup(); setTimeout(rehide, 20); }, true); } else { setTimeout(rehide, 50); } } // Cursor-blinking function restartBlink() { clearInterval(blinker); var on = true; cursor.style.visibility = ""; blinker = setInterval(function() { cursor.style.visibility = (on = !on) ? "" : "hidden"; }, 650); } var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; function matchBrackets(autoclear) { var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1; var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; if (!match) return; var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles; for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2) if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;} var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; function scan(line, from, to) { if (!line.text) return; var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur; for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) { var text = st[i]; if (st[i+1] != style) {pos += d * text.length; continue;} for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) { if (pos >= from && pos < to && re.test(cur = text.charAt(j))) { var match = matching[cur]; if (match.charAt(1) == ">" == forward) stack.push(cur); else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; else if (!stack.length) return {pos: pos, match: true}; } } } } for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) { var line = getLine(i), first = i == head.line; var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length); if (found) break; } if (!found) found = {pos: null, match: false}; var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style), two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style); var clear = operation(function(){one.clear(); two && two.clear();}); if (autoclear) setTimeout(clear, 800); else bracketHighlighted = clear; } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(n) { var minindent, minline; for (var search = n, lim = n - 40; search > lim; --search) { if (search == 0) return 0; var line = getLine(search-1); if (line.stateAfter) return search; var indented = line.indentation(options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline; } function getStateBefore(n) { var start = findStartLine(n), state = start && getLine(start-1).stateAfter; if (!state) state = startState(mode); else state = copyState(mode, state); doc.iter(start, n, function(line) { line.highlight(mode, state, options.tabSize); line.stateAfter = copyState(mode, state); }); if (start < n) changes.push({from: start, to: n}); if (n < doc.size && !getLine(n).stateAfter) work.push(n); return state; } function highlightLines(start, end) { var state = getStateBefore(start); doc.iter(start, end, function(line) { line.highlight(mode, state, options.tabSize); line.stateAfter = copyState(mode, state); }); } function highlightWorker() { var end = +new Date + options.workTime; var foundWork = work.length; while (work.length) { if (!getLine(showingFrom).stateAfter) var task = showingFrom; else var task = work.pop(); if (task >= doc.size) continue; var start = findStartLine(task), state = start && getLine(start-1).stateAfter; if (state) state = copyState(mode, state); else state = startState(mode); var unchanged = 0, compare = mode.compareStates, realChange = false, i = start, bail = false; doc.iter(i, doc.size, function(line) { var hadState = line.stateAfter; if (+new Date > end) { work.push(i); startWorker(options.workDelay); if (realChange) changes.push({from: task, to: i + 1}); return (bail = true); } var changed = line.highlight(mode, state, options.tabSize); if (changed) realChange = true; line.stateAfter = copyState(mode, state); var done = null; if (compare) { var same = hadState && compare(hadState, state); if (same != Pass) done = !!same; } if (done == null) { if (changed !== false || !hadState) unchanged = 0; else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, ""))) done = true; } if (done) return true; ++i; }); if (bail) return; if (realChange) changes.push({from: task, to: i + 1}); } if (foundWork && options.onHighlightComplete) options.onHighlightComplete(instance); } function startWorker(time) { if (!work.length) return; highlight.set(time, operation(highlightWorker)); } // Operations are used to wrap changes in such a way that each // change won't have to update the cursor and display (which would // be awkward, slow, and error-prone), but instead updates are // batched and then all combined and executed at once. function startOperation() { updateInput = userSelChange = textChanged = null; changes = []; selectionChanged = false; callbacks = []; } function endOperation() { if (updateMaxLine) computeMaxLength(); if (maxLineChanged && !options.lineWrapping) { var cursorWidth = widthForcer.offsetWidth, left = stringWidth(maxLine); widthForcer.style.left = left + "px"; lineSpace.style.minWidth = (left + cursorWidth) + "px"; maxLineChanged = false; } var newScrollPos, updated; if (selectionChanged) { var coords = calculateCursorCoords(); newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot); } if (changes.length) updated = updateDisplay(changes, true, (newScrollPos ? newScrollPos.scrollTop : null)); else { if (selectionChanged) updateSelection(); if (gutterDirty) updateGutter(); } if (newScrollPos) scrollCursorIntoView(); if (selectionChanged) {scrollEditorIntoView(); restartBlink();} if (focused && !leaveInputAlone && (updateInput === true || (updateInput !== false && selectionChanged))) resetInput(userSelChange); if (selectionChanged && options.matchBrackets) setTimeout(operation(function() { if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;} if (posEq(sel.from, sel.to)) matchBrackets(false); }), 20); var sc = selectionChanged, cbs = callbacks; // these can be reset by callbacks if (textChanged && options.onChange && instance) options.onChange(instance, textChanged); if (sc && options.onCursorActivity) options.onCursorActivity(instance); for (var i = 0; i < cbs.length; ++i) cbs[i](instance); if (updated && options.onUpdate) options.onUpdate(instance); } var nestedOperation = 0; function operation(f) { return function() { if (!nestedOperation++) startOperation(); try {var result = f.apply(this, arguments);} finally {if (!--nestedOperation) endOperation();} return result; }; } function compoundChange(f) { history.startCompound(); try { return f(); } finally { history.endCompound(); } } for (var ext in extensions) if (extensions.propertyIsEnumerable(ext) && !instance.propertyIsEnumerable(ext)) instance[ext] = extensions[ext]; return instance; } // (end of function CodeMirror) // The default configuration options. CodeMirror.defaults = { value: "", mode: null, theme: "default", indentUnit: 2, indentWithTabs: false, smartIndent: true, tabSize: 4, keyMap: "default", extraKeys: null, electricChars: true, autoClearEmptyLines: false, onKeyEvent: null, onDragEvent: null, lineWrapping: false, lineNumbers: false, gutter: false, fixedGutter: false, firstLineNumber: 1, readOnly: false, dragDrop: true, onChange: null, onCursorActivity: null, onGutterClick: null, onHighlightComplete: null, onUpdate: null, onFocus: null, onBlur: null, onScroll: null, matchBrackets: false, workTime: 100, workDelay: 200, pollInterval: 100, undoDepth: 40, tabindex: null, autofocus: null, lineNumberFormatter: function(integer) { return integer; } }; var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); var mac = ios || /Mac/.test(navigator.platform); var win = /Win/.test(navigator.platform); // Known modes, by name and by MIME var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; CodeMirror.defineMode = function(name, mode) { if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; if (arguments.length > 2) { mode.dependencies = []; for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); } modes[name] = mode; }; CodeMirror.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; CodeMirror.resolveMode = function(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) spec = mimeModes[spec]; else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) return CodeMirror.resolveMode("application/xml"); if (typeof spec == "string") return {name: spec}; else return spec || {name: "null"}; }; CodeMirror.getMode = function(options, spec) { var spec = CodeMirror.resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) return CodeMirror.getMode(options, "text/plain"); return mfactory(options, spec); }; CodeMirror.listModes = function() { var list = []; for (var m in modes) if (modes.propertyIsEnumerable(m)) list.push(m); return list; }; CodeMirror.listMIMEs = function() { var list = []; for (var m in mimeModes) if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]}); return list; }; var extensions = CodeMirror.extensions = {}; CodeMirror.defineExtension = function(name, func) { extensions[name] = func; }; var commands = CodeMirror.commands = { selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, killLine: function(cm) { var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0}); else cm.replaceRange("", from, sel ? to : {line: from.line}); }, deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});}, undo: function(cm) {cm.undo();}, redo: function(cm) {cm.redo();}, goDocStart: function(cm) {cm.setCursor(0, 0, true);}, goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);}, goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);}, goLineStartSmart: function(cm) { var cur = cm.getCursor(); var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/)); cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true); }, goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);}, goLineUp: function(cm) {cm.moveV(-1, "line");}, goLineDown: function(cm) {cm.moveV(1, "line");}, goPageUp: function(cm) {cm.moveV(-1, "page");}, goPageDown: function(cm) {cm.moveV(1, "page");}, goCharLeft: function(cm) {cm.moveH(-1, "char");}, goCharRight: function(cm) {cm.moveH(1, "char");}, goColumnLeft: function(cm) {cm.moveH(-1, "column");}, goColumnRight: function(cm) {cm.moveH(1, "column");}, goWordLeft: function(cm) {cm.moveH(-1, "word");}, goWordRight: function(cm) {cm.moveH(1, "word");}, delCharLeft: function(cm) {cm.deleteH(-1, "char");}, delCharRight: function(cm) {cm.deleteH(1, "char");}, delWordLeft: function(cm) {cm.deleteH(-1, "word");}, delWordRight: function(cm) {cm.deleteH(1, "word");}, indentAuto: function(cm) {cm.indentSelection("smart");}, indentMore: function(cm) {cm.indentSelection("add");}, indentLess: function(cm) {cm.indentSelection("subtract");}, insertTab: function(cm) {cm.replaceSelection("\t", "end");}, defaultTab: function(cm) { if (cm.somethingSelected()) cm.indentSelection("add"); else cm.replaceSelection("\t", "end"); }, transposeChars: function(cm) { var cur = cm.getCursor(), line = cm.getLine(cur.line); if (cur.ch > 0 && cur.ch < line.length - 1) cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1}); }, newlineAndIndent: function(cm) { cm.replaceSelection("\n", "end"); cm.indentLine(cm.getCursor().line); }, toggleOverwrite: function(cm) {cm.toggleOverwrite();} }; var keyMap = CodeMirror.keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" }; // Note that the save and find-related commands aren't defined by // default. Unknown commands are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", fallthrough: "basic" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft", "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft", "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", fallthrough: ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft", "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" }; function getKeyMap(val) { if (typeof val == "string") return keyMap[val]; else return val; } function lookupKey(name, extraMap, map, handle, stop) { function lookup(map) { map = getKeyMap(map); var found = map[name]; if (found != null && handle(found)) return true; if (map.nofallthrough) { if (stop) stop(); return true; } var fallthrough = map.fallthrough; if (fallthrough == null) return false; if (Object.prototype.toString.call(fallthrough) != "[object Array]") return lookup(fallthrough); for (var i = 0, e = fallthrough.length; i < e; ++i) { if (lookup(fallthrough[i])) return true; } return false; } if (extraMap && lookup(extraMap)) return true; return lookup(map); } function isModifierKey(event) { var name = keyNames[e_prop(event, "keyCode")]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; } CodeMirror.fromTextArea = function(textarea, options) { if (!options) options = {}; options.value = textarea.value; if (!options.tabindex && textarea.tabindex) options.tabindex = textarea.tabindex; if (options.autofocus == null && textarea.getAttribute("autofocus") != null) options.autofocus = true; function save() {textarea.value = instance.getValue();} if (textarea.form) { // Deplorable hack to make the submit method do the right thing. var rmSubmit = connect(textarea.form, "submit", save, true); if (typeof textarea.form.submit == "function") { var realSubmit = textarea.form.submit; function wrappedSubmit() { save(); textarea.form.submit = realSubmit; textarea.form.submit(); textarea.form.submit = wrappedSubmit; } textarea.form.submit = wrappedSubmit; } } textarea.style.display = "none"; var instance = CodeMirror(function(node) { textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); instance.save = save; instance.getTextArea = function() { return textarea; }; instance.toTextArea = function() { save(); textarea.parentNode.removeChild(instance.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { rmSubmit(); if (typeof textarea.form.submit == "function") textarea.form.submit = realSubmit; } }; return instance; }; // Utility functions for working with state. Exported because modes // sometimes need to do this. function copyState(mode, state) { if (state === true) return state; if (mode.copyState) return mode.copyState(state); var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) val = val.concat([]); nstate[n] = val; } return nstate; } CodeMirror.copyState = copyState; function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; } CodeMirror.startState = startState; // The character stream used by a mode's parser. function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos);}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() {return countColumn(this.string, this.start, this.tabSize);}, indentation: function() {return countColumn(this.string, null, this.tabSize);}, match: function(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { if (consume !== false) this.pos += pattern.length; return true; } } else { var match = this.string.slice(this.pos).match(pattern); if (match && consume !== false) this.pos += match[0].length; return match; } }, current: function(){return this.string.slice(this.start, this.pos);} }; CodeMirror.StringStream = StringStream; function MarkedText(from, to, className, marker) { this.from = from; this.to = to; this.style = className; this.marker = marker; } MarkedText.prototype = { attach: function(line) { this.marker.set.push(line); }, detach: function(line) { var ix = indexOf(this.marker.set, line); if (ix > -1) this.marker.set.splice(ix, 1); }, split: function(pos, lenBefore) { if (this.to <= pos && this.to != null) return null; var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore; var to = this.to == null ? null : this.to - pos + lenBefore; return new MarkedText(from, to, this.style, this.marker); }, dup: function() { return new MarkedText(null, null, this.style, this.marker); }, clipTo: function(fromOpen, from, toOpen, to, diff) { if (fromOpen && to > this.from && (to < this.to || this.to == null)) this.from = null; else if (this.from != null && this.from >= from) this.from = Math.max(to, this.from) + diff; if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null)) this.to = null; else if (this.to != null && this.to > from) this.to = to < this.to ? this.to + diff : from; }, isDead: function() { return this.from != null && this.to != null && this.from >= this.to; }, sameSet: function(x) { return this.marker == x.marker; } }; function Bookmark(pos) { this.from = pos; this.to = pos; this.line = null; } Bookmark.prototype = { attach: function(line) { this.line = line; }, detach: function(line) { if (this.line == line) this.line = null; }, split: function(pos, lenBefore) { if (pos < this.from) { this.from = this.to = (this.from - pos) + lenBefore; return this; } }, isDead: function() { return this.from > this.to; }, clipTo: function(fromOpen, from, toOpen, to, diff) { if ((fromOpen || from < this.from) && (toOpen || to > this.to)) { this.from = 0; this.to = -1; } else if (this.from > from) { this.from = this.to = Math.max(to, this.from) + diff; } }, sameSet: function(x) { return false; }, find: function() { if (!this.line || !this.line.parent) return null; return {line: lineNo(this.line), ch: this.from}; }, clear: function() { if (this.line) { var found = indexOf(this.line.marked, this); if (found != -1) this.line.marked.splice(found, 1); this.line = null; } } }; // Line objects. These hold state related to a line, including // highlighting info (the styles array). function Line(text, styles) { this.styles = styles || [text, null]; this.text = text; this.height = 1; this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null; this.stateAfter = this.parent = this.hidden = null; } Line.inheritMarks = function(text, orig) { var ln = new Line(text), mk = orig && orig.marked; if (mk) { for (var i = 0; i < mk.length; ++i) { if (mk[i].to == null && mk[i].style) { var newmk = ln.marked || (ln.marked = []), mark = mk[i]; var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln); } } } return ln; } Line.prototype = { // Replace a piece of a line, keeping the styles around it intact. replace: function(from, to_, text) { var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_; copyStyles(0, from, this.styles, st); if (text) st.push(text, null); copyStyles(to, this.text.length, this.styles, st); this.styles = st; this.text = this.text.slice(0, from) + text + this.text.slice(to); this.stateAfter = null; if (mk) { var diff = text.length - (to - from); for (var i = 0; i < mk.length; ++i) { var mark = mk[i]; mark.clipTo(from == null, from || 0, to_ == null, to, diff); if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);} } } }, // Split a part off a line, keeping styles and markers intact. split: function(pos, textBefore) { var st = [textBefore, null], mk = this.marked; copyStyles(pos, this.text.length, this.styles, st); var taken = new Line(textBefore + this.text.slice(pos), st); if (mk) { for (var i = 0; i < mk.length; ++i) { var mark = mk[i]; var newmark = mark.split(pos, textBefore.length); if (newmark) { if (!taken.marked) taken.marked = []; taken.marked.push(newmark); newmark.attach(taken); if (newmark == mark) mk.splice(i--, 1); } } } return taken; }, append: function(line) { var mylen = this.text.length, mk = line.marked, mymk = this.marked; this.text += line.text; copyStyles(0, line.text.length, line.styles, this.styles); if (mymk) { for (var i = 0; i < mymk.length; ++i) if (mymk[i].to == null) mymk[i].to = mylen; } if (mk && mk.length) { if (!mymk) this.marked = mymk = []; outer: for (var i = 0; i < mk.length; ++i) { var mark = mk[i]; if (!mark.from) { for (var j = 0; j < mymk.length; ++j) { var mymark = mymk[j]; if (mymark.to == mylen && mymark.sameSet(mark)) { mymark.to = mark.to == null ? null : mark.to + mylen; if (mymark.isDead()) { mymark.detach(this); mk.splice(i--, 1); } continue outer; } } } mymk.push(mark); mark.attach(this); mark.from += mylen; if (mark.to != null) mark.to += mylen; } } }, fixMarkEnds: function(other) { var mk = this.marked, omk = other.marked; if (!mk) return; outer: for (var i = 0; i < mk.length; ++i) { var mark = mk[i], close = mark.to == null; if (close && omk) { for (var j = 0; j < omk.length; ++j) { var om = omk[j]; if (!om.sameSet(mark) || om.from != null) continue if (mark.from == this.text.length && om.to == 0) { omk.splice(j, 1); mk.splice(i--, 1); continue outer; } else { close = false; break; } } } if (close) mark.to = this.text.length; } }, fixMarkStarts: function() { var mk = this.marked; if (!mk) return; for (var i = 0; i < mk.length; ++i) if (mk[i].from == null) mk[i].from = 0; }, addMark: function(mark) { mark.attach(this); if (this.marked == null) this.marked = []; this.marked.push(mark); this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);}); }, // Run the given mode's parser over a line, update the styles // array, which contains alternating fragments of text and CSS // classes. highlight: function(mode, state, tabSize) { var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0; var changed = false, curWord = st[0], prevWord; if (this.text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { var style = mode.token(stream, state); var substr = this.text.slice(stream.start, stream.pos); stream.start = stream.pos; if (pos && st[pos-1] == style) st[pos-2] += substr; else if (substr) { if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true; st[pos++] = substr; st[pos++] = style; prevWord = curWord; curWord = st[pos]; } // Give up when line is ridiculously long if (stream.pos > 5000) { st[pos++] = this.text.slice(stream.pos); st[pos++] = null; break; } } if (st.length != pos) {st.length = pos; changed = true;} if (pos && st[pos-2] != prevWord) changed = true; // Short lines with simple highlights return null, and are // counted as changed by the driver because they are likely to // highlight the same way in various contexts. return changed || (st.length < 5 && this.text.length < 10 ? null : false); }, // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(mode, state, ch) { var txt = this.text, stream = new StringStream(txt); while (stream.pos < ch && !stream.eol()) { stream.start = stream.pos; var style = mode.token(stream, state); } return {start: stream.start, end: stream.pos, string: stream.current(), className: style || null, state: state}; }, indentation: function(tabSize) {return countColumn(this.text, null, tabSize);}, // Produces an HTML fragment for the line, taking selection, // marking, and highlighting into account. getHTML: function(makeTab, wrapAt, wrapId, wrapWBR) { var html = [], first = true, col = 0; function span_(text, style) { if (!text) return; // Work around a bug where, in some compat modes, IE ignores leading spaces if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1); first = false; if (text.indexOf("\t") == -1) { col += text.length; var escaped = htmlEscape(text); } else { var escaped = ""; for (var pos = 0;;) { var idx = text.indexOf("\t", pos); if (idx == -1) { escaped += htmlEscape(text.slice(pos)); col += text.length - pos; break; } else { col += idx - pos; var tab = makeTab(col); escaped += htmlEscape(text.slice(pos, idx)) + tab.html; col += tab.width; pos = idx + 1; } } } if (style) html.push('<span class="', style, '">', escaped, "</span>"); else html.push(escaped); } var span = span_; if (wrapAt != null) { var outPos = 0, open = "<span id=\"" + wrapId + "\">"; span = function(text, style) { var l = text.length; if (wrapAt >= outPos && wrapAt < outPos + l) { if (wrapAt > outPos) { span_(text.slice(0, wrapAt - outPos), style); // See comment at the definition of spanAffectsWrapping if (wrapWBR) html.push("<wbr>"); } html.push(open); var cut = wrapAt - outPos; span_(opera ? text.slice(cut, cut + 1) : text.slice(cut), style); html.push("</span>"); if (opera) span_(text.slice(cut + 1), style); wrapAt--; outPos += l; } else { outPos += l; span_(text, style); // Output empty wrapper when at end of line // (Gecko and IE8+ do strange wrapping when adding a space // to the end of the line. Other browsers don't react well // to zero-width spaces. So we do hideous browser sniffing // to determine which to use.) if (outPos == wrapAt && outPos == len) html.push(open + (gecko || (ie && !ie_lt8) ? "&#x200b;" : " ") + "</span>"); // Stop outputting HTML when gone sufficiently far beyond measure else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){}; } } } var st = this.styles, allText = this.text, marked = this.marked; var len = allText.length; function styleToClass(style) { if (!style) return null; return "cm-" + style.replace(/ +/g, " cm-"); } if (!allText && wrapAt == null) { span(" "); } else if (!marked || !marked.length) { for (var i = 0, ch = 0; ch < len; i+=2) { var str = st[i], style = st[i+1], l = str.length; if (ch + l > len) str = str.slice(0, len - ch); ch += l; span(str, styleToClass(style)); } } else { var pos = 0, i = 0, text = "", style, sg = 0; var nextChange = marked[0].from || 0, marks = [], markpos = 0; function advanceMarks() { var m; while (markpos < marked.length && ((m = marked[markpos]).from == pos || m.from == null)) { if (m.style != null) marks.push(m); ++markpos; } nextChange = markpos < marked.length ? marked[markpos].from : Infinity; for (var i = 0; i < marks.length; ++i) { var to = marks[i].to; if (to == null) to = Infinity; if (to == pos) marks.splice(i--, 1); else nextChange = Math.min(to, nextChange); } } var m = 0; while (pos < len) { if (nextChange == pos) advanceMarks(); var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; var appliedStyle = style; for (var j = 0; j < marks.length; ++j) appliedStyle = (appliedStyle ? appliedStyle + " " : "") + marks[j].style; span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle); if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} pos = end; } text = st[i++]; style = styleToClass(st[i++]); } } } return html.join(""); }, cleanUp: function() { this.parent = null; if (this.marked) for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this); } }; // Utility used by replace and split above function copyStyles(from, to, source, dest) { for (var i = 0, pos = 0, state = 0; pos < to; i+=2) { var part = source[i], end = pos + part.length; if (state == 0) { if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]); if (end >= from) state = 1; } else if (state == 1) { if (end > to) dest.push(part.slice(0, to - pos), source[i+1]); else dest.push(part, source[i+1]); } pos = end; } } // Data structure that holds the sequence of lines. function LeafChunk(lines) { this.lines = lines; this.parent = null; for (var i = 0, e = lines.length, height = 0; i < e; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length; }, remove: function(at, n, callbacks) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; this.height -= line.height; line.cleanUp(); if (line.handlers) for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]); } this.lines.splice(at, n); }, collapse: function(lines) { lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); }, insertHeight: function(at, lines, height) { this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; }, iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) if (op(this.lines[at])) return true; } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0, e = children.length; i < e; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size; }, remove: function(at, n, callbacks) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.remove(at, rm, callbacks); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) break; at = 0; } else at -= sz; } if (this.size - n < 25) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); }, insert: function(at, lines) { var height = 0; for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; this.insertHeight(at, lines, height); }, insertHeight: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertHeight(at, lines, height); if (child.lines && child.lines.length > 50) { while (child.lines.length > 50) { var spilled = child.lines.splice(child.lines.length - 25, 25); var newleaf = new LeafChunk(spilled); child.height -= newleaf.height; this.children.splice(i + 1, 0, newleaf); newleaf.parent = this; } this.maybeSpill(); } break; } at -= sz; } }, maybeSpill: function() { if (this.children.length <= 10) return; var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10); me.parent.maybeSpill(); }, iter: function(from, to, op) { this.iterN(from, to - from, op); }, iterN: function(at, n, op) { for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) return true; if ((n -= used) == 0) break; at = 0; } else at -= sz; } } }; function getLineAt(chunk, n) { while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break; } n -= sz; } } return chunk.lines[n]; } function lineNo(line) { if (line.parent == null) return null; var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0, e = chunk.children.length; ; ++i) { if (chunk.children[i] == cur) break; no += chunk.children[i].chunkSize(); } } return no; } function lineAtHeight(chunk, h) { var n = 0; outer: do { for (var i = 0, e = chunk.children.length; i < e; ++i) { var child = chunk.children[i], ch = child.height; if (h < ch) { chunk = child; continue outer; } h -= ch; n += child.chunkSize(); } return n; } while (!chunk.lines); for (var i = 0, e = chunk.lines.length; i < e; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) break; h -= lh; } return n + i; } function heightAtLine(chunk, n) { var h = 0; outer: do { for (var i = 0, e = chunk.children.length; i < e; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; continue outer; } n -= sz; h += child.height; } return h; } while (!chunk.lines); for (var i = 0; i < n; ++i) h += chunk.lines[i].height; return h; } // The history object 'chunks' changes that are made close together // and at almost the same time into bigger undoable units. function History() { this.time = 0; this.done = []; this.undone = []; this.compound = 0; this.closed = false; } History.prototype = { addChange: function(start, added, old) { this.undone.length = 0; var time = +new Date, cur = this.done[this.done.length - 1], last = cur && cur[cur.length - 1]; var dtime = time - this.time; if (this.compound && cur && !this.closed) { cur.push({start: start, added: added, old: old}); } else if (dtime > 400 || !last || this.closed || last.start > start + old.length || last.start + last.added < start) { this.done.push([{start: start, added: added, old: old}]); this.closed = false; } else { var startBefore = Math.max(0, last.start - start), endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); if (startBefore) last.start = start; last.added += added - (old.length - startBefore - endAfter); } this.time = time; }, startCompound: function() { if (!this.compound++) this.closed = true; }, endCompound: function() { if (!--this.compound) this.closed = true; } }; function stopMethod() {e_stop(this);} // Ensure an event has a stop method. function addStop(event) { if (!event.stop) event.stop = stopMethod; return event; } function e_preventDefault(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } function e_stopPropagation(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} CodeMirror.e_stop = e_stop; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; function e_target(e) {return e.target || e.srcElement;} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) b = 1; else if (e.button & 2) b = 3; else if (e.button & 4) b = 2; } if (mac && e.ctrlKey && b == 1) b = 3; return b; } // Allow 3rd-party code to override event properties by adding an override // object to an event object. function e_prop(e, prop) { var overridden = e.override && e.override.hasOwnProperty(prop); return overridden ? e.override[prop] : e[prop]; } // Event handler registration. If disconnect is true, it'll return a // function that unregisters the handler. function connect(node, type, handler, disconnect) { if (typeof node.addEventListener == "function") { node.addEventListener(type, handler, false); if (disconnect) return function() {node.removeEventListener(type, handler, false);}; } else { var wrapHandler = function(event) {handler(event || window.event);}; node.attachEvent("on" + type, wrapHandler); if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);}; } } CodeMirror.connect = connect; function Delayed() {this.id = null;} Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; var gecko = /gecko\/\d{7}/i.test(navigator.userAgent); var ie = /MSIE \d/.test(navigator.userAgent); var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); var quirksMode = ie && document.documentMode == 5; var webkit = /WebKit\//.test(navigator.userAgent); var chrome = /Chrome\//.test(navigator.userAgent); var opera = /Opera\//.test(navigator.userAgent); var safari = /Apple Computer/.test(navigator.vendor); var khtml = /KHTML\//.test(navigator.userAgent); var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent); // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie_lt9) return false; var div = document.createElement('div'); return "draggable" in div || "dragDrop" in div; }(); // Feature-detect whether newlines in textareas are converted to \r\n var lineSep = function () { var te = document.createElement("textarea"); te.value = "foo\nbar"; if (te.value.indexOf("\r") > -1) return "\r\n"; return "\n"; }(); // For a reason I have yet to figure out, some browsers disallow // word wrapping between certain characters *only* if a new inline // element is started between them. This makes it hard to reliably // measure the position of things, since that requires inserting an // extra span. This terribly fragile set of regexps matches the // character combinations that suffer from this phenomenon on the // various browsers. var spanAffectsWrapping = /^$/; // Won't match any two-character string if (gecko) spanAffectsWrapping = /$'/; else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = 0, n = 0; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; } function computedStyle(elt) { if (elt.currentStyle) return elt.currentStyle; return window.getComputedStyle(elt, null); } function eltOffset(node, screen) { // Take the parts of bounding client rect that we are interested in so we are able to edit if need be, // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page) try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; } catch(e) { box = {top: 0, left: 0}; } if (!screen) { // Get the toplevel scroll, working around browser differences. if (window.pageYOffset == null) { var t = document.documentElement || document.body.parentNode; if (t.scrollTop == null) t = document.body; box.top += t.scrollTop; box.left += t.scrollLeft; } else { box.top += window.pageYOffset; box.left += window.pageXOffset; } } return box; } // Get a node's text content. function eltText(node) { return node.textContent || node.innerText || node.nodeValue || ""; } function selectInput(node) { if (ios) { // Mobile Safari apparently has a bug where select() is broken. node.selectionStart = 0; node.selectionEnd = node.value.length; } else node.select(); } // Operations on {line, ch} objects. function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} function copyPos(x) {return {line: x.line, ch: x.ch};} var escapeElement = document.createElement("pre"); function htmlEscape(str) { escapeElement.textContent = str; return escapeElement.innerHTML; } // Recent (late 2011) Opera betas insert bogus newlines at the start // of the textContent, so we strip those. if (htmlEscape("a") == "\na") { htmlEscape = function(str) { escapeElement.textContent = str; return escapeElement.innerHTML.slice(1); }; // Some IEs don't preserve tabs through innerHTML } else if (htmlEscape("\t") != "\t") { htmlEscape = function(str) { escapeElement.innerHTML = ""; escapeElement.appendChild(document.createTextNode(str)); return escapeElement.innerHTML; }; } CodeMirror.htmlEscape = htmlEscape; // Used to position the cursor after an undo/redo by finding the // last edited character. function editEnd(from, to) { if (!to) return 0; if (!from) return to.length; for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) if (from.charAt(i) != to.charAt(j)) break; return j + 1; } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } function isWordChar(ch) { return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase(); } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) nl = string.length; var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result; } : function(string){return string.split(/\r\n?|\n/);}; CodeMirror.splitLines = splitLines; var hasSelection = window.getSelection ? function(te) { try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } } : function(te) { try {var range = te.ownerDocument.selection.createRange();} catch(e) {} if (!range || range.parentElement() != te) return false; return range.compareEndPoints("StartToEnd", range) != 0; }; CodeMirror.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); CodeMirror.defineMIME("text/plain", "null"); var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; CodeMirror.keyNames = keyNames; (function() { // Number keys for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); // Alphabetic keys for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); // Function keys for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; })(); return CodeMirror; })();
//------------------------------------- Waiting for the entire site to load ------------------------------------------------// jQuery(window).load(function() { jQuery("#loaderInner").fadeOut(); jQuery("#loader").delay(400).fadeOut("slow"); $('.teaserTitle ').stop().animate({marginTop :'330px', opacity:"1"}, 1000, 'easeOutQuint'); $('.down a ').stop().animate({marginTop :'30px', opacity:"1"}, 600, 'easeOutQuint'); }); $(document).ready(function(){ //------------------------------------- Navigation setup ------------------------------------------------// //--------- Scroll navigation ---------------// $("#mainNav ul a, .logo a, .shortLink a, .down a").click(function(event){ event.preventDefault(); var full_url = this.href; var parts = full_url.split("#"); var trgt = parts[1]; var target_offset = $("#"+trgt).offset(); var target_top = target_offset.top; $('html,body').animate({scrollTop:target_top -66}, 800); }); //-------------Highlight the current section in the navigation bar------------// var sections = $("section"); var navigation_links = $("#mainNav a"); sections.waypoint({ handler: function(event, direction) { var active_section; active_section = $(this); if (direction === "up") active_section = active_section.prev(); var active_link = $('#mainNav a[href="#' + active_section.attr("id") + '"]'); navigation_links.removeClass("active"); active_link.addClass("active"); }, offset: '35%' }); //------------------------------------- End navigation setup ------------------------------------------------// //------------------------------------- Facts counter ------------------------------------------------// $('.facts').appear(function() { $(".timer .count").each(function() { var counter = $(this).html(); $(this).countTo({ from: 0, to: counter, speed: 2000, refreshInterval: 60, }); }); }); //------------------------------------- End facts counter ------------------------------------------------// //---------------------------------- Testimonials-----------------------------------------// $('#testimonials').slides({ preload: false, generateNextPrev: false, play: 4500, container: 'testimoniaContainer' }); //---------------------------------- End testimonials-----------------------------------------// //--------------------------------- Hover animation for the elements of the portfolio --------------------------------// $(".link").css({ opacity: 0 }); $('.work, .item').hover( function(){ $(this).children('.link ').animate({ opacity: 0.90 }, 'fast'); }, function(){ $(this).children('.link ').animate({ opacity: 0 }, 'slow'); }); //--------------------------------- End hover animation for the elements of the portfolio --------------------------------// //-----------------------------------Initilaizing fancybox for the portfolio-------------------------------------------------// $('.portfolio a.folio').fancybox({ 'overlayShow' : true, 'opacity' : true, 'transitionIn' : 'elastic', 'transitionOut' : 'none', 'overlayOpacity' : 0.8 }); //-----------------------------------End initilaizing fancybox for the portfolio-------------------------------------------------// //--------------------------------- Sorting portfolio elements with quicksand plugin --------------------------------// var $portfolioClone = $('.portfolio').clone(); $('.filter a').click(function(e){ $('.filter li').removeClass('current'); var $filterClass = $(this).parent().attr('class'); if ( $filterClass == 'all' ) { var $filteredPortfolio = $portfolioClone.find('li'); } else { var $filteredPortfolio = $portfolioClone.find('li[data-type~=' + $filterClass + ']'); } $('.portfolio').quicksand( $filteredPortfolio, { duration: 800, easing: 'easeInOutQuad' }, function(){ $('.item').hover( function(){ $(this).children('.link').animate({ opacity: 0.90 }, 'fast'); }, function(){ $(this).children('.link').animate({ opacity: 0 }, 'slow'); }); //------------------------------ Reinitilaizing fancybox for the new cloned elements of the portfolio----------------------------// $('.portfolio a.folio').fancybox({ 'overlayShow' : true, 'opacity' : true, 'transitionIn' : 'elastic', 'transitionOut' : 'none', 'overlayOpacity' : 0.8 }); //-------------------------- End reinitilaizing fancybox for the new cloned elements of the portfolio ----------------------------// }); $(this).parent().addClass('current'); e.preventDefault(); }); //--------------------------------- End sorting portfolio elements with quicksand plugin--------------------------------// //---------------------------------- Form validation-----------------------------------------// $('#submit').click(function(){ $('input#name').removeClass("errorForm"); $('textarea#message').removeClass("errorForm"); $('input#email').removeClass("errorForm"); var error = false; var name = $('input#name').val(); if(name == "" || name == " ") { error = true; $('input#name').addClass("errorForm"); } var msg = $('textarea#message').val(); if(msg == "" || msg == " ") { error = true; $('textarea#message').addClass("errorForm"); } var email_compare = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i; var email = $('input#email').val(); if (email == "" || email == " ") { $('input#email').addClass("errorForm"); error = true; }else if (!email_compare.test(email)) { $('input#email').addClass("errorForm"); error = true; } if(error == true) { return false; } var data_string = $('.contactForm form').serialize(); $.ajax({ type: "POST", url: $('.contactForm form').attr('action'), data: data_string, success: function(message) { if(message == 'SENDING'){ $('#success').fadeIn('slow'); } else{ $('#error').fadeIn('slow'); } } }); return false; }); //---------------------------------- End form validation-----------------------------------------// //--------------------------------- To the top handler --------------------------------// $().UItoTop({ easingType: 'easeOutQuart' }); //--------------------------------- End to the top handler --------------------------------// //--------------------------------- Mobile menu --------------------------------// var fade=false; $('.mobileBtn').click(function() { if(fade==false){ $('#mainNav ul').slideDown("slow"); fade=true; return false; }else{ $('#mainNav ul').slideUp("faste"); fade=false; return false; } }); //--------------------------------- End mobile menu --------------------------------// //--------------------------------- Parallax --------------------------------// $(".testimonialsContainer").parallax("100%", 0.3); $(".feedContainer").parallax("100%", 0.3); //--------------------------------- End parallax --------------------------------// });
/** * Match Object * * Plan: * > Conducts one round between two agents. * > Requirements: * * 1) Must take the two agents and the payoff matrix as inputs. * 2) Must call Agent.nextMove() * 3) Must include a run() function * * Can I pass the history in as a parameter to nextMove(), i.e., Agent.nextMove(history) */ 'use strict'; var History = require('./history'), Agent = require('./agent'); module.exports = function(agentOneStrategy, agentTwoStrategy, payoffMatrix, rounds) { // Instantiate the agents var agentOne = new Agent(agentOneStrategy), agentTwo = new Agent(agentTwoStrategy); // Defines each agent's opponent agentOne.setOpponent(agentTwo.id()); agentTwo.setOpponent(agentOne.id()); // Initialize a history object var history = new History(payoffMatrix); // Runs the simulation var run = function() { while (rounds > 0) { // Next Turn var turn = {}; // Calculate the next moves and save them to the turn turn[ agentOne.id() ] = agentOne.nextMove(history); turn[ agentTwo.id() ] = agentTwo.nextMove(history); // Add the turn to the history history.store(turn); rounds--; } // After simulation, outputs the history return getScores(); }; var getScores = function() { var results = 'Player One:\n' + ' strategy: ' + agentOne.strategy() + '\n' + ' Score: ' + history.getScoreOf(agentOne) + '\n' + '\n' + 'Player Two\n' + ' strategy: ' + agentTwo.strategy() + '\n' + ' Score: ' + history.getScoreOf(agentTwo); console.log(results); return results; }; return { run: run } };
// http-response-error-filter.js const http = require("http"); const arccore = require("@encapsule/arccore"); const serializeResponseFilter = require("./http-response-serialize-filter"); const httpResponseErrorRequestSpec = require("./iospecs/http-response-error-request-spec"); var factoryResponse = arccore.filter.create({ operationID: "XoyKovKcQ-i-Pwy5PSrn1Q", operationName: "HTTP Error Responder", operationDescription: "Sends a normalized error response to a remote HTTP client.", inputFilterSpec: httpResponseErrorRequestSpec, bodyFunction: function(request_) { console.log("..... " + this.operationID + "::" + this.operationName); var response = { error: null, result: null }; var errors = []; var inBreakScope = false; while (!inBreakScope) { inBreakScope = true; // Wrap the output in an IRUT-tagged namespace object so that it can be easily discriminated // from other application and 3rd-party message signatures by derived applications. if (!request_.error_descriptor.http.message) { request_.error_descriptor.http.message = http.STATUS_CODES[request_.error_descriptor.http.code]; } request_.error_descriptor.data.http = request_.error_descriptor.http; request_.error_descriptor.data.request = request_.request_descriptor; request_.error_descriptor.data = { "ESCW71rwTz24meWiZpJb4A": request_.error_descriptor.data }; var innerResponse = serializeResponseFilter.request({ integrations: request_.integrations, streams: request_.streams, request_descriptor: request_.request_descriptor, response_descriptor: request_.error_descriptor }); if (innerResponse.error) { errors.unshift(innerResponse.error); break; } break; } if (errors.length) { response.error = errors.join(" "); console.error(response.error); } return response; } }); if (factoryResponse.error) { throw new Error(factoryResponse.error); } module.exports = factoryResponse.result;
module.exports = [ require('../../success/webpack.config'), require('../../success/webpack.config'), require('../../module-not-found-errors/webpack.config') ];
// This test written in mocha+should.js var should = require('./init.js'); var jdb = require('../'); var DataSource = jdb.DataSource; var createPromiseCallback = require('../lib/utils.js').createPromiseCallback; var db, tmp, Book, Chapter, Author, Reader; var Category, Job; var Picture, PictureLink; var Person, Address; var Link; var getTransientDataSource = function(settings) { return new DataSource('transient', settings, db.modelBuilder); }; var getMemoryDataSource = function(settings) { return new DataSource('memory', settings, db.modelBuilder); }; describe('relations', function () { before(function() { db = getSchema(); }); describe('hasMany', function () { before(function (done) { Book = db.define('Book', {name: String, type: String}); Chapter = db.define('Chapter', {name: {type: String, index: true}, bookType: String}); Author = db.define('Author', {name: String}); Reader = db.define('Reader', {name: String}); db.automigrate(['Book', 'Chapter', 'Author', 'Reader'], done); }); it('can be declared in different ways', function (done) { Book.hasMany(Chapter); Book.hasMany(Reader, {as: 'users'}); Book.hasMany(Author, {foreignKey: 'projectId'}); var b = new Book; b.chapters.should.be.an.instanceOf(Function); b.users.should.be.an.instanceOf(Function); b.authors.should.be.an.instanceOf(Function); Object.keys((new Chapter).toObject()).should.containEql('bookId'); Object.keys((new Author).toObject()).should.containEql('projectId'); db.automigrate(['Book', 'Chapter', 'Author', 'Reader'], done); }); it('can be declared in short form', function (done) { Author.hasMany('readers'); (new Author).readers.should.be.an.instanceOf(Function); Object.keys((new Reader).toObject()).should.containEql('authorId'); db.autoupdate(['Author', 'Reader'], done); }); describe('with scope', function() { before(function (done) { Book.hasMany(Chapter); done(); }); it('should build record on scope', function (done) { Book.create(function (err, book) { var c = book.chapters.build(); c.bookId.should.eql(book.id); c.save(done); }); }); it('should create record on scope', function (done) { Book.create(function (err, book) { book.chapters.create(function (err, c) { should.not.exist(err); should.exist(c); c.bookId.should.eql(book.id); done(); }); }); }); it('should create record on scope with promises', function (done) { Book.create() .then (function (book) { return book.chapters.create() .then (function (c) { should.exist(c); c.bookId.should.eql(book.id); done(); }); }).catch(done); }); it('should create a batch of records on scope', function (done) { var chapters = [ {name: 'a'}, {name: 'z'}, {name: 'c'} ]; Book.create(function (err, book) { book.chapters.create(chapters, function (err, chs) { should.not.exist(err); should.exist(chs); chs.should.have.lengthOf(chapters.length); chs.forEach(function(c) { c.bookId.should.eql(book.id); }); done(); }); }); }); it('should create a batch of records on scope with promises', function (done) { var chapters = [ {name: 'a'}, {name: 'z'}, {name: 'c'} ]; Book.create(function (err, book) { book.chapters.create(chapters) .then(function (chs) { should.exist(chs); chs.should.have.lengthOf(chapters.length); chs.forEach(function(c) { c.bookId.should.eql(book.id); }); done(); }).catch(done); }); }); it('should fetch all scoped instances', function (done) { Book.create(function (err, book) { book.chapters.create({name: 'a'}, function () { book.chapters.create({name: 'z'}, function () { book.chapters.create({name: 'c'}, function () { verify(book); }); }); }); }); function verify(book) { book.chapters(function (err, ch) { should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(3); var chapters = book.chapters(); chapters.should.eql(ch); book.chapters({order: 'name DESC'}, function (e, c) { should.not.exist(e); should.exist(c); c.shift().name.should.equal('z'); c.pop().name.should.equal('a'); done(); }); }); } }); it('should fetch all scoped instances with promises', function (done) { Book.create() .then(function (book) { return book.chapters.create({name: 'a'}) .then(function () { return book.chapters.create({name: 'z'}) }) .then(function () { return book.chapters.create({name: 'c'}) }) .then(function () { return verify(book); }); }).catch(done); function verify(book) { return book.chapters.getAsync() .then(function (ch) { should.exist(ch); ch.should.have.lengthOf(3); var chapters = book.chapters(); chapters.should.eql(ch); return book.chapters.getAsync({order: 'name DESC'}) .then(function (c) { should.exist(c); c.shift().name.should.equal('z'); c.pop().name.should.equal('a'); done(); }); }); } }); it('should fetch all scoped instances with getAsync with callback and condition', function (done) { Book.create(function (err, book) { book.chapters.create({name: 'a'}, function () { book.chapters.create({name: 'z'}, function () { book.chapters.create({name: 'c'}, function () { verify(book); }); }); }); }); function verify(book) { book.chapters(function (err, ch) { should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(3); var chapters = book.chapters(); chapters.should.eql(ch); book.chapters.getAsync({order: 'name DESC'}, function (e, c) { should.not.exist(e); should.exist(c); c.shift().name.should.equal('z'); c.pop().name.should.equal('a'); done(); }); }); } }); it('should fetch all scoped instances with getAsync with callback and no condition', function (done) { Book.create(function (err, book) { book.chapters.create({name: 'a'}, function () { book.chapters.create({name: 'z'}, function () { book.chapters.create({name: 'c'}, function () { verify(book); }); }); }); }); function verify(book) { book.chapters(function (err, ch) { should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(3); var chapters = book.chapters(); chapters.should.eql(ch); book.chapters.getAsync(function (e, c) { should.not.exist(e); should.exist(c); should.exist(c.length); c.shift().name.should.equal('a'); c.pop().name.should.equal('c'); done(); }); }); } }); it('should find scoped record', function (done) { var id; Book.create(function (err, book) { book.chapters.create({name: 'a'}, function (err, ch) { id = ch.id; book.chapters.create({name: 'z'}, function () { book.chapters.create({name: 'c'}, function () { verify(book); }); }); }); }); function verify(book) { book.chapters.findById(id, function (err, ch) { should.not.exist(err); should.exist(ch); ch.id.should.eql(id); done(); }); } }); it('should find scoped record with promises', function (done) { var id; Book.create() .then(function (book) { return book.chapters.create({name: 'a'}) .then(function (ch) { id = ch.id; return book.chapters.create({name: 'z'}) }) .then(function () { return book.chapters.create({name: 'c'}) }) .then(function () { return verify(book); }) }).catch(done); function verify(book) { return book.chapters.findById(id) .then(function (ch) { should.exist(ch); ch.id.should.eql(id); done(); }); } }); it('should count scoped records - all and filtered', function (done) { Book.create(function (err, book) { book.chapters.create({name: 'a'}, function (err, ch) { book.chapters.create({name: 'b'}, function () { book.chapters.create({name: 'c'}, function () { verify(book); }); }); }); }); function verify(book) { book.chapters.count(function (err, count) { should.not.exist(err); count.should.equal(3); book.chapters.count({ name: 'b' }, function (err, count) { should.not.exist(err); count.should.equal(1); done(); }); }); } }); it('should count scoped records - all and filtered with promises', function (done) { Book.create() .then(function (book) { book.chapters.create({name: 'a'}) .then(function () { return book.chapters.create({name: 'b'}) }) .then(function () { return book.chapters.create({name: 'c'}) }) .then(function () { return verify(book); }); }).catch(done); function verify(book) { return book.chapters.count() .then(function (count) { count.should.equal(3); return book.chapters.count({ name: 'b' }) }) .then(function (count) { count.should.equal(1); done(); }); } }); it('should set targetClass on scope property', function() { should.equal(Book.prototype.chapters._targetClass, 'Chapter'); }); it('should update scoped record', function (done) { var id; Book.create(function (err, book) { book.chapters.create({name: 'a'}, function (err, ch) { id = ch.id; book.chapters.updateById(id, {name: 'aa'}, function(err, ch) { verify(book); }); }); }); function verify(book) { book.chapters.findById(id, function (err, ch) { should.not.exist(err); should.exist(ch); ch.id.should.eql(id); ch.name.should.equal('aa'); done(); }); } }); it('should update scoped record with promises', function (done) { var id; Book.create() .then(function (book) { return book.chapters.create({name: 'a'}) .then(function (ch) { id = ch.id; return book.chapters.updateById(id, {name: 'aa'}) }) .then(function(ch) { return verify(book); }); }) .catch(done); function verify(book) { return book.chapters.findById(id) .then(function (ch) { should.exist(ch); ch.id.should.eql(id); ch.name.should.equal('aa'); done(); }); } }); it('should destroy scoped record', function (done) { var id; Book.create(function (err, book) { book.chapters.create({name: 'a'}, function (err, ch) { id = ch.id; book.chapters.destroy(id, function(err, ch) { verify(book); }); }); }); function verify(book) { book.chapters.findById(id, function (err, ch) { should.exist(err); done(); }); } }); it('should destroy scoped record with promises', function (done) { var id; Book.create() .then(function (book) { return book.chapters.create({name: 'a'}) .then(function (ch) { id = ch.id; return book.chapters.destroy(id) }) .then(function(ch) { return verify(book); }); }) .catch(done); function verify(book) { return book.chapters.findById(id) .catch(function (err) { should.exist(err); done(); }); } }); it('should check existence of a scoped record', function (done) { var id; Book.create(function (err, book) { book.chapters.create({name: 'a'}, function (err, ch) { id = ch.id; book.chapters.create({name: 'z'}, function () { book.chapters.create({name: 'c'}, function () { verify(book); }); }); }); }); function verify(book) { book.chapters.exists(id, function (err, flag) { should.not.exist(err); flag.should.be.eql(true); done(); }); } }); it('should check existence of a scoped record with promises', function (done) { var id; Book.create() .then(function (book) { return book.chapters.create({name: 'a'}) .then(function (ch) { id = ch.id; return book.chapters.create({name: 'z'}) }) .then(function () { return book.chapters.create({name: 'c'}) }) .then(function () { return verify(book); }); }).catch(done); function verify(book) { return book.chapters.exists(id) .then(function (flag) { flag.should.be.eql(true); done(); }); } }); it('should check ignore related data on creation - array', function (done) { Book.create({ chapters: [] }, function (err, book) { should.not.exist(err); book.chapters.should.be.a.function; var obj = book.toObject(); should.not.exist(obj.chapters); done(); }); }); it('should check ignore related data on creation with promises - array', function (done) { Book.create({ chapters: [] }) .then(function (book) { book.chapters.should.be.a.function; var obj = book.toObject(); should.not.exist(obj.chapters); done(); }).catch(done); }); it('should check ignore related data on creation - object', function (done) { Book.create({ chapters: {} }, function (err, book) { should.not.exist(err); book.chapters.should.be.a.function; var obj = book.toObject(); should.not.exist(obj.chapters); done(); }); }); it('should check ignore related data on creation with promises - object', function (done) { Book.create({ chapters: {} }) .then(function (book) { book.chapters.should.be.a.function; var obj = book.toObject(); should.not.exist(obj.chapters); done(); }).catch(done); }); }); }); describe('hasMany through', function () { var Physician, Patient, Appointment, Address; before(function (done) { // db = getSchema(); Physician = db.define('Physician', {name: String}); Patient = db.define('Patient', {name: String}); Appointment = db.define('Appointment', {date: {type: Date, default: function () { return new Date(); }}}); Address = db.define('Address', {name: String}); Physician.hasMany(Patient, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment}); Patient.belongsTo(Address); Appointment.belongsTo(Patient); Appointment.belongsTo(Physician); db.automigrate(['Physician', 'Patient', 'Appointment', 'Address'], done); }); it('should build record on scope', function (done) { Physician.create(function (err, physician) { var patient = physician.patients.build(); patient.physicianId.should.eql(physician.id); patient.save(done); }); }); it('should create record on scope', function (done) { Physician.create(function (err, physician) { physician.patients.create(function (err, patient) { should.not.exist(err); should.exist(patient); Appointment.find({where: {physicianId: physician.id, patientId: patient.id}}, function(err, apps) { should.not.exist(err); apps.should.have.lengthOf(1); done(); }); }); }); }); it('should create record on scope with promises', function (done) { Physician.create() .then(function (physician) { return physician.patients.create() .then(function (patient) { should.exist(patient); return Appointment.find({where: {physicianId: physician.id, patientId: patient.id}}) .then(function (apps) { apps.should.have.lengthOf(1); done(); }); }); }).catch(done); }); it('should create multiple records on scope', function (done) { var async = require('async'); Physician.create(function (err, physician) { physician.patients.create([{}, {}], function (err, patients) { should.not.exist(err); should.exist(patients); patients.should.have.lengthOf(2); function verifyPatient(patient, next) { Appointment.find({where: { physicianId: physician.id, patientId: patient.id }}, function(err, apps) { should.not.exist(err); apps.should.have.lengthOf(1); next(); }); } async.forEach(patients, verifyPatient, done); }); }); }); it('should create multiple records on scope with promises', function (done) { var async = require('async'); Physician.create() .then(function (physician) { return physician.patients.create([{}, {}]) .then(function (patients) { should.exist(patients); patients.should.have.lengthOf(2); function verifyPatient(patient, next) { Appointment.find({where: { physicianId: physician.id, patientId: patient.id }}) .then(function(apps) { apps.should.have.lengthOf(1); next(); }); } async.forEach(patients, verifyPatient, done); }); }).catch(done); }); it('should fetch all scoped instances', function (done) { Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function () { physician.patients.create({name: 'z'}, function () { physician.patients.create({name: 'c'}, function () { verify(physician); }); }); }); }); function verify(physician) { physician.patients(function (err, ch) { var patients = physician.patients(); patients.should.eql(ch); should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(3); done(); }); } }); it('should fetch all scoped instances with promises', function (done) { Physician.create() .then(function (physician) { return physician.patients.create({name: 'a'}) .then(function () { return physician.patients.create({name: 'z'}) }) .then(function () { return physician.patients.create({name: 'c'}) }) .then(function () { return verify(physician); }) }).catch(done); function verify(physician) { return physician.patients.getAsync() .then(function (ch) { var patients = physician.patients(); patients.should.eql(ch); should.exist(ch); ch.should.have.lengthOf(3); done(); }); } }); it('should fetch scoped instances with paging filters', function (done) { Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function () { physician.patients.create({name: 'z'}, function () { physician.patients.create({name: 'c'}, function () { verify(physician); }); }); }); }); function verify(physician) { //limit plus skip physician.patients({ limit:1, skip:1 },function (err, ch) { should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(1); ch[0].name.should.eql('z'); //offset plus skip physician.patients({ limit:1, offset:1 },function (err1, ch1) { should.not.exist(err1); should.exist(ch1); ch1.should.have.lengthOf(1); ch1[0].name.should.eql('z'); //order physician.patients({ order: "patientId DESC" },function (err2, ch2) { should.not.exist(err2); should.exist(ch2); ch2.should.have.lengthOf(3); ch2[0].name.should.eql('c'); done(); }); }); }); } }); it('should find scoped record', function (done) { var id; Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function (err, ch) { id = ch.id; physician.patients.create({name: 'z'}, function () { physician.patients.create({name: 'c'}, function () { verify(physician); }); }); }); }); function verify(physician) { physician.patients.findById(id, function (err, ch) { should.not.exist(err); should.exist(ch); ch.id.should.eql(id); done(); }); } }); it('should find scoped record with promises', function (done) { var id; Physician.create() .then(function (physician) { return physician.patients.create({name: 'a'}) .then(function (ch) { id = ch.id; return physician.patients.create({name: 'z'}) }) .then(function () { return physician.patients.create({name: 'c'}) }) .then(function () { return verify(physician); }); }).catch(done); function verify(physician) { return physician.patients.findById(id, function (err, ch) { should.not.exist(err); should.exist(ch); ch.id.should.eql(id); done(); }); } }); it('should allow to use include syntax on related data', function (done) { Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function (err, patient) { Address.create({name: 'z'}, function (err, address) { should.not.exist(err); patient.address(address); patient.save(function() { verify(physician, address.id); }); }); }); }); function verify(physician, addressId) { physician.patients({include: 'address'}, function (err, ch) { should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(1); ch[0].addressId.should.eql(addressId); var address = ch[0].address(); should.exist(address); address.should.be.an.instanceof(Address); address.name.should.equal('z'); done(); }); } }); it('should allow to use include syntax on related data with promises', function (done) { Physician.create() .then(function (physician) { return physician.patients.create({name: 'a'}) .then(function (patient) { return Address.create({name: 'z'}) .then(function (address) { patient.address(address); return patient.save() .then(function() { return verify(physician, address.id); }); }); }); }).catch(done); function verify(physician, addressId) { return physician.patients.getAsync({include: 'address'}) .then(function (ch) { should.exist(ch); ch.should.have.lengthOf(1); ch[0].addressId.should.eql(addressId); var address = ch[0].address(); should.exist(address); address.should.be.an.instanceof(Address); address.name.should.equal('z'); done(); }); } }); it('should set targetClass on scope property', function() { should.equal(Physician.prototype.patients._targetClass, 'Patient'); }); it('should update scoped record', function (done) { var id; Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function (err, ch) { id = ch.id; physician.patients.updateById(id, {name: 'aa'}, function(err, ch) { verify(physician); }); }); }); function verify(physician) { physician.patients.findById(id, function (err, ch) { should.not.exist(err); should.exist(ch); ch.id.should.eql(id); ch.name.should.equal('aa'); done(); }); } }); it('should update scoped record with promises', function (done) { var id; Physician.create() .then(function (physician) { return physician.patients.create({name: 'a'}) .then(function (ch) { id = ch.id; return physician.patients.updateById(id, {name: 'aa'}) .then(function(ch) { return verify(physician); }); }); }).catch(done); function verify(physician) { return physician.patients.findById(id) .then(function (ch) { should.exist(ch); ch.id.should.eql(id); ch.name.should.equal('aa'); done(); }); } }); it('should destroy scoped record', function (done) { var id; Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function (err, ch) { id = ch.id; physician.patients.destroy(id, function(err, ch) { verify(physician); }); }); }); function verify(physician) { physician.patients.findById(id, function (err, ch) { should.exist(err); done(); }); } }); it('should destroy scoped record with promises', function (done) { var id; Physician.create() .then(function (physician) { return physician.patients.create({name: 'a'}) .then(function (ch) { id = ch.id; return physician.patients.destroy(id) .then(function(ch) { return verify(physician); }); }); }).catch(done); function verify(physician) { return physician.patients.findById(id) .then(function (ch) { should.not.exist(ch); done(); }) .catch(function (err) { should.exist(err); done(); }); } }); it('should check existence of a scoped record', function (done) { var id; Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function (err, ch) { should.not.exist(err); id = ch.id; physician.patients.create({name: 'z'}, function () { physician.patients.create({name: 'c'}, function () { verify(physician); }); }); }); }); function verify(physician) { physician.patients.exists(id, function (err, flag) { should.not.exist(err); flag.should.be.eql(true); done(); }); } }); it('should check existence of a scoped record with promises', function (done) { var id; Physician.create() .then(function (physician) { return physician.patients.create({name: 'a'}) .then(function (ch) { id = ch.id; return physician.patients.create({name: 'z'}) }) .then(function () { return physician.patients.create({name: 'c'}) }) .then(function () { return verify(physician); }); }).catch(done); function verify(physician) { return physician.patients.exists(id) .then(function (flag) { flag.should.be.eql(true); done(); }); } }); it('should allow to add connection with instance', function (done) { Physician.create({name: 'ph1'}, function (e, physician) { Patient.create({name: 'pa1'}, function (e, patient) { physician.patients.add(patient, function (e, app) { should.not.exist(e); should.exist(app); app.should.be.an.instanceOf(Appointment); app.physicianId.should.eql(physician.id); app.patientId.should.eql(patient.id); done(); }); }); }); }); it('should allow to add connection with instance with promises', function (done) { Physician.create({name: 'ph1'}) .then(function (physician) { return Patient.create({name: 'pa1'}) .then(function (patient) { return physician.patients.add(patient) .then(function (app) { should.exist(app); app.should.be.an.instanceOf(Appointment); app.physicianId.should.eql(physician.id); app.patientId.should.eql(patient.id); done(); }); }); }).catch(done); }); it('should allow to add connection with through data', function (done) { Physician.create({name: 'ph1'}, function (e, physician) { Patient.create({name: 'pa1'}, function (e, patient) { var now = Date.now(); physician.patients.add(patient, { date: new Date(now) }, function (e, app) { should.not.exist(e); should.exist(app); app.should.be.an.instanceOf(Appointment); app.physicianId.should.eql(physician.id); app.patientId.should.eql(patient.id); app.patientId.should.eql(patient.id); app.date.getTime().should.equal(now); done(); }); }); }); }); it('should allow to add connection with through data with promises', function (done) { Physician.create({name: 'ph1'}) .then(function (physician) { return Patient.create({name: 'pa1'}) .then(function (patient) { var now = Date.now(); return physician.patients.add(patient, { date: new Date(now) }) .then(function (app) { should.exist(app); app.should.be.an.instanceOf(Appointment); app.physicianId.should.eql(physician.id); app.patientId.should.eql(patient.id); app.patientId.should.eql(patient.id); app.date.getTime().should.equal(now); done(); }); }); }).catch(done); }); it('should allow to remove connection with instance', function (done) { var id; Physician.create(function (err, physician) { physician.patients.create({name: 'a'}, function (err, patient) { id = patient.id; physician.patients.remove(id, function (err, ch) { verify(physician); }); }); }); function verify(physician) { physician.patients.exists(id, function (err, flag) { should.not.exist(err); flag.should.be.eql(false); done(); }); } }); it('should allow to remove connection with instance with promises', function (done) { var id; Physician.create() .then(function (physician) { return physician.patients.create({name: 'a'}) .then(function (patient) { id = patient.id; return physician.patients.remove(id) .then(function (ch) { return verify(physician); }); }); }).catch(done); function verify(physician) { return physician.patients.exists(id) .then(function (flag) { flag.should.be.eql(false); done(); }); } }); beforeEach(function (done) { Appointment.destroyAll(function (err) { Physician.destroyAll(function (err) { Patient.destroyAll(done); }); }); }); }); describe('hasMany through - collect', function () { var Physician, Patient, Appointment, Address; beforeEach(function (done) { // db = getSchema(); Physician = db.define('Physician', {name: String}); Patient = db.define('Patient', {name: String}); Appointment = db.define('Appointment', {date: {type: Date, default: function () { return new Date(); }}}); Address = db.define('Address', {name: String}); db.automigrate(['Physician', 'Patient', 'Appointment', 'Address'], done); }); describe('with default options', function () { it('can determine the collect by modelTo\'s name as default', function () { Physician.hasMany(Patient, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment, as: 'yyy'}); Patient.belongsTo(Address); Appointment.belongsTo(Physician); Appointment.belongsTo(Patient); var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'patient'); scope1.should.have.property('include', 'patient'); var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'physician'); scope2.should.have.property('include', 'physician'); }); }); describe('when custom reverse belongsTo names for both sides', function () { it('can determine the collect via keyThrough', function () { Physician.hasMany(Patient, {through: Appointment, foreignKey: 'fooId', keyThrough: 'barId'}); Patient.hasMany(Physician, {through: Appointment, foreignKey: 'barId', keyThrough: 'fooId', as: 'yyy'}); Appointment.belongsTo(Physician, {as: 'foo'}); Appointment.belongsTo(Patient, {as: 'bar'}); Patient.belongsTo(Address); // jam. Appointment.belongsTo(Patient, {as: 'car'}); // jam. Should we complain in this case??? var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); it('can determine the collect via modelTo name', function () { Physician.hasMany(Patient, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment, as: 'yyy'}); Appointment.belongsTo(Physician, {as: 'foo', foreignKey: 'physicianId'}); Appointment.belongsTo(Patient, {as: 'bar', foreignKey: 'patientId'}); Patient.belongsTo(Address); // jam. var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); it('can determine the collect via modelTo name (with jams)', function () { Physician.hasMany(Patient, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment, as: 'yyy'}); Appointment.belongsTo(Physician, {as: 'foo', foreignKey: 'physicianId'}); Appointment.belongsTo(Patient, {as: 'bar', foreignKey: 'patientId'}); Patient.belongsTo(Address); // jam. Appointment.belongsTo(Physician, {as: 'goo', foreignKey: 'physicianId'}); // jam. Should we complain in this case??? Appointment.belongsTo(Patient, {as: 'car', foreignKey: 'patientId'}); // jam. Should we complain in this case??? var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); // first matched relation scope2.should.have.property('include', 'foo'); // first matched relation }); }); describe('when custom reverse belongsTo name for one side only', function () { beforeEach(function () { Physician.hasMany(Patient, {as: 'xxx', through: Appointment, foreignKey: 'fooId'}); Patient.hasMany(Physician, {as: 'yyy', through: Appointment, keyThrough: 'fooId'}); Appointment.belongsTo(Physician, {as: 'foo'}); Appointment.belongsTo(Patient); Patient.belongsTo(Address); // jam. Appointment.belongsTo(Physician, {as: 'bar'}); // jam. Should we complain in this case??? }); it('can determine the collect via model name', function () { var physician = new Physician({id: 1}); var scope1 = physician.xxx._scope; scope1.should.have.property('collect', 'patient'); scope1.should.have.property('include', 'patient'); }); it('can determine the collect via keyThrough', function () { var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); }); }); describe('hasMany through bi-directional relations on the same model', function () { var User, Follow, Address; before(function (done) { // db = getSchema(); User = db.define('User', {name: String}); Follow = db.define('Follow', {date: {type: Date, default: function () { return new Date(); }}}); Address = db.define('Address', {name: String}); User.hasMany(User, {as: 'followers', foreignKey: 'followeeId', keyThrough: 'followerId', through: Follow}); User.hasMany(User, {as: 'following', foreignKey: 'followerId', keyThrough: 'followeeId', through: Follow}); User.belongsTo(Address); Follow.belongsTo(User, {as: 'follower'}); Follow.belongsTo(User, {as: 'followee'}); db.automigrate(['User', 'Follow'], done); }); it('should set foreignKeys of through model correctly in first relation', function (done) { var follower = new User({id: 1}); var followee = new User({id: 2}); followee.followers.add(follower, function (err, throughInst) { should.not.exist(err); should.exist(throughInst); throughInst.followerId.should.eql(follower.id); throughInst.followeeId.should.eql(followee.id); done(); }); }); it('should set foreignKeys of through model correctly in second relation', function (done) { var follower = new User({id: 3}); var followee = new User({id: 4}); follower.following.add(followee, function (err, throughInst) { should.not.exist(err); should.exist(throughInst); throughInst.followeeId.should.eql(followee.id); throughInst.followerId.should.eql(follower.id); done(); }); }); }); describe('hasMany through - between same models', function () { var User, Follow, Address; before(function (done) { // db = getSchema(); User = db.define('User', {name: String}); Follow = db.define('Follow', {date: {type: Date, default: function () { return new Date(); }}}); Address = db.define('Address', {name: String}); User.hasMany(User, {as: 'followers', foreignKey: 'followeeId', keyThrough: 'followerId', through: Follow}); User.hasMany(User, {as: 'following', foreignKey: 'followerId', keyThrough: 'followeeId', through: Follow}); User.belongsTo(Address); Follow.belongsTo(User, {as: 'follower'}); Follow.belongsTo(User, {as: 'followee'}); db.automigrate(['User', 'Follow', 'Address'], done); }); it('should set the keyThrough and the foreignKey', function (done) { var user = new User({id: 1}); var user2 = new User({id: 2}); user.following.add(user2, function (err, f) { should.not.exist(err); should.exist(f); f.followeeId.should.eql(user2.id); f.followerId.should.eql(user.id); done(); }); }); it('can determine the collect via keyThrough for each side', function () { var user = new User({id: 1}); var scope1 = user.followers._scope; scope1.should.have.property('collect', 'follower'); scope1.should.have.property('include', 'follower'); var scope2 = user.following._scope; scope2.should.have.property('collect', 'followee'); scope2.should.have.property('include', 'followee'); }); }); describe('hasMany with properties', function () { it('can be declared with properties', function (done) { Book.hasMany(Chapter, { properties: { type: 'bookType' } }); db.automigrate(['Book', 'Chapter'], done); }); it('should create record on scope', function (done) { Book.create({ type: 'fiction' }, function (err, book) { book.chapters.create(function (err, c) { should.not.exist(err); should.exist(c); c.bookId.should.eql(book.id); c.bookType.should.equal('fiction'); done(); }); }); }); it('should create record on scope with promises', function (done) { Book.create({ type: 'fiction' }) .then(function (book) { return book.chapters.create() .then(function (c) { should.exist(c); c.bookId.should.eql(book.id); c.bookType.should.equal('fiction'); done(); }); }).catch(done); }); }); describe('hasMany with scope and properties', function () { it('can be declared with properties', function (done) { // db = getSchema(); Category = db.define('Category', {name: String, jobType: String}); Job = db.define('Job', {name: String, type: String}); Category.hasMany(Job, { properties: function(inst, target) { if (!inst.jobType) return; // skip return { type: inst.jobType }; }, scope: function(inst, filter) { var m = this.properties(inst); // re-use properties if (m) return { where: m }; } }); db.automigrate(['Category', 'Job'], done); }); it('should create record on scope', function (done) { Category.create(function (err, c) { should.not.exists(err); c.jobs.create({ type: 'book' }, function(err, p) { should.not.exists(err); p.categoryId.should.eql(c.id); p.type.should.equal('book'); c.jobs.create({ type: 'widget' }, function(err, p) { should.not.exists(err); p.categoryId.should.eql(c.id); p.type.should.equal('widget'); done(); }); }); }); }); it('should create record on scope with promises', function (done) { Category.create() .then(function (c) { return c.jobs.create({ type: 'book' }) .then(function (p) { p.categoryId.should.eql(c.id); p.type.should.equal('book'); return c.jobs.create({ type: 'widget' }) .then(function (p) { p.categoryId.should.eql(c.id); p.type.should.equal('widget'); done(); }); }); }).catch(done); }); it('should find records on scope', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobs(function(err, jobs) { should.not.exists(err); jobs.should.have.length(2); done(); }); }); }); it('should find records on scope with promises', function (done) { Category.findOne() .then(function (c) { return c.jobs.getAsync() }) .then(function(jobs) { jobs.should.have.length(2); done(); }) .catch(done); }); it('should find record on scope - filtered', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobs({ where: { type: 'book' } }, function(err, jobs) { should.not.exists(err); jobs.should.have.length(1); jobs[0].type.should.equal('book'); done(); }); }); }); it('should find record on scope with promises - filtered', function (done) { Category.findOne() .then(function (c) { return c.jobs.getAsync({ where: { type: 'book' } }) }) .then(function(jobs) { jobs.should.have.length(1); jobs[0].type.should.equal('book'); done(); }) .catch(done); }); // So why not just do the above? In LoopBack, the context // that gets passed into a beforeRemote handler contains // a reference to the parent scope/instance: ctx.instance // in order to enforce a (dynamic scope) at runtime // a temporary property can be set in the beforeRemoting // handler. Optionally,properties dynamic properties can be declared. // // The code below simulates this. it('should create record on scope - properties', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobType = 'tool'; // temporary c.jobs.create(function(err, p) { p.categoryId.should.eql(c.id); p.type.should.equal('tool'); done(); }); }); }); it('should find records on scope', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobs(function(err, jobs) { should.not.exists(err); jobs.should.have.length(3); done(); }); }); }); it('should find record on scope - scoped', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobType = 'book'; // temporary, for scoping c.jobs(function(err, jobs) { should.not.exists(err); jobs.should.have.length(1); jobs[0].type.should.equal('book'); done(); }); }); }); it('should find record on scope - scoped', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobType = 'tool'; // temporary, for scoping c.jobs(function(err, jobs) { should.not.exists(err); jobs.should.have.length(1); jobs[0].type.should.equal('tool'); done(); }); }); }); it('should find count of records on scope - scoped', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobType = 'tool'; // temporary, for scoping c.jobs.count(function(err, count) { should.not.exists(err); count.should.equal(1); done(); }); }); }); it('should delete records on scope - scoped', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobType = 'tool'; // temporary, for scoping c.jobs.destroyAll(function(err, result) { done(err); }); }); }); it('should find record on scope - verify', function (done) { Category.findOne(function (err, c) { should.not.exists(err); c.jobs(function(err, jobs) { should.not.exists(err); jobs.should.have.length(2); done(); }); }); }); }); describe('polymorphic hasOne', function () { before(function (done) { // db = getSchema(); Picture = db.define('Picture', {name: String}); Author = db.define('Author', {name: String}); Reader = db.define('Reader', {name: String}); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('can be declared', function (done) { Author.hasOne(Picture, { as: 'avatar', polymorphic: 'imageable' }); Reader.hasOne(Picture, { as: 'mugshot', polymorphic: 'imageable' }); Picture.belongsTo('imageable', { polymorphic: true }); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('should create polymorphic relation - author', function (done) { Author.create({name: 'Author 1' }, function (err, author) { should.not.exists(err); author.avatar.create({ name: 'Avatar' }, function (err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(author.id); p.imageableType.should.equal('Author'); done(); }); }); }); it('should create polymorphic relation with promises - author', function (done) { Author.create({name: 'Author 1' }) .then(function (author) { return author.avatar.create({ name: 'Avatar' }) .then(function (p) { should.exist(p); p.imageableId.should.eql(author.id); p.imageableType.should.equal('Author'); done(); }); }).catch(done); }); it('should create polymorphic relation - reader', function (done) { Reader.create({name: 'Reader 1' }, function (err, reader) { should.not.exists(err); reader.mugshot.create({ name: 'Mugshot' }, function (err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(reader.id); p.imageableType.should.equal('Reader'); done(); }); }); }); it('should find polymorphic relation - author', function (done) { Author.findOne(function (err, author) { should.not.exists(err); author.avatar(function (err, p) { should.not.exist(err); var avatar = author.avatar(); avatar.should.equal(p); p.name.should.equal('Avatar'); p.imageableId.should.eql(author.id); p.imageableType.should.equal('Author'); done(); }); }); }); it('should find polymorphic relation - reader', function (done) { Reader.findOne(function (err, reader) { should.not.exists(err); reader.mugshot(function (err, p) { should.not.exist(err); p.name.should.equal('Mugshot'); p.imageableId.should.eql(reader.id); p.imageableType.should.equal('Reader'); done(); }); }); }); it('should include polymorphic relation - author', function (done) { Author.findOne({include: 'avatar'}, function (err, author) { should.not.exists(err); var avatar = author.avatar(); should.exist(avatar); avatar.name.should.equal('Avatar'); done(); }); }); it('should find polymorphic relation with promises - reader', function (done) { Reader.findOne() .then(function (reader) { return reader.mugshot.getAsync() .then(function (p) { p.name.should.equal('Mugshot'); p.imageableId.should.eql(reader.id); p.imageableType.should.equal('Reader'); done(); }); }).catch(done); }); it('should find inverse polymorphic relation - author', function (done) { Picture.findOne({ where: { name: 'Avatar' } }, function (err, p) { should.not.exists(err); p.imageable(function (err, imageable) { should.not.exist(err); imageable.should.be.instanceof(Author); imageable.name.should.equal('Author 1'); done(); }); }); }); it('should include inverse polymorphic relation - author', function (done) { Picture.findOne({where: {name: 'Avatar'}, include: 'imageable'}, function (err, p) { should.not.exists(err); var imageable = p.imageable(); should.exist(imageable); imageable.should.be.instanceof(Author); imageable.name.should.equal('Author 1'); done(); }); }); it('should find inverse polymorphic relation - reader', function (done) { Picture.findOne({ where: { name: 'Mugshot' } }, function (err, p) { should.not.exists(err); p.imageable(function (err, imageable) { should.not.exist(err); imageable.should.be.instanceof(Reader); imageable.name.should.equal('Reader 1'); done(); }); }); }); }); describe('polymorphic hasOne with non standard ids', function () { before(function (done) { // db = getSchema(); Picture = db.define('Picture', {name: String}); Author = db.define('Author', { username: {type: String, id: true, generated: true}, name: String }); Reader = db.define('Reader', { username: {type: String, id: true, generated: true}, name: String }); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('can be declared with non standard foreign key', function (done) { Author.hasOne(Picture, { as: 'avatar', polymorphic: { foreignKey: 'oid', discriminator: 'type' } }); Reader.hasOne(Picture, { as: 'mugshot', polymorphic: { foreignKey: 'oid', discriminator: 'type' } }); Picture.belongsTo('owner', { idName: 'username', polymorphic: { idType: Author.definition.properties.username.type, foreignKey: 'oid', discriminator: 'type' } }); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('should create polymorphic relation - author', function (done) { Author.create({name: 'Author 1' }, function (err, author) { should.not.exists(err); author.avatar.create({ name: 'Avatar' }, function (err, p) { should.not.exist(err); should.exist(p); p.oid.toString().should.equal(author.username.toString()); p.type.should.equal('Author'); done(); }); }); }); it('should create polymorphic relation with promises - author', function (done) { Author.create({name: 'Author 1' }) .then(function (author) { return author.avatar.create({ name: 'Avatar' }) .then(function (p) { should.exist(p); p.oid.toString().should.equal(author.username.toString()); p.type.should.equal('Author'); done(); }); }).catch(done); }); it('should create polymorphic relation - reader', function (done) { Reader.create({name: 'Reader 1' }, function (err, reader) { should.not.exists(err); reader.mugshot.create({ name: 'Mugshot' }, function (err, p) { should.not.exist(err); should.exist(p); p.oid.toString().should.equal(reader.username.toString()); p.type.should.equal('Reader'); done(); }); }); }); it('should find polymorphic relation - author', function (done) { Author.findOne(function (err, author) { should.not.exists(err); author.avatar(function (err, p) { should.not.exist(err); var avatar = author.avatar(); avatar.should.equal(p); p.name.should.equal('Avatar'); p.oid.toString().should.equal(author.username.toString()); p.type.should.equal('Author'); done(); }); }); }); it('should find polymorphic relation - reader', function (done) { Reader.findOne(function (err, reader) { should.not.exists(err); reader.mugshot(function (err, p) { should.not.exist(err); p.name.should.equal('Mugshot'); p.oid.toString().should.equal(reader.username.toString()); p.type.should.equal('Reader'); done(); }); }); }); it('should find inverse polymorphic relation - author', function (done) { Picture.findOne({ where: { name: 'Avatar' } }, function (err, p) { should.not.exists(err); p.owner(function (err, owner) { should.not.exist(err); owner.should.be.instanceof(Author); owner.name.should.equal('Author 1'); done(); }); }); }); it('should find inverse polymorphic relation - reader', function (done) { Picture.findOne({ where: { name: 'Mugshot' } }, function (err, p) { should.not.exists(err); p.owner(function (err, owner) { should.not.exist(err); owner.should.be.instanceof(Reader); owner.name.should.equal('Reader 1'); done(); }); }); }); it('should include polymorphic relation - reader', function (done) { Reader.findOne({include: 'mugshot'}, function (err, reader) { should.not.exists(err); var mugshot = reader.mugshot(); should.exist(mugshot); mugshot.name.should.equal('Mugshot'); done(); }); }); it('should include inverse polymorphic relation - reader', function (done) { Picture.findOne({where: {name: 'Mugshot'}, include: 'owner'}, function (err, p) { should.not.exists(err); var owner = p.owner(); should.exist(owner); owner.should.be.instanceof(Reader); owner.name.should.equal('Reader 1'); done(); }); }); }); describe('polymorphic hasMany', function () { before(function (done) { // db = getSchema(); Picture = db.define('Picture', {name: String}); Author = db.define('Author', {name: String}); Reader = db.define('Reader', {name: String}); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('can be declared', function (done) { Author.hasMany(Picture, { polymorphic: 'imageable' }); Reader.hasMany(Picture, { polymorphic: { // alt syntax as: 'imageable', foreignKey: 'imageableId', discriminator: 'imageableType' } }); Picture.belongsTo('imageable', { polymorphic: true }); Author.relations['pictures'].toJSON().should.eql({ name: 'pictures', type: 'hasMany', modelFrom: 'Author', keyFrom: 'id', modelTo: 'Picture', keyTo: 'imageableId', multiple: true, polymorphic: { as: 'imageable', foreignKey: 'imageableId', discriminator: 'imageableType' } }); Picture.relations['imageable'].toJSON().should.eql({ name: 'imageable', type: 'belongsTo', modelFrom: 'Picture', keyFrom: 'imageableId', modelTo: '<polymorphic>', keyTo: 'id', multiple: false, polymorphic: { as: 'imageable', foreignKey: 'imageableId', discriminator: 'imageableType' } }); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('should create polymorphic relation - author', function (done) { Author.create({ name: 'Author 1' }, function (err, author) { should.not.exists(err); author.pictures.create({ name: 'Author Pic' }, function (err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(author.id); p.imageableType.should.equal('Author'); done(); }); }); }); it('should create polymorphic relation - reader', function (done) { Reader.create({ name: 'Reader 1' }, function (err, reader) { should.not.exists(err); reader.pictures.create({ name: 'Reader Pic' }, function (err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(reader.id); p.imageableType.should.equal('Reader'); done(); }); }); }); it('should find polymorphic items - author', function (done) { Author.findOne(function (err, author) { should.not.exists(err); author.pictures(function (err, pics) { should.not.exist(err); var pictures = author.pictures(); pictures.should.eql(pics); pics.should.have.length(1); pics[0].name.should.equal('Author Pic'); done(); }); }); }); it('should find polymorphic items - reader', function (done) { Reader.findOne(function (err, reader) { should.not.exists(err); reader.pictures(function (err, pics) { should.not.exist(err); pics.should.have.length(1); pics[0].name.should.equal('Reader Pic'); done(); }); }); }); it('should find the inverse of polymorphic relation - author', function (done) { Picture.findOne({ where: { name: 'Author Pic' } }, function (err, p) { should.not.exist(err); p.imageableType.should.equal('Author'); p.imageable(function(err, imageable) { should.not.exist(err); imageable.should.be.instanceof(Author); imageable.name.should.equal('Author 1'); done(); }); }); }); it('should find the inverse of polymorphic relation - reader', function (done) { Picture.findOne({ where: { name: 'Reader Pic' } }, function (err, p) { should.not.exist(err); p.imageableType.should.equal('Reader'); p.imageable(function(err, imageable) { should.not.exist(err); imageable.should.be.instanceof(Reader); imageable.name.should.equal('Reader 1'); done(); }); }); }); it('should include the inverse of polymorphic relation', function (done) { Picture.find({ include: 'imageable' }, function (err, pics) { should.not.exist(err); pics.should.have.length(2); pics[0].name.should.equal('Author Pic'); pics[0].imageable().name.should.equal('Author 1'); pics[1].name.should.equal('Reader Pic'); pics[1].imageable().name.should.equal('Reader 1'); done(); }); }); it('should assign a polymorphic relation', function(done) { Author.create({ name: 'Author 2' }, function(err, author) { should.not.exists(err); var p = new Picture({ name: 'Sample' }); p.imageable(author); // assign p.imageableId.should.eql(author.id); p.imageableType.should.equal('Author'); p.save(done); }); }); it('should find polymorphic items - author', function (done) { Author.findOne({ where: { name: 'Author 2' } }, function (err, author) { should.not.exists(err); author.pictures(function (err, pics) { should.not.exist(err); pics.should.have.length(1); pics[0].name.should.equal('Sample'); done(); }); }); }); it('should find the inverse of polymorphic relation - author', function (done) { Picture.findOne({ where: { name: 'Sample' } }, function (err, p) { should.not.exist(err); p.imageableType.should.equal('Author'); p.imageable(function(err, imageable) { should.not.exist(err); imageable.should.be.instanceof(Author); imageable.name.should.equal('Author 2'); done(); }); }); }); it('should include the inverse of polymorphic relation - author', function (done) { Picture.findOne({where: {name: 'Sample'}, include: 'imageable'}, function (err, p) { should.not.exist(err); var imageable = p.imageable(); should.exist(imageable); imageable.should.be.instanceof(Author); imageable.name.should.equal('Author 2'); done(); }); }); }); describe('polymorphic hasAndBelongsToMany through', function () { before(function (done) { // db = getSchema(); Picture = db.define('Picture', {name: String}); Author = db.define('Author', {name: String}); Reader = db.define('Reader', {name: String}); PictureLink = db.define('PictureLink', {}); db.automigrate(['Picture', 'Author', 'Reader', 'PictureLink'], done); }); it('can be declared', function (done) { Author.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); Reader.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); // Optionally, define inverse relations: Picture.hasMany(Author, { through: PictureLink, polymorphic: 'imageable', invert: true }); Picture.hasMany(Reader, { through: PictureLink, polymorphic: 'imageable', invert: true }); db.automigrate(['Picture', 'Author', 'Reader', 'PictureLink'], done); }); it('can determine the collect via modelTo name', function () { Author.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); Reader.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); // Optionally, define inverse relations: Picture.hasMany(Author, { through: PictureLink, polymorphic: 'imageable', invert: true }); Picture.hasMany(Reader, { through: PictureLink, polymorphic: 'imageable', invert: true }); var author = new Author({id: 1}); var scope1 = author.pictures._scope; scope1.should.have.property('collect', 'picture'); scope1.should.have.property('include', 'picture'); var reader = new Reader({id: 1}); var scope2 = reader.pictures._scope; scope2.should.have.property('collect', 'picture'); scope2.should.have.property('include', 'picture'); var picture = new Picture({id: 1}); var scope3 = picture.authors._scope; scope3.should.have.property('collect', 'imageable'); scope3.should.have.property('include', 'imageable'); var scope4 = picture.readers._scope; scope4.should.have.property('collect', 'imageable'); scope4.should.have.property('include', 'imageable'); }); var author, reader, pictures = []; it('should create polymorphic relation - author', function (done) { Author.create({ name: 'Author 1' }, function (err, a) { should.not.exist(err); author = a; author.pictures.create({ name: 'Author Pic 1' }, function (err, p) { should.not.exist(err); pictures.push(p); author.pictures.create({ name: 'Author Pic 2' }, function (err, p) { should.not.exist(err); pictures.push(p); done(); }); }); }); }); it('should create polymorphic relation - reader', function (done) { Reader.create({ name: 'Reader 1' }, function (err, r) { should.not.exist(err); reader = r; reader.pictures.create({ name: 'Reader Pic 1' }, function (err, p) { should.not.exist(err); pictures.push(p); done(); }); }); }); it('should create polymorphic through model', function (done) { PictureLink.findOne(function(err, link) { should.not.exist(err); link.pictureId.should.eql(pictures[0].id); // eql for mongo ObjectId link.imageableId.should.eql(author.id); link.imageableType.should.equal('Author'); link.imageable(function(err, imageable) { imageable.should.be.instanceof(Author); imageable.id.should.eql(author.id); done(); }); }); }); it('should get polymorphic relation through model - author', function (done) { Author.findById(author.id, function(err, author) { should.not.exist(err); author.name.should.equal('Author 1'); author.pictures(function(err, pics) { should.not.exist(err); pics.should.have.length(2); pics[0].name.should.equal('Author Pic 1'); pics[1].name.should.equal('Author Pic 2'); done(); }); }); }); it('should get polymorphic relation through model - reader', function (done) { Reader.findById(reader.id, function(err, reader) { should.not.exist(err); reader.name.should.equal('Reader 1'); reader.pictures(function(err, pics) { should.not.exist(err); pics.should.have.length(1); pics[0].name.should.equal('Reader Pic 1'); done(); }); }); }); it('should include polymorphic items', function (done) { Author.find({ include: 'pictures' }, function(err, authors) { authors.should.have.length(1); authors[0].pictures(function(err, pics) { pics.should.have.length(2); pics[0].name.should.equal('Author Pic 1'); pics[1].name.should.equal('Author Pic 2'); done(); }); }); }); var anotherPicture; it('should add to a polymorphic relation - author', function (done) { Author.findById(author.id, function(err, author) { Picture.create({name: 'Example' }, function(err, p) { should.not.exist(err); pictures.push(p); anotherPicture = p; author.pictures.add(p, function(err, link) { link.should.be.instanceof(PictureLink); link.pictureId.should.eql(p.id); link.imageableId.should.eql(author.id); link.imageableType.should.equal('Author'); done(); }); }); }); }); it('should create polymorphic through model', function (done) { PictureLink.findOne({ where: { pictureId: anotherPicture.id, imageableType: 'Author' } }, function(err, link) { should.not.exist(err); link.pictureId.should.eql(anotherPicture.id); link.imageableId.should.eql(author.id); link.imageableType.should.equal('Author'); done(); }); }); var anotherAuthor, anotherReader; it('should add to a polymorphic relation - author', function (done) { Author.create({ name: 'Author 2' }, function (err, author) { should.not.exist(err); anotherAuthor = author; author.pictures.add(anotherPicture.id, function (err, p) { should.not.exist(err); done(); }); }); }); it('should add to a polymorphic relation - author', function (done) { Reader.create({name: 'Reader 2' }, function (err, reader) { should.not.exist(err); anotherReader = reader; reader.pictures.add(anotherPicture.id, function (err, p) { should.not.exist(err); done(); }); }); }); it('should get the inverse polymorphic relation - author', function (done) { Picture.findById(anotherPicture.id, function(err, p) { p.authors(function(err, authors) { authors.should.have.length(2); authors[0].name.should.equal('Author 1'); authors[1].name.should.equal('Author 2'); done(); }); }); }); it('should get the inverse polymorphic relation - reader', function (done) { Picture.findById(anotherPicture.id, function(err, p) { p.readers(function(err, readers) { readers.should.have.length(1); readers[0].name.should.equal('Reader 2'); done(); }); }); }); it('should find polymorphic items - author', function (done) { Author.findById(author.id, function(err, author) { author.pictures(function(err, pics) { pics.should.have.length(3); pics[0].name.should.equal('Author Pic 1'); pics[1].name.should.equal('Author Pic 2'); pics[2].name.should.equal('Example'); done(); }); }); }); it('should check if polymorphic relation exists - author', function (done) { Author.findById(author.id, function(err, author) { author.pictures.exists(anotherPicture.id, function(err, exists) { exists.should.be.true; done(); }); }); }); it('should remove from a polymorphic relation - author', function (done) { Author.findById(author.id, function(err, author) { author.pictures.remove(anotherPicture.id, function(err) { should.not.exist(err); done(); }); }); }); it('should find polymorphic items - author', function (done) { Author.findById(author.id, function(err, author) { author.pictures(function(err, pics) { pics.should.have.length(2); pics[0].name.should.equal('Author Pic 1'); pics[1].name.should.equal('Author Pic 2'); done(); }); }); }); it('should check if polymorphic relation exists - author', function (done) { Author.findById(author.id, function(err, author) { author.pictures.exists(7, function(err, exists) { exists.should.be.false; done(); }); }); }); it('should create polymorphic item through relation scope', function (done) { Picture.findById(anotherPicture.id, function(err, p) { p.authors.create({ name: 'Author 3' }, function(err, a) { should.not.exist(err); author = a; author.name.should.equal('Author 3'); done(); }); }); }); it('should create polymorphic through model - new author', function (done) { PictureLink.findOne({ where: { pictureId: anotherPicture.id, imageableId: author.id, imageableType: 'Author' } }, function(err, link) { should.not.exist(err); link.pictureId.should.eql(anotherPicture.id); link.imageableId.should.eql(author.id); link.imageableType.should.equal('Author'); done(); }); }); it('should find polymorphic items - new author', function (done) { Author.findById(author.id, function(err, author) { author.pictures(function(err, pics) { pics.should.have.length(1); pics[0].id.should.eql(anotherPicture.id); pics[0].name.should.equal('Example'); done(); }); }); }); }); describe('belongsTo', function () { var List, Item, Fear, Mind; var listId, itemId; it('can be declared in different ways', function () { List = db.define('List', {name: String}); Item = db.define('Item', {name: String}); Fear = db.define('Fear'); Mind = db.define('Mind'); // syntax 1 (old) Item.belongsTo(List); Object.keys((new Item).toObject()).should.containEql('listId'); (new Item).list.should.be.an.instanceOf(Function); // syntax 2 (new) Fear.belongsTo('mind', { methods: { check: function() { return true; } } }); Object.keys((new Fear).toObject()).should.containEql('mindId'); (new Fear).mind.should.be.an.instanceOf(Function); // (new Fear).mind.build().should.be.an.instanceOf(Mind); }); it('should setup a custom method on accessor', function() { var rel = Fear.relations['mind']; rel.defineMethod('other', function() { return true; }) }); it('should have setup a custom method on accessor', function() { var f = new Fear(); f.mind.check.should.be.a.function; f.mind.check().should.be.true; f.mind.other.should.be.a.function; f.mind.other().should.be.true; }); it('can be used to query data', function (done) { List.hasMany('todos', {model: Item}); db.automigrate(['List', 'Item', 'Fear', 'Find'], function () { List.create({name: 'List 1'}, function (e, list) { listId = list.id; should.not.exist(e); should.exist(list); list.todos.create({name: 'Item 1'},function (err, todo) { itemId = todo.id; todo.list(function (e, l) { should.not.exist(e); should.exist(l); l.should.be.an.instanceOf(List); todo.list().id.should.equal(l.id); todo.list().name.should.equal('List 1'); done(); }); }); }); }); }); it('can be used to query data with getAsync with callback', function (done) { List.hasMany('todos', {model: Item}); db.automigrate(['List', 'Item', 'Fear', 'Find'], function () { List.create({name: 'List 1'}, function (e, list) { listId = list.id; should.not.exist(e); should.exist(list); list.todos.create({name: 'Item 1'},function (err, todo) { itemId = todo.id; todo.list.getAsync(function (e, l) { should.not.exist(e); should.exist(l); l.should.be.an.instanceOf(List); todo.list().id.should.equal(l.id); todo.list().name.should.equal('List 1'); done(); }); }); }); }); }); it('can be used to query data with promises', function (done) { List.hasMany('todos', {model: Item}); db.automigrate(['List', 'Item', 'Fear', 'Find'], function () { List.create({name: 'List 1'}) .then(function (list) { listId = list.id; should.exist(list); return list.todos.create({name: 'Item 1'}) }) .then(function (todo) { itemId = todo.id; return todo.list.getAsync() .then(function (l) { should.exist(l); l.should.be.an.instanceOf(List); todo.list().id.should.equal(l.id); todo.list().name.should.equal('List 1'); done(); }); }) .catch(done); }); }); it('could accept objects when creating on scope', function (done) { List.create(function (e, list) { should.not.exist(e); should.exist(list); Item.create({list: list}, function (err, item) { should.not.exist(err); should.exist(item); should.exist(item.listId); item.listId.should.equal(list.id); item.__cachedRelations.list.should.equal(list); done(); }); }); }); it('should update related item on scope', function(done) { Item.findById(itemId, function (e, todo) { todo.list.update({name: 'List A'}, function(err, list) { should.not.exist(err); should.exist(list); list.name.should.equal('List A'); done(); }); }); }); it('should get related item on scope', function(done) { Item.findById(itemId, function (e, todo) { todo.list(function(err, list) { should.not.exist(err); should.exist(list); list.name.should.equal('List A'); done(); }); }); }); it('should destroy related item on scope', function(done) { Item.findById(itemId, function (e, todo) { todo.list.destroy(function(err) { should.not.exist(err); done(); }); }); }); it('should get related item on scope - verify', function(done) { Item.findById(itemId, function (e, todo) { todo.list(function(err, list) { should.not.exist(err); should.not.exist(list); done(); }); }); }); it('should not have deleted related item', function(done) { List.findById(listId, function (e, list) { should.not.exist(e); should.exist(list); done(); }); }); it('should allow to create belongsTo model in beforeCreate hook', function (done) { var mind; Fear.beforeCreate = function (next) { this.mind.create(function (err, m) { mind = m; if (err) next(err); else next(); }); }; Fear.create(function (err, fear) { should.not.exists(err); should.exists(fear); fear.mindId.should.be.equal(mind.id); should.exists(fear.mind()); done(); }); }); it('should allow to create belongsTo model in beforeCreate hook with promises', function (done) { var mind; Fear.beforeCreate = function (next) { this.mind.create() .then(function (m) { mind = m; next(); }).catch(next); }; Fear.create() .then(function (fear) { should.exists(fear); fear.mindId.should.be.equal(mind.id); should.exists(fear.mind()); done(); }).catch(done); }); }); describe('belongsTo with scope', function () { var Person, Passport; it('can be declared with scope and properties', function (done) { Person = db.define('Person', {name: String, age: Number, passportNotes: String}); Passport = db.define('Passport', {name: String, notes: String}); Passport.belongsTo(Person, { properties: { notes: 'passportNotes' }, scope: { fields: { id: true, name: true } } }); db.automigrate(['Person', 'Passport'], done); }); var personCreated; it('should create record on scope', function (done) { var p = new Passport({ name: 'Passport', notes: 'Some notes...' }); p.person.create({name: 'Fred', age: 36 }, function(err, person) { personCreated = person; p.personId.should.equal(person.id); person.name.should.equal('Fred'); person.passportNotes.should.equal('Some notes...'); p.save(function (err, passport) { should.not.exists(err); done(); }); }); }); it('should find record on scope', function (done) { Passport.findOne(function (err, p) { p.personId.should.eql(personCreated.id); p.person(function(err, person) { person.name.should.equal('Fred'); person.should.have.property('age', undefined); person.should.have.property('passportNotes', undefined); done(); }); }); }); it('should create record on scope with promises', function (done) { var p = new Passport({ name: 'Passport', notes: 'Some notes...' }); p.person.create({name: 'Fred', age: 36 }) .then(function (person) { p.personId.should.equal(person.id); person.name.should.equal('Fred'); person.passportNotes.should.equal('Some notes...'); return p.save() }) .then(function (passport) { done(); }) .catch(done); }); it('should find record on scope with promises', function (done) { Passport.findOne() .then(function (p) { p.personId.should.eql(personCreated.id); return p.person.getAsync() }) .then(function (person) { person.name.should.equal('Fred'); person.should.have.property('age', undefined); person.should.have.property('passportNotes', undefined); done(); }) .catch(done); }); }); // Disable the tests until the issue in // https://github.com/strongloop/loopback-datasource-juggler/pull/399 // is fixed describe.skip('belongsTo with embed', function () { var Person, Passport; it('can be declared with embed and properties', function (done) { Person = db.define('Person', {name: String, age: Number}); Passport = db.define('Passport', {name: String, notes: String}); Passport.belongsTo(Person, { properties: ['name'], options: { embedsProperties: true, invertProperties: true } }); db.automigrate(['Person', 'Passport'], done); }); it('should create record with embedded data', function (done) { Person.create({name: 'Fred', age: 36 }, function(err, person) { var p = new Passport({ name: 'Passport', notes: 'Some notes...' }); p.person(person); p.personId.should.equal(person.id); var data = p.toObject(true); data.person.id.should.equal(person.id); data.person.name.should.equal('Fred'); p.save(function (err) { should.not.exists(err); done(); }); }); }); it('should find record with embedded data', function (done) { Passport.findOne(function (err, p) { should.not.exists(err); var data = p.toObject(true); data.person.id.should.equal(p.personId); data.person.name.should.equal('Fred'); done(); }); }); it('should find record with embedded data with promises', function (done) { Passport.findOne() .then(function (p) { var data = p.toObject(true); data.person.id.should.equal(p.personId); data.person.name.should.equal('Fred'); done(); }).catch(done); }); }); describe('hasOne', function () { var Supplier, Account; var supplierId, accountId; before(function () { // db = getSchema(); Supplier = db.define('Supplier', {name: String}); Account = db.define('Account', {accountNo: String, supplierName: String}); }); it('can be declared using hasOne method', function () { Supplier.hasOne(Account, { properties: { name: 'supplierName' }, methods: { check: function() { return true; } } }); Object.keys((new Account()).toObject()).should.containEql('supplierId'); (new Supplier()).account.should.be.an.instanceOf(Function); }); it('should setup a custom method on accessor', function() { var rel = Supplier.relations['account']; rel.defineMethod('other', function() { return true; }) }); it('should have setup a custom method on accessor', function() { var s = new Supplier(); s.account.check.should.be.a.function; s.account.check().should.be.true; s.account.other.should.be.a.function; s.account.other().should.be.true; }); it('can be used to query data', function (done) { db.automigrate(['Supplier', 'Account'], function () { Supplier.create({name: 'Supplier 1'}, function (e, supplier) { supplierId = supplier.id; should.not.exist(e); should.exist(supplier); supplier.account.create({accountNo: 'a01'}, function (err, account) { supplier.account(function (e, act) { accountId = act.id; should.not.exist(e); should.exist(act); act.should.be.an.instanceOf(Account); supplier.account().id.should.equal(act.id); act.supplierName.should.equal(supplier.name); done(); }); }); }); }); }); it('can be used to query data with getAsync with callback', function (done) { db.automigrate(['Supplier', 'Account'], function () { Supplier.create({name: 'Supplier 1'}, function (e, supplier) { supplierId = supplier.id; should.not.exist(e); should.exist(supplier); supplier.account.create({accountNo: 'a01'}, function (err, account) { supplier.account.getAsync(function (e, act) { accountId = act.id; should.not.exist(e); should.exist(act); act.should.be.an.instanceOf(Account); supplier.account().id.should.equal(act.id); act.supplierName.should.equal(supplier.name); done(); }); }); }); }); }); it('can be used to query data with promises', function (done) { db.automigrate(['Supplier', 'Account'], function () { Supplier.create({name: 'Supplier 1'}) .then(function (supplier) { supplierId = supplier.id; should.exist(supplier); return supplier.account.create({accountNo: 'a01'}) .then(function (account) { return supplier.account.getAsync() }) .then(function (act) { accountId = act.id; should.exist(act); act.should.be.an.instanceOf(Account); supplier.account().id.should.equal(act.id); act.supplierName.should.equal(supplier.name); done(); }) }) .catch(done); }); }); it('should set targetClass on scope property', function() { should.equal(Supplier.prototype.account._targetClass, 'Account'); }); it('should update the related item on scope', function(done) { Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); supplier.account.update({supplierName: 'Supplier A'}, function(err, act) { should.not.exist(e); act.supplierName.should.equal('Supplier A'); done(); }); }); }); it('should update the related item on scope with promises', function(done) { Supplier.findById(supplierId) .then(function(supplier) { should.exist(supplier); return supplier.account.update({supplierName: 'Supplier B'}) }) .then(function(act) { act.supplierName.should.equal('Supplier B'); done(); }) .catch(done); }); it('should ignore the foreign key in the update', function(done) { Supplier.create({name: 'Supplier 2'}, function (e, supplier) { var sid = supplier.id; Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); supplier.account.update({supplierName: 'Supplier A', supplierId: sid}, function(err, act) { should.not.exist(e); act.supplierName.should.equal('Supplier A'); act.supplierId.should.eql(supplierId); done(); }); }); }); }); it('should get the related item on scope', function(done) { Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); supplier.account(function(err, act) { should.not.exist(e); should.exist(act); act.supplierName.should.equal('Supplier A'); done(); }); }); }); it('should get the related item on scope with promises', function(done) { Supplier.findById(supplierId) .then(function(supplier) { should.exist(supplier); return supplier.account.getAsync() }) .then(function (act) { should.exist(act); act.supplierName.should.equal('Supplier A'); done(); }) .catch(done); }); it('should destroy the related item on scope', function(done) { Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); supplier.account.destroy(function(err) { should.not.exist(e); done(); }); }); }); it('should destroy the related item on scope with promises', function(done) { Supplier.findById(supplierId) .then(function (supplier) { should.exist(supplier); return supplier.account.create({accountNo: 'a01'}) .then(function (account) { return supplier.account.destroy() }) .then(function (err) { done(); }); }) .catch(done); }); it('should get the related item on scope - verify', function(done) { Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); supplier.account(function(err, act) { should.not.exist(e); should.not.exist(act); done(); }); }); }); it('should get the related item on scope with promises - verify', function(done) { Supplier.findById(supplierId) .then(function(supplier) { should.exist(supplier); return supplier.account.getAsync() }) .then(function(act) { should.not.exist(act); done(); }) .catch(done); }); it('should have deleted related item', function(done) { Supplier.findById(supplierId, function (e, supplier) { should.not.exist(e); should.exist(supplier); done(); }); }); }); describe('hasOne with scope', function () { var Supplier, Account; var supplierId, accountId; before(function () { // db = getSchema(); Supplier = db.define('Supplier', {name: String}); Account = db.define('Account', {accountNo: String, supplierName: String, block: Boolean}); Supplier.hasOne(Account, { scope: { where: { block: false } }, properties: { name: 'supplierName' } }); }); it('can be used to query data', function (done) { db.automigrate(['Supplier', 'Account'], function () { Supplier.create({name: 'Supplier 1'}, function (e, supplier) { supplierId = supplier.id; should.not.exist(e); should.exist(supplier); supplier.account.create({accountNo: 'a01', block: false}, function (err, account) { supplier.account(function (e, act) { accountId = act.id; should.not.exist(e); should.exist(act); act.should.be.an.instanceOf(Account); should.exist(act.block); act.block.should.be.false; supplier.account().id.should.equal(act.id); act.supplierName.should.equal(supplier.name); done(); }); }); }); }); }); it('should include record that matches scope', function(done) { Supplier.findById(supplierId, {include: 'account'}, function(err, supplier) { should.exists(supplier.toJSON().account); supplier.account(function(err, account) { should.exists(account); done(); }); }); }); it('should not find record that does not match scope', function (done) { Account.updateAll({ block: true }, function (err) { Supplier.findById(supplierId, function (err, supplier) { supplier.account(function (err, account) { should.not.exists(account); done(); }); }); }); }); it('should not include record that does not match scope', function (done) { Account.updateAll({ block: true }, function (err) { Supplier.findById(supplierId, {include: 'account'}, function (err, supplier) { should.not.exists(supplier.toJSON().account); supplier.account(function (err, account) { should.not.exists(account); done(); }); }); }); }); it('can be used to query data with promises', function (done) { db.automigrate(['Supplier', 'Account'], function () { Supplier.create({name: 'Supplier 1'}) .then(function (supplier) { supplierId = supplier.id; should.exist(supplier); return supplier.account.create({accountNo: 'a01', block: false}) .then(function (account) { return supplier.account.getAsync() }) .then(function (act) { accountId = act.id; should.exist(act); act.should.be.an.instanceOf(Account); should.exist(act.block); act.block.should.be.false; supplier.account().id.should.equal(act.id); act.supplierName.should.equal(supplier.name); done(); }); }) .catch(done); }); }); it('should find record that match scope with promises', function (done) { Account.updateAll({ block: true }) .then(function () { return Supplier.findById(supplierId) }) .then(function (supplier) { return supplier.account.getAsync() }) .then(function (account) { should.not.exist(account); done(); }) .catch(done); }); }); describe('hasOne with non standard id', function () { var Supplier, Account; var supplierId, accountId; before(function () { // db = getSchema(); Supplier = db.define('Supplier', { sid: { type: String, id: true, generated: true }, name: String }); Account = db.define('Account', { accid: { type: String, id: true, generated: false }, supplierName: String }); }); it('can be declared with non standard foreignKey', function () { Supplier.hasOne(Account, { properties: {name: 'supplierName'}, foreignKey: 'sid' }); Object.keys((new Account()).toObject()).should.containEql('sid'); (new Supplier()).account.should.be.an.instanceOf(Function); }); it('can be used to query data', function (done) { db.automigrate(['Supplier', 'Account'], function () { Supplier.create({name: 'Supplier 1'}, function (e, supplier) { supplierId = supplier.sid; should.not.exist(e); should.exist(supplier); supplier.account.create({accid: 'a01'}, function (err, account) { supplier.account(function (e, act) { accountId = act.accid; should.not.exist(e); should.exist(act); act.should.be.an.instanceOf(Account); supplier.account().accid.should.equal(act.accid); act.supplierName.should.equal(supplier.name); done(); }); }); }); }); }); it('should destroy the related item on scope', function(done) { Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); supplier.account.destroy(function(err) { should.not.exist(e); done(); }); }); }); it('should get the related item on scope - verify', function(done) { Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); supplier.account(function(err, act) { should.not.exist(e); should.not.exist(act); done(); }); }); }); it('should have deleted related item', function(done) { Supplier.findById(supplierId, function (e, supplier) { should.not.exist(e); should.exist(supplier); done(); }); }); }); describe('hasAndBelongsToMany', function () { var Article, TagName, ArticleTag; it('can be declared', function (done) { Article = db.define('Article', {title: String}); TagName = db.define('TagName', {name: String, flag: String}); Article.hasAndBelongsToMany('tagNames'); ArticleTag = db.models.ArticleTagName; db.automigrate(['Article', 'TagName', 'ArticleTagName'], done); }); it('should allow to create instances on scope', function (done) { Article.create(function (e, article) { article.tagNames.create({name: 'popular'}, function (e, t) { t.should.be.an.instanceOf(TagName); ArticleTag.findOne(function (e, at) { should.exist(at); at.tagNameId.toString().should.equal(t.id.toString()); at.articleId.toString().should.equal(article.id.toString()); done(); }); }); }); }); it('should allow to fetch scoped instances', function (done) { Article.findOne(function (e, article) { article.tagNames(function (e, tags) { should.not.exist(e); should.exist(tags); article.tagNames().should.eql(tags); done(); }); }); }); it('should allow to add connection with instance', function (done) { Article.findOne(function (e, article) { TagName.create({name: 'awesome'}, function (e, tag) { article.tagNames.add(tag, function (e, at) { should.not.exist(e); should.exist(at); at.should.be.an.instanceOf(ArticleTag); at.tagNameId.should.equal(tag.id); at.articleId.should.equal(article.id); done(); }); }); }); }); it('should allow to remove connection with instance', function (done) { Article.findOne(function (e, article) { article.tagNames(function (e, tags) { var len = tags.length; tags.should.not.be.empty; article.tagNames.remove(tags[0], function (e) { should.not.exist(e); article.tagNames(true, function (e, tags) { tags.should.have.lengthOf(len - 1); done(); }); }); }); }); }); it('should allow to create instances on scope with promises', function (done) { db.automigrate(['Article', 'TagName', 'ArticleTagName'], function () { Article.create() .then(function (article) { return article.tagNames.create({name: 'popular'}) .then(function (t) { t.should.be.an.instanceOf(TagName); return ArticleTag.findOne() .then(function (at) { should.exist(at); at.tagNameId.toString().should.equal(t.id.toString()); at.articleId.toString().should.equal(article.id.toString()); done(); }); }); }).catch(done); }); }); it('should allow to fetch scoped instances with promises', function (done) { Article.findOne() .then(function (article) { return article.tagNames.getAsync() .then(function (tags) { should.exist(tags); article.tagNames().should.eql(tags); done(); }); }).catch(done); }); it('should allow to add connection with instance with promises', function (done) { Article.findOne() .then(function (article) { return TagName.create({name: 'awesome'}) .then(function (tag) { return article.tagNames.add(tag) .then(function (at) { should.exist(at); at.should.be.an.instanceOf(ArticleTag); at.tagNameId.should.equal(tag.id); at.articleId.should.equal(article.id); done(); }); }) }) .catch(done); }); it('should allow to remove connection with instance with promises', function (done) { Article.findOne() .then(function (article) { return article.tagNames.getAsync() .then(function (tags) { var len = tags.length; tags.should.not.be.empty; return article.tagNames.remove(tags[0]) .then(function () { return article.tagNames.getAsync() }) .then(function (tags) { tags.should.have.lengthOf(len - 1); done(); }); }); }) .catch(done); }); it('should set targetClass on scope property', function() { should.equal(Article.prototype.tagNames._targetClass, 'TagName'); }); it('should apply inclusion fields to the target model', function(done) { Article.create({title: 'a1'}, function (e, article) { should.not.exist(e); article.tagNames.create({name: 't1', flag: '1'}, function(e, t) { should.not.exist(e); Article.find({ where: {id: article.id}, include: {relation: 'tagNames', scope: {fields: ['name']}}}, function(e, articles) { should.not.exist(e); articles.should.have.property('length', 1); var a = articles[0].toJSON(); a.should.have.property('title', 'a1'); a.should.have.property('tagNames'); a.tagNames.should.have.property('length', 1); var n = a.tagNames[0]; n.should.have.property('name', 't1'); n.should.have.property('flag', undefined); n.id.should.eql(t.id); done(); }); }); }); }); it('should apply inclusion where to the target model', function(done) { Article.create({title: 'a2'}, function (e, article) { should.not.exist(e); article.tagNames.create({name: 't2', flag: '2'}, function(e, t2) { should.not.exist(e); article.tagNames.create({name: 't3', flag: '3'}, function(e, t3) { Article.find({ where: {id: article.id}, include: {relation: 'tagNames', scope: {where: {flag: '2'}}}}, function(e, articles) { should.not.exist(e); articles.should.have.property('length', 1); var a = articles[0].toJSON(); a.should.have.property('title', 'a2'); a.should.have.property('tagNames'); a.tagNames.should.have.property('length', 1); var n = a.tagNames[0]; n.should.have.property('name', 't2'); n.should.have.property('flag', '2'); n.id.should.eql(t2.id); done(); }); }); }); }); }); }); describe('embedsOne', function () { var person; var Passport; var Other; before(function () { tmp = getTransientDataSource(); // db = getSchema(); Person = db.define('Person', {name: String}); Passport = tmp.define('Passport', {name:{type:'string', required: true}}, {idInjection: false} ); Address = tmp.define('Address', { street: String }, { idInjection: false }); Other = db.define('Other', {name: String}); }); it('can be declared using embedsOne method', function (done) { Person.embedsOne(Passport, { default: {name: 'Anonymous'}, // a bit contrived methods: { check: function() { return true; } } }); Person.embedsOne(Address); // all by default db.automigrate(['Person'], done); }); it('should have setup a property and accessor', function() { var p = new Person(); p.passport.should.be.an.object; // because of default p.passportItem.should.be.a.function; p.passportItem.create.should.be.a.function; p.passportItem.build.should.be.a.function; p.passportItem.destroy.should.be.a.function; }); it('should setup a custom method on accessor', function() { var rel = Person.relations['passportItem']; rel.defineMethod('other', function() { return true; }) }); it('should have setup a custom method on accessor', function() { var p = new Person(); p.passportItem.check.should.be.a.function; p.passportItem.check().should.be.true; p.passportItem.other.should.be.a.function; p.passportItem.other().should.be.true; }); it('should behave properly without default or being set', function (done) { var p = new Person(); should.not.exist(p.address); var a = p.addressItem(); should.not.exist(a); Person.create({}, function (err, p) { should.not.exist(p.address); var a = p.addressItem(); should.not.exist(a); done(); }); }); it('should return an instance with default values', function() { var p = new Person(); p.passport.toObject().should.eql({name: 'Anonymous'}); p.passportItem().should.equal(p.passport); p.passportItem(function(err, passport) { should.not.exist(err); passport.should.equal(p.passport); }); }); it('should embed a model instance', function() { var p = new Person(); p.passportItem(new Passport({name: 'Fred'})); p.passport.toObject().should.eql({name: 'Fred'}); p.passport.should.be.an.instanceOf(Passport); }); it('should not embed an invalid model type', function() { var p = new Person(); p.passportItem(new Other()); p.passport.toObject().should.eql({name: 'Anonymous'}); p.passport.should.be.an.instanceOf(Passport); }); var personId; it('should create an embedded item on scope', function(done) { Person.create({name: 'Fred'}, function(err, p) { should.not.exist(err); personId = p.id; p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); p.passport.toObject().should.eql({name: 'Fredric'}); p.passport.should.be.an.instanceOf(Passport); done(); }); }); }); it('should get an embedded item on scope', function(done) { Person.findById(personId, function(err, p) { should.not.exist(err); var passport = p.passportItem(); passport.toObject().should.eql({name: 'Fredric'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); passport.should.equal(p.passportItem.value()); done(); }); }); it('should validate an embedded item on scope - on creation', function(done) { var p = new Person({name: 'Fred'}); p.passportItem.create({}, function(err, passport) { should.exist(err); err.name.should.equal('ValidationError'); err.details.messages.name.should.eql(['can\'t be blank']); done(); }); }); it('should validate an embedded item on scope - on update', function(done) { Person.findById(personId, function(err, p) { var passport = p.passportItem(); passport.name = null; p.save(function(err) { should.exist(err); err.name.should.equal('ValidationError'); err.details.messages.passportItem .should.eql(['is invalid: `name` can\'t be blank']); done(); }); }); }); it('should update an embedded item on scope', function(done) { Person.findById(personId, function(err, p) { p.passportItem.update({name: 'Freddy'}, function(err, passport) { should.not.exist(err); var passport = p.passportItem(); passport.toObject().should.eql({name: 'Freddy'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); done(); }); }); }); it('should get an embedded item on scope - verify', function(done) { Person.findById(personId, function(err, p) { should.not.exist(err); var passport = p.passportItem(); passport.toObject().should.eql({name: 'Freddy'}); done(); }); }); it('should destroy an embedded item on scope', function(done) { Person.findById(personId, function(err, p) { p.passportItem.destroy(function(err) { should.not.exist(err); should.equal(p.passport, null); done(); }); }); }); it('should get an embedded item on scope - verify', function(done) { Person.findById(personId, function(err, p) { should.not.exist(err); should.equal(p.passport, null); done(); }); }); it('should save an unsaved model', function(done) { var p = new Person({name: 'Fred'}); p.isNewRecord().should.be.true; p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); p.passport.should.equal(passport); p.isNewRecord().should.be.false; done(); }); }); it('should create an embedded item on scope with promises', function(done) { Person.create({name: 'Fred'}) .then(function(p) { personId = p.id; p.passportItem.create({name: 'Fredric'}) .then(function(passport) { p.passport.toObject().should.eql({name: 'Fredric'}); p.passport.should.be.an.instanceOf(Passport); done(); }); }).catch(done); }); it('should get an embedded item on scope with promises', function(done) { Person.findById(personId) .then(function(p) { var passport = p.passportItem(); passport.toObject().should.eql({name: 'Fredric'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); passport.should.equal(p.passportItem.value()); done(); }).catch(done); }); it('should validate an embedded item on scope with promises - on creation', function(done) { var p = new Person({name: 'Fred'}); p.passportItem.create({}) .then(function(passport) { should.not.exist(passport); done(); }) .catch(function (err) { should.exist(err); err.name.should.equal('ValidationError'); err.details.messages.name.should.eql(['can\'t be blank']); done(); }).catch(done); }); it('should validate an embedded item on scope with promises - on update', function(done) { Person.findById(personId) .then(function(p) { var passport = p.passportItem(); passport.name = null; return p.save() .then(function (p) { should.not.exist(p); done(); }) .catch(function(err) { should.exist(err); err.name.should.equal('ValidationError'); err.details.messages.passportItem .should.eql(['is invalid: `name` can\'t be blank']); done(); }); }).catch(done); }); it('should update an embedded item on scope with promises', function(done) { Person.findById(personId) .then(function (p) { return p.passportItem.update({name: 'Jason'}) .then(function(passport) { var passport = p.passportItem(); passport.toObject().should.eql({name: 'Jason'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); done(); }); }).catch(done); }); it('should get an embedded item on scope with promises - verify', function(done) { Person.findById(personId) .then(function(p) { var passport = p.passportItem(); passport.toObject().should.eql({name: 'Jason'}); done(); }).catch(done); }); it('should destroy an embedded item on scope with promises', function(done) { Person.findById(personId) .then(function(p) { return p.passportItem.destroy() .then(function() { should.equal(p.passport, null); done(); }); }).catch(done); }); it('should get an embedded item on scope with promises - verify', function(done) { Person.findById(personId) .then(function(p) { should.equal(p.passport, null); done(); }).catch(done); }); }); describe('embedsOne - persisted model', function () { // This test spefically uses the Memory connector // in order to test the use of the auto-generated // id, in the sequence of the related model. before(function () { db = getMemoryDataSource(); Person = db.define('Person', {name: String}); Passport = db.define('Passport', {name:{type:'string', required: true}} ); }); it('can be declared using embedsOne method', function (done) { Person.embedsOne(Passport, { options: {persistent: true} }); db.automigrate(['Person', 'Passport'], done); }); it('should create an item - to offset id', function(done) { Passport.create({name:'Wilma'}, function(err, p) { should.not.exist(err); p.id.should.equal(1); p.name.should.equal('Wilma'); done(); }); }); it('should create an embedded item on scope', function(done) { Person.create({name: 'Fred'}, function(err, p) { should.not.exist(err); p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); p.passport.id.should.eql(2); p.passport.name.should.equal('Fredric'); done(); }); }); }); it('should create an embedded item on scope with promises', function(done) { Person.create({name: 'Barney'}) .then(function(p) { return p.passportItem.create({name: 'Barnabus'}) .then(function(passport) { p.passport.id.should.eql(3); p.passport.name.should.equal('Barnabus'); done(); }); }).catch(done); }); }); describe('embedsOne - generated id', function () { before(function () { tmp = getTransientDataSource(); // db = getSchema(); Person = db.define('Person', {name: String}); Passport = tmp.define('Passport', {id: {type:'string', id: true, generated:true}}, {name: {type:'string', required: true}} ); }); it('can be declared using embedsOne method', function (done) { Person.embedsOne(Passport); db.automigrate(['Person'], done); }); it('should create an embedded item on scope', function(done) { Person.create({name: 'Fred'}, function(err, p) { should.not.exist(err); p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); passport.id.should.match(/^[0-9a-fA-F]{24}$/); p.passport.name.should.equal('Fredric'); done(); }); }); }); }); describe('embedsMany', function () { var address1, address2; before(function (done) { tmp = getTransientDataSource({defaultIdType: Number}); // db = getSchema(); Person = db.define('Person', {name: String}); Address = tmp.define('Address', {street: String}); Address.validatesPresenceOf('street'); db.automigrate(['Person'], done); }); it('can be declared', function (done) { Person.embedsMany(Address); db.automigrate(['Person'], done); }); it('should have setup embedded accessor/scope', function() { var p = new Person({ name: 'Fred' }); p.addresses.should.be.an.array; p.addresses.should.have.length(0); p.addressList.should.be.a.function; p.addressList.findById.should.be.a.function; p.addressList.updateById.should.be.a.function; p.addressList.destroy.should.be.a.function; p.addressList.exists.should.be.a.function; p.addressList.create.should.be.a.function; p.addressList.build.should.be.a.function; }); it('should create embedded items on scope', function(done) { Person.create({ name: 'Fred' }, function(err, p) { p.addressList.create({ street: 'Street 1' }, function(err, address) { should.not.exist(err); address1 = address; should.exist(address1.id); address1.street.should.equal('Street 1'); done(); }); }); }); it('should create embedded items on scope', function(done) { Person.findOne(function(err, p) { p.addressList.create({ street: 'Street 2' }, function(err, address) { should.not.exist(err); address2 = address; should.exist(address2.id); address2.street.should.equal('Street 2'); done(); }); }); }); it('should return embedded items from scope', function(done) { Person.findOne(function(err, p) { p.addressList(function(err, addresses) { should.not.exist(err); var list = p.addressList(); list.should.equal(addresses); list.should.equal(p.addresses); p.addressList.value().should.equal(list); addresses.should.have.length(2); addresses[0].id.should.eql(address1.id); addresses[0].street.should.equal('Street 1'); addresses[1].id.should.eql(address2.id); addresses[1].street.should.equal('Street 2'); done(); }); }); }); it('should filter embedded items on scope', function(done) { Person.findOne(function(err, p) { p.addressList({ where: { street: 'Street 2' } }, function(err, addresses) { should.not.exist(err); addresses.should.have.length(1); addresses[0].id.should.eql(address2.id); addresses[0].street.should.equal('Street 2'); done(); }); }); }); it('should validate embedded items', function(done) { Person.findOne(function(err, p) { p.addressList.create({}, function(err, address) { should.exist(err); should.not.exist(address); err.name.should.equal('ValidationError'); err.details.codes.street.should.eql(['presence']); done(); }); }); }); it('should find embedded items by id', function(done) { Person.findOne(function(err, p) { p.addressList.findById(address2.id, function(err, address) { address.should.be.instanceof(Address); address.id.should.eql(address2.id); address.street.should.equal('Street 2'); done(); }); }); }); it('should check if item exists', function(done) { Person.findOne(function(err, p) { p.addressList.exists(address2.id, function(err, exists) { should.not.exist(err); exists.should.be.true; done(); }); }); }); it('should update embedded items by id', function(done) { Person.findOne(function(err, p) { p.addressList.updateById(address2.id, { street: 'New Street' }, function(err, address) { address.should.be.instanceof(Address); address.id.should.eql(address2.id); address.street.should.equal('New Street'); done(); }); }); }); it('should validate the update of embedded items', function(done) { Person.findOne(function(err, p) { p.addressList.updateById(address2.id, { street: null }, function(err, address) { err.name.should.equal('ValidationError'); err.details.codes.street.should.eql(['presence']); done(); }); }); }); it('should find embedded items by id - verify', function(done) { Person.findOne(function(err, p) { p.addressList.findById(address2.id, function(err, address) { address.should.be.instanceof(Address); address.id.should.eql(address2.id); address.street.should.equal('New Street'); done(); }); }); }); it('should have accessors: at, get, set', function(done) { Person.findOne(function(err, p) { p.addressList.at(0).id.should.equal(address1.id); p.addressList.get(address1.id).id.should.equal(address1.id); p.addressList.set(address1.id, { street: 'Changed 1' }); p.addresses[0].street.should.equal('Changed 1'); p.addressList.at(1).id.should.equal(address2.id); p.addressList.get(address2.id).id.should.equal(address2.id); p.addressList.set(address2.id, { street: 'Changed 2' }); p.addresses[1].street.should.equal('Changed 2'); done(); }); }); it('should remove embedded items by id', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(2); p.addressList.destroy(address1.id, function(err) { should.not.exist(err); p.addresses.should.have.length(1); done(); }); }); }); it('should have removed embedded items - verify', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(1); done(); }); }); it('should create embedded items on scope', function(done) { Person.findOne(function(err, p) { p.addressList.create({ street: 'Street 3' }, function(err, address) { should.not.exist(err); address.street.should.equal('Street 3'); done(); }); }); }); it('should remove embedded items - filtered', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(2); p.addressList.destroyAll({ street: 'Street 3' }, function(err) { should.not.exist(err); p.addresses.should.have.length(1); done(); }); }); }); it('should remove all embedded items', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(1); p.addressList.destroyAll(function(err) { should.not.exist(err); p.addresses.should.have.length(0); done(); }); }); }); it('should have removed all embedded items - verify', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(0); done(); }); }); it('should save an unsaved model', function(done) { var p = new Person({name: 'Fred'}); p.isNewRecord().should.be.true; p.addressList.create({ street: 'Street 4' }, function(err, address) { should.not.exist(err); address.street.should.equal('Street 4'); p.isNewRecord().should.be.false; done(); }); }); }); describe('embedsMany - numeric ids + forceId', function () { before(function (done) { tmp = getTransientDataSource(); // db = getSchema(); Person = db.define('Person', {name: String}); Address = tmp.define('Address', { id: {type: Number, id:true}, street: String }); db.automigrate(['Person'], done); }); it('can be declared', function (done) { Person.embedsMany(Address, {options: {forceId: true}}); db.automigrate(['Person'], done); }); it('should create embedded items on scope', function(done) { Person.create({ name: 'Fred' }, function(err, p) { p.addressList.create({ street: 'Street 1' }, function(err, address) { should.not.exist(err); address.id.should.equal(1); p.addressList.create({ street: 'Street 2' }, function(err, address) { address.id.should.equal(2); p.addressList.create({ id: 12345, street: 'Street 3' }, function(err, address) { address.id.should.equal(3); done(); }); }); }); }); }); }); describe('embedsMany - explicit ids', function () { before(function (done) { tmp = getTransientDataSource(); // db = getSchema(); Person = db.define('Person', {name: String}); Address = tmp.define('Address', {street: String}); Address.validatesPresenceOf('street'); db.automigrate(['Person'], done); }); it('can be declared', function (done) { Person.embedsMany(Address); db.automigrate(['Person'], done); }); it('should create embedded items on scope', function(done) { Person.create({ name: 'Fred' }, function(err, p) { p.addressList.create({ id: 'home', street: 'Street 1' }, function(err, address) { should.not.exist(err); p.addressList.create({ id: 'work', street: 'Work Street 2' }, function(err, address) { should.not.exist(err); address.id.should.equal('work'); address.street.should.equal('Work Street 2'); done(); }); }); }); }); it('should find embedded items by id', function(done) { Person.findOne(function(err, p) { p.addressList.findById('work', function(err, address) { address.should.be.instanceof(Address); address.id.should.equal('work'); address.street.should.equal('Work Street 2'); done(); }); }); }); it('should check for duplicate ids', function(done) { Person.findOne(function(err, p) { p.addressList.create({ id: 'home', street: 'Invalid' }, function(err, addresses) { should.exist(err); err.name.should.equal('ValidationError'); err.details.codes.addresses.should.eql(['uniqueness']); done(); }); }); }); it('should update embedded items by id', function(done) { Person.findOne(function(err, p) { p.addressList.updateById('home', { street: 'New Street' }, function(err, address) { address.should.be.instanceof(Address); address.id.should.equal('home'); address.street.should.equal('New Street'); done(); }); }); }); it('should remove embedded items by id', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(2); p.addressList.destroy('home', function(err) { should.not.exist(err); p.addresses.should.have.length(1); done(); }); }); }); it('should have embedded items - verify', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(1); done(); }); }); it('should validate all embedded items', function(done) { var addresses = []; addresses.push({ id: 'home', street: 'Home Street' }); addresses.push({ id: 'work', street: '' }); Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) { err.name.should.equal('ValidationError'); err.details.messages.addresses.should.eql([ 'contains invalid item: `work` (`street` can\'t be blank)' ]); done(); }); }); it('should build embedded items', function(done) { Person.create({ name: 'Wilma' }, function(err, p) { p.addressList.build({ id: 'home', street: 'Home' }); p.addressList.build({ id: 'work', street: 'Work' }); p.addresses.should.have.length(2); p.save(function(err, p) { done(); }); }); }); it('should have embedded items - verify', function(done) { Person.findOne({ where: { name: 'Wilma' } }, function(err, p) { p.name.should.equal('Wilma'); p.addresses.should.have.length(2); p.addresses[0].id.should.equal('home'); p.addresses[0].street.should.equal('Home'); p.addresses[1].id.should.equal('work'); p.addresses[1].street.should.equal('Work'); done(); }); }); it('should have accessors: at, get, set', function(done) { Person.findOne({ where: { name: 'Wilma' } }, function(err, p) { p.name.should.equal('Wilma'); p.addresses.should.have.length(2); p.addressList.at(0).id.should.equal('home'); p.addressList.get('home').id.should.equal('home'); p.addressList.set('home', { id: 'den' }).id.should.equal('den'); p.addressList.at(1).id.should.equal('work'); p.addressList.get('work').id.should.equal('work'); p.addressList.set('work', { id: 'factory' }).id.should.equal('factory'); done(); }); }); it('should create embedded from attributes - property name', function(done) { var addresses = [ {id: 'home', street: 'Home Street'}, {id: 'work', street: 'Work Street'} ]; Person.create({name: 'Wilma', addresses: addresses}, function(err, p) { should.not.exist(err); p.addressList.at(0).id.should.equal('home'); p.addressList.at(1).id.should.equal('work'); done(); }); }); it('should not create embedded from attributes - relation name', function(done) { var addresses = [ {id: 'home', street: 'Home Street'}, {id: 'work', street: 'Work Street'} ]; Person.create({name: 'Wilma', addressList: addresses}, function(err, p) { should.not.exist(err); p.addresses.should.have.length(0); done(); }); }); it('should create embedded items with auto-generated id', function(done) { Person.create({ name: 'Wilma' }, function(err, p) { p.addressList.create({ street: 'Home Street 1' }, function(err, address) { should.not.exist(err); address.id.should.match(/^[0-9a-fA-F]{24}$/); address.street.should.equal('Home Street 1'); done(); }); }); }); }); describe('embedsMany - persisted model', function () { var address0, address1, address2; var person; // This test spefically uses the Memory connector // in order to test the use of the auto-generated // id, in the sequence of the related model. before(function (done) { db = getMemoryDataSource(); Person = db.define('Person', {name: String}); Address = db.define('Address', {street: String}); Address.validatesPresenceOf('street'); db.automigrate(['Person', 'Address'], done); }); it('can be declared', function (done) { // to save related model itself, set // persistent: true Person.embedsMany(Address, { scope: {order: 'street'}, options: {persistent: true} }); db.automigrate(['Person', 'Address'], done); }); it('should create individual items (0)', function(done) { Address.create({ street: 'Street 0' }, function(err, inst) { inst.id.should.equal(1); // offset sequence address0 = inst; done(); }); }); it('should create individual items (1)', function(done) { Address.create({ street: 'Street 1' }, function(err, inst) { inst.id.should.equal(2); address1 = inst; done(); }); }); it('should create individual items (2)', function(done) { Address.create({ street: 'Street 2' }, function(err, inst) { inst.id.should.equal(3); address2 = inst; done(); }); }); it('should create individual items (3)', function(done) { Address.create({ street: 'Street 3' }, function(err, inst) { inst.id.should.equal(4); // offset sequence done(); }); }); it('should add embedded items on scope', function(done) { Person.create({ name: 'Fred' }, function(err, p) { person = p; p.addressList.create(address1.toObject(), function(err, address) { should.not.exist(err); address.id.should.eql(2); address.street.should.equal('Street 1'); p.addressList.create(address2.toObject(), function(err, address) { should.not.exist(err); address.id.should.eql(3); address.street.should.equal('Street 2'); done(); }); }); }); }); it('should create embedded items on scope', function(done) { Person.findById(person.id, function(err, p) { p.addressList.create({ street: 'Street 4' }, function(err, address) { should.not.exist(err); address.id.should.equal(5); // in Address sequence, correct offset address.street.should.equal('Street 4'); done(); }); }); }); it('should have embedded items on scope', function(done) { Person.findById(person.id, function(err, p) { p.addressList(function(err, addresses) { should.not.exist(err); addresses.should.have.length(3); addresses[0].street.should.equal('Street 1'); addresses[1].street.should.equal('Street 2'); addresses[2].street.should.equal('Street 4'); done(); }); }); }); it('should validate embedded items on scope - id', function(done) { Person.create({ name: 'Wilma' }, function(err, p) { p.addressList.create({ id: null, street: 'Street 1' }, function(err, address) { should.not.exist(err); address.street.should.equal('Street 1'); done(); }); }); }); it('should validate embedded items on scope - street', function(done) { Person.create({ name: 'Wilma' }, function(err, p) { p.addressList.create({ id: 1234 }, function(err, address) { should.exist(err); err.name.should.equal('ValidationError'); err.details.codes.street.should.eql(['presence']); var expected = 'The `Address` instance is not valid. '; expected += 'Details: `street` can\'t be blank (value: undefined).'; err.message.should.equal(expected); done(); }); }); }); }); describe('embedsMany - relations, scope and properties', function () { var category, job1, job2, job3; before(function () { // db = getSchema(); Category = db.define('Category', {name: String}); Job = db.define('Job', {name: String}); Link = db.define('Link', {name: String, notes: String}); }); it('can be declared', function (done) { Category.embedsMany(Link, { as: 'items', // rename scope: { include: 'job' }, // always include options: { belongsTo: 'job' } // optional, for add()/remove() }); Link.belongsTo(Job, { foreignKey: 'id', // re-use the actual job id properties: { id: 'id', name: 'name' }, // denormalize, transfer id options: { invertProperties: true } }); db.automigrate(['Category', 'Job', 'Link'], function() { Job.create({ name: 'Job 0' }, done); // offset ids for tests }); }); it('should setup related items', function(done) { Job.create({ name: 'Job 1' }, function(err, p) { job1 = p; Job.create({ name: 'Job 2' }, function(err, p) { job2 = p; Job.create({ name: 'Job 3' }, function(err, p) { job3 = p; done(); }); }); }); }); it('should associate items on scope', function(done) { Category.create({ name: 'Category A' }, function(err, cat) { var link = cat.items.build(); link.job(job1); var link = cat.items.build(); link.job(job2); cat.save(function(err, cat) { var job = cat.items.at(0); job.should.be.instanceof(Link); job.should.not.have.property('jobId'); job.id.should.eql(job1.id); job.name.should.equal(job1.name); var job = cat.items.at(1); job.id.should.eql(job2.id); job.name.should.equal(job2.name); done(); }); }); }); it('should include related items on scope', function(done) { Category.findOne(function(err, cat) { cat.links.should.have.length(2); // denormalized properties: cat.items.at(0).should.be.instanceof(Link); cat.items.at(0).id.should.eql(job1.id); cat.items.at(0).name.should.equal(job1.name); cat.items.at(1).id.should.eql(job2.id); cat.items.at(1).name.should.equal(job2.name); // lazy-loaded relations should.not.exist(cat.items.at(0).job()); should.not.exist(cat.items.at(1).job()); cat.items(function(err, items) { cat.items.at(0).job().should.be.instanceof(Job); cat.items.at(1).job().should.be.instanceof(Job); cat.items.at(1).job().name.should.equal('Job 2'); done(); }); }); }); it('should remove embedded items by id', function(done) { Category.findOne(function(err, cat) { cat.links.should.have.length(2); cat.items.destroy(job1.id, function(err) { should.not.exist(err); cat.links.should.have.length(1); done(); }); }); }); it('should find items on scope', function(done) { Category.findOne(function(err, cat) { cat.links.should.have.length(1); cat.items.at(0).id.should.eql(job2.id); cat.items.at(0).name.should.equal(job2.name); // lazy-loaded relations should.not.exist(cat.items.at(0).job()); cat.items(function(err, items) { cat.items.at(0).job().should.be.instanceof(Job); cat.items.at(0).job().name.should.equal('Job 2'); done(); }); }); }); it('should add related items to scope', function(done) { Category.findOne(function(err, cat) { cat.links.should.have.length(1); cat.items.add(job3, function(err, link) { link.should.be.instanceof(Link); link.id.should.eql(job3.id); link.name.should.equal('Job 3'); cat.links.should.have.length(2); done(); }); }); }); it('should find items on scope', function(done) { Category.findOne(function(err, cat) { cat.links.should.have.length(2); cat.items.at(0).should.be.instanceof(Link); cat.items.at(0).id.should.eql(job2.id); cat.items.at(0).name.should.equal(job2.name); cat.items.at(1).id.should.eql(job3.id); cat.items.at(1).name.should.equal(job3.name); done(); }); }); it('should remove embedded items by reference id', function(done) { Category.findOne(function(err, cat) { cat.links.should.have.length(2); cat.items.remove(job2.id, function(err) { should.not.exist(err); cat.links.should.have.length(1); done(); }); }); }); it('should have removed embedded items by reference id', function(done) { Category.findOne(function(err, cat) { cat.links.should.have.length(1); done(); }); }); var jobId; it('should create items on scope', function(done) { Category.create({ name: 'Category B' }, function(err, cat) { category = cat; var link = cat.items.build({ notes: 'Some notes...' }); link.job.create({ name: 'Job 1' }, function(err, p) { jobId = p.id; cat.links[0].id.should.eql(p.id); cat.links[0].name.should.equal('Job 1'); // denormalized cat.links[0].notes.should.equal('Some notes...'); cat.items.at(0).should.equal(cat.links[0]); done(); }); }); }); it('should find items on scope', function(done) { Category.findById(category.id, function(err, cat) { cat.name.should.equal('Category B'); cat.links.toObject().should.eql([ {id: jobId, name: 'Job 1', notes: 'Some notes...'} ]); cat.items.at(0).should.equal(cat.links[0]); cat.items(function(err, items) { // alternative access items.should.be.an.array; items.should.have.length(1); items[0].job(function(err, p) { p.name.should.equal('Job 1'); // actual value done(); }); }); }); }); it('should update items on scope - and save parent', function(done) { Category.findById(category.id, function(err, cat) { var link = cat.items.at(0); link.updateAttributes({notes: 'Updated notes...'}, function(err, link) { link.notes.should.equal('Updated notes...'); done(); }); }); }); it('should find items on scope - verify update', function(done) { Category.findById(category.id, function(err, cat) { cat.name.should.equal('Category B'); cat.links.toObject().should.eql([ {id: jobId, name: 'Job 1', notes: 'Updated notes...'} ]); done(); }); }); it('should remove items from scope - and save parent', function(done) { Category.findById(category.id, function(err, cat) { cat.items.at(0).destroy(function(err, link) { cat.links.should.eql([]); done(); }); }); }); it('should find items on scope - verify destroy', function(done) { Category.findById(category.id, function(err, cat) { cat.name.should.equal('Category B'); cat.links.should.eql([]); done(); }); }); }); describe('embedsMany - polymorphic relations', function () { var person1, person2; before(function (done) { // db = getSchema(); tmp = getTransientDataSource(); Book = db.define('Book', {name: String}); Author = db.define('Author', {name: String}); Reader = db.define('Reader', {name: String}); Link = tmp.define('Link', { id: {type: Number, id: true}, name: String, notes: String }); // generic model Link.validatesPresenceOf('linkedId'); Link.validatesPresenceOf('linkedType'); db.automigrate(['Book', 'Author', 'Reader'], done); }); it('can be declared', function (done) { var idType = db.connector.getDefaultIdType(); Book.embedsMany(Link, { as: 'people', polymorphic: 'linked', scope: { include: 'linked' } }); Link.belongsTo('linked', { polymorphic: { idType: idType }, // native type properties: { name: 'name' }, // denormalized options: { invertProperties: true } }); db.automigrate(['Book', 'Author', 'Reader'], done); }); it('should setup related items', function(done) { Author.create({ name: 'Author 1' }, function(err, p) { person1 = p; Reader.create({ name: 'Reader 1' }, function(err, p) { person2 = p; done(); }); }); }); it('should create items on scope', function(done) { Book.create({ name: 'Book' }, function(err, book) { var link = book.people.build({ notes: 'Something ...' }); link.linked(person1); var link = book.people.build(); link.linked(person2); book.save(function(err, book) { should.not.exist(err); var link = book.people.at(0); link.should.be.instanceof(Link); link.id.should.equal(1); link.linkedId.should.eql(person1.id); link.linkedType.should.equal('Author'); link.name.should.equal('Author 1'); var link = book.people.at(1); link.should.be.instanceof(Link); link.id.should.equal(2); link.linkedId.should.eql(person2.id); link.linkedType.should.equal('Reader'); link.name.should.equal('Reader 1'); done(); }); }); }); it('should include related items on scope', function(done) { Book.findOne(function(err, book) { book.links.should.have.length(2); var link = book.people.at(0); link.should.be.instanceof(Link); link.id.should.equal(1); link.linkedId.should.eql(person1.id); link.linkedType.should.equal('Author'); link.notes.should.equal('Something ...'); var link = book.people.at(1); link.should.be.instanceof(Link); link.id.should.equal(2); link.linkedId.should.eql(person2.id); link.linkedType.should.equal('Reader'); // lazy-loaded relations should.not.exist(book.people.at(0).linked()); should.not.exist(book.people.at(1).linked()); book.people(function(err, people) { people[0].linked().should.be.instanceof(Author); people[0].linked().name.should.equal('Author 1'); people[1].linked().should.be.instanceof(Reader); people[1].linked().name.should.equal('Reader 1'); done(); }); }); }); it('should include nested related items on scope', function(done) { // There's some date duplication going on, so it might // make sense to override toObject on a case-by-case basis // to sort this out (delete links, keep people). // In loopback, an afterRemote filter could do this as well. Book.find({ include: 'people' }, function(err, books) { var obj = books[0].toObject(); obj.should.have.property('links'); obj.should.have.property('people'); obj.links.should.have.length(2); obj.links[0].name.should.equal('Author 1'); obj.links[1].name.should.equal('Reader 1'); obj.people.should.have.length(2); obj.people[0].name.should.equal('Author 1'); obj.people[0].notes.should.equal('Something ...'); obj.people[0].linked.name.should.equal('Author 1'); obj.people[1].linked.name.should.equal('Reader 1'); done(); }); }); }); describe('referencesMany', function () { var job1, job2, job3; before(function (done) { // db = getSchema(); Category = db.define('Category', {name: String}); Job = db.define('Job', {name: String}); db.automigrate(['Job', 'Category'], done); }); it('can be declared', function (done) { var reverse = function(cb) { cb = cb || createPromiseCallback(); var modelInstance = this.modelInstance; var fk = this.definition.keyFrom; var ids = modelInstance[fk] || []; modelInstance.updateAttribute(fk, ids.reverse(), function(err, inst) { cb(err, inst[fk] || []); }); return cb.promise; }; reverse.shared = true; // remoting reverse.http = { verb: 'put', path: '/jobs/reverse' }; Category.referencesMany(Job, { scopeMethods: { reverse: reverse } }); Category.prototype['__reverse__jobs'].should.be.a.function; should.exist(Category.prototype['__reverse__jobs'].shared); Category.prototype['__reverse__jobs'].http.should.eql(reverse.http); db.automigrate(['Job', 'Category'], done); }); it('should setup test records', function (done) { Job.create({ name: 'Job 1' }, function(err, p) { job1 = p; Job.create({ name: 'Job 3' }, function(err, p) { job3 = p; done(); }); }); }); it('should create record on scope', function (done) { Category.create({ name: 'Category A' }, function(err, cat) { cat.jobIds.should.be.an.array; cat.jobIds.should.have.length(0); cat.jobs.create({ name: 'Job 2' }, function(err, p) { should.not.exist(err); cat.jobIds.should.have.length(1); cat.jobIds.should.eql([p.id]); p.name.should.equal('Job 2'); job2 = p; done(); }); }); }); it('should not allow duplicate record on scope', function (done) { Category.findOne(function(err, cat) { cat.jobIds = [job2.id, job2.id]; cat.save(function(err, p) { should.exist(err); err.name.should.equal('ValidationError'); err.details.codes.jobs.should.eql(['uniqueness']); done(); }); }); }); it('should find items on scope', function (done) { Category.findOne(function(err, cat) { cat.jobIds.should.eql([job2.id]); cat.jobs(function(err, jobs) { should.not.exist(err); var p = jobs[0]; p.id.should.eql(job2.id); p.name.should.equal('Job 2'); done(); }); }); }); it('should find items on scope - findById', function (done) { Category.findOne(function(err, cat) { cat.jobIds.should.eql([job2.id]); cat.jobs.findById(job2.id, function(err, p) { should.not.exist(err); p.should.be.instanceof(Job); p.id.should.eql(job2.id); p.name.should.equal('Job 2'); done(); }); }); }); it('should check if a record exists on scope', function (done) { Category.findOne(function(err, cat) { cat.jobs.exists(job2.id, function(err, exists) { should.not.exist(err); should.exist(exists); done(); }); }); }); it('should update a record on scope', function (done) { Category.findOne(function(err, cat) { var attrs = { name: 'Job 2 - edit' }; cat.jobs.updateById(job2.id, attrs, function(err, p) { should.not.exist(err); p.name.should.equal(attrs.name); done(); }); }); }); it('should get a record by index - at', function (done) { Category.findOne(function(err, cat) { cat.jobs.at(0, function(err, p) { should.not.exist(err); p.should.be.instanceof(Job); p.id.should.eql(job2.id); p.name.should.equal('Job 2 - edit'); done(); }); }); }); it('should add a record to scope - object', function (done) { Category.findOne(function(err, cat) { cat.jobs.add(job1, function(err, prod) { should.not.exist(err); cat.jobIds.should.eql([job2.id, job1.id]); prod.id.should.eql(job1.id); prod.should.have.property('name'); done(); }); }); }); it('should add a record to scope - object', function (done) { Category.findOne(function(err, cat) { cat.jobs.add(job3.id, function(err, prod) { should.not.exist(err); var expected = [job2.id, job1.id, job3.id]; cat.jobIds.should.eql(expected); prod.id.should.eql(job3.id); prod.should.have.property('name'); done(); }); }); }); it('should find items on scope - findById', function (done) { Category.findOne(function(err, cat) { cat.jobs.findById(job3.id, function(err, p) { should.not.exist(err); p.id.should.eql(job3.id); p.name.should.equal('Job 3'); done(); }); }); }); it('should find items on scope - filter', function (done) { Category.findOne(function(err, cat) { var filter = { where: { name: 'Job 1' } }; cat.jobs(filter, function(err, jobs) { should.not.exist(err); jobs.should.have.length(1); var p = jobs[0]; p.id.should.eql(job1.id); p.name.should.equal('Job 1'); done(); }); }); }); it('should remove items from scope', function (done) { Category.findOne(function(err, cat) { cat.jobs.remove(job1.id, function(err, ids) { should.not.exist(err); var expected = [job2.id, job3.id]; cat.jobIds.should.eql(expected); ids.should.eql(cat.jobIds); done(); }); }); }); it('should find items on scope - verify', function (done) { Category.findOne(function(err, cat) { var expected = [job2.id, job3.id]; cat.jobIds.should.eql(expected); cat.jobs(function(err, jobs) { should.not.exist(err); jobs.should.have.length(2); jobs[0].id.should.eql(job2.id); jobs[1].id.should.eql(job3.id); done(); }); }); }); it('should allow custom scope methods - reverse', function(done) { Category.findOne(function(err, cat) { cat.jobs.reverse(function(err, ids) { var expected = [job3.id, job2.id]; ids.should.eql(expected); cat.jobIds.should.eql(expected); done(); }); }) }); it('should include related items from scope', function(done) { Category.find({ include: 'jobs' }, function(err, categories) { categories.should.have.length(1); var cat = categories[0].toObject(); cat.name.should.equal('Category A'); cat.jobs.should.have.length(2); cat.jobs[0].id.should.eql(job3.id); cat.jobs[1].id.should.eql(job2.id); done(); }); }); it('should destroy items from scope - destroyById', function (done) { Category.findOne(function(err, cat) { cat.jobs.destroy(job2.id, function(err) { should.not.exist(err); var expected = [job3.id]; cat.jobIds.should.eql(expected); Job.exists(job2.id, function(err, exists) { should.not.exist(err); should.exist(exists); exists.should.be.false; done(); }); }); }); }); it('should find items on scope - verify', function (done) { Category.findOne(function(err, cat) { var expected = [job3.id]; cat.jobIds.should.eql(expected); cat.jobs(function(err, jobs) { should.not.exist(err); jobs.should.have.length(1); jobs[0].id.should.eql(job3.id); done(); }); }); }); it('should setup test records with promises', function (done) { db.automigrate(['Job', 'Category'], function () { return Job.create({ name: 'Job 1' }) .then(function (p) { job1 = p; return Job.create({ name: 'Job 3' }) }) .then(function (p) { job3 = p; done(); }).catch(done); }); }); it('should create record on scope with promises', function (done) { Category.create({ name: 'Category A' }) .then(function(cat) { cat.jobIds.should.be.an.array; cat.jobIds.should.have.length(0); return cat.jobs.create({ name: 'Job 2' }) .then(function(p) { cat.jobIds.should.have.length(1); cat.jobIds.should.eql([p.id]); p.name.should.equal('Job 2'); job2 = p; done(); }); }).catch(done); }); it('should not allow duplicate record on scope with promises', function (done) { Category.findOne() .then(function (cat) { cat.jobIds = [job2.id, job2.id]; cat.save() }) .then(function (p) { should.not.exist(p); done(); }) .catch(function (err) { should.exist(err); err.name.should.equal('ValidationError'); err.details.codes.jobs.should.eql(['uniqueness']); done(); }); }); it('should find items on scope with promises', function (done) { Category.findOne() .then(function (cat) { cat.jobIds.should.eql([job2.id]); return cat.jobs.getAsync() }) .then(function (jobs) { var p = jobs[0]; p.id.should.eql(job2.id); p.name.should.equal('Job 2'); done(); }) .catch(done); }); it('should find items on scope with promises - findById', function (done) { Category.findOne() .then(function (cat) { cat.jobIds.should.eql([job2.id]); return cat.jobs.findById(job2.id) }) .then(function (p) { p.should.be.instanceof(Job); p.id.should.eql(job2.id); p.name.should.equal('Job 2'); done(); }) .catch(done); }); it('should check if a record exists on scope with promises', function (done) { Category.findOne() .then(function (cat) { return cat.jobs.exists(job2.id) .then(function (exists) { should.exist(exists); done(); }); }).catch(done); }); it('should update a record on scope with promises', function (done) { Category.findOne() .then(function (cat) { var attrs = { name: 'Job 2 - edit' }; return cat.jobs.updateById(job2.id, attrs) .then(function (p) { p.name.should.equal(attrs.name); done(); }) }) .catch(done); }); it('should get a record by index with promises - at', function (done) { Category.findOne() .then(function (cat) { return cat.jobs.at(0) }) .then(function (p) { p.should.be.instanceof(Job); p.id.should.eql(job2.id); p.name.should.equal('Job 2 - edit'); done(); }) .catch(done); }); it('should add a record to scope with promises - object', function (done) { Category.findOne() .then(function (cat) { return cat.jobs.add(job1) .then(function (prod) { cat.jobIds.should.eql([job2.id, job1.id]); prod.id.should.eql(job1.id); prod.should.have.property('name'); done(); }); }) .catch(done); }); it('should add a record to scope with promises - object', function (done) { Category.findOne() .then(function (cat) { return cat.jobs.add(job3.id) .then(function (prod) { var expected = [job2.id, job1.id, job3.id]; cat.jobIds.should.eql(expected); prod.id.should.eql(job3.id); prod.should.have.property('name'); done(); }); }) .catch(done); }); it('should find items on scope with promises - findById', function (done) { Category.findOne() .then(function (cat) { return cat.jobs.findById(job3.id) }) .then(function (p) { p.id.should.eql(job3.id); p.name.should.equal('Job 3'); done(); }) .catch(done); }); it('should find items on scope with promises - filter', function (done) { Category.findOne() .then(function (cat) { var filter = { where: { name: 'Job 1' } }; return cat.jobs.getAsync(filter) }) .then(function (jobs) { jobs.should.have.length(1); var p = jobs[0]; p.id.should.eql(job1.id); p.name.should.equal('Job 1'); done(); }) .catch(done); }); it('should remove items from scope with promises', function (done) { Category.findOne() .then(function (cat) { return cat.jobs.remove(job1.id) .then(function (ids) { var expected = [job2.id, job3.id]; cat.jobIds.should.eql(expected); ids.should.eql(cat.jobIds); done(); }); }) .catch(done); }); it('should find items on scope with promises - verify', function (done) { Category.findOne() .then(function (cat) { var expected = [job2.id, job3.id]; cat.jobIds.should.eql(expected); return cat.jobs.getAsync() }) .then(function (jobs) { jobs.should.have.length(2); jobs[0].id.should.eql(job2.id); jobs[1].id.should.eql(job3.id); done(); }) .catch(done); }); it('should allow custom scope methods with promises - reverse', function(done) { Category.findOne() .then(function (cat) { return cat.jobs.reverse() .then(function (ids) { var expected = [job3.id, job2.id]; ids.should.eql(expected); cat.jobIds.should.eql(expected); done(); }); }) .catch(done); }); it('should include related items from scope with promises', function(done) { Category.find({ include: 'jobs' }) .then(function (categories) { categories.should.have.length(1); var cat = categories[0].toObject(); cat.name.should.equal('Category A'); cat.jobs.should.have.length(2); cat.jobs[0].id.should.eql(job3.id); cat.jobs[1].id.should.eql(job2.id); done(); }).catch(done); }); it('should destroy items from scope with promises - destroyById', function (done) { Category.findOne() .then(function (cat) { return cat.jobs.destroy(job2.id) .then(function () { var expected = [job3.id]; cat.jobIds.should.eql(expected); return Job.exists(job2.id) }) .then(function (exists) { should.exist(exists); exists.should.be.false; done(); }); }) .catch(done); }); it('should find items on scope with promises - verify', function (done) { Category.findOne() .then(function (cat) { var expected = [job3.id]; cat.jobIds.should.eql(expected); return cat.jobs.getAsync() }) .then(function (jobs) { jobs.should.have.length(1); jobs[0].id.should.eql(job3.id); done(); }) .catch(done); }); }); describe('custom relation/scope methods', function () { var categoryId; before(function (done) { // db = getSchema(); Category = db.define('Category', {name: String}); Job = db.define('Job', {name: String}); db.automigrate(['Job', 'Category'], done); }); it('can be declared', function (done) { var relation = Category.hasMany(Job); var summarize = function(cb) { cb = cb || createPromiseCallback(); var modelInstance = this.modelInstance; this.fetch(function(err, items) { if (err) return cb(err, []); var summary = items.map(function(item) { var obj = item.toObject(); obj.categoryName = modelInstance.name; return obj; }); cb(null, summary); }); return cb.promise; }; summarize.shared = true; // remoting summarize.http = { verb: 'get', path: '/jobs/summary' }; relation.defineMethod('summarize', summarize); Category.prototype['__summarize__jobs'].should.be.a.function; should.exist(Category.prototype['__summarize__jobs'].shared); Category.prototype['__summarize__jobs'].http.should.eql(summarize.http); db.automigrate(['Job', 'Category'], done); }); it('should setup test records', function (done) { Category.create({ name: 'Category A' }, function(err, cat) { categoryId = cat.id; cat.jobs.create({ name: 'Job 1' }, function(err, p) { cat.jobs.create({ name: 'Job 2' }, function(err, p) { done(); }); }) }); }); it('should allow custom scope methods - summarize', function(done) { var expected = [ { name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' }, { name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' } ]; Category.findOne(function(err, cat) { cat.jobs.summarize(function(err, summary) { should.not.exist(err); var result = summary.map(function(item) { delete item.id; return item; }); result.should.eql(expected); done(); }); }) }); it('should allow custom scope methods with promises - summarize', function(done) { var expected = [ { name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' }, { name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' } ]; Category.findOne() .then(function (cat) { return cat.jobs.summarize() }) .then(function (summary) { var result = summary.map(function(item) { delete item.id; return item; }); result.should.eql(expected); done(); }) .catch(done); }); }); });
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ module('Layer'); test('previousSibling / nextSibling', function() { var project = paper.project; var firstLayer = project.activeLayer; var secondLayer = new Layer(); equals(function() { return secondLayer.previousSibling == firstLayer; }, true); equals(function() { return secondLayer.nextSibling == null; }, true); // Move another layer into secondLayer and check nextSibling / // previousSibling: var path = new Path(); var thirdLayer = new Layer(); secondLayer.insertChild(0, thirdLayer); equals(function() { return secondLayer.children.length; }, 2); equals(function() { return thirdLayer.nextSibling == path; }, true); secondLayer.addChild(thirdLayer); equals(function() { return thirdLayer.nextSibling == null; }, true); equals(function() { return thirdLayer.previousSibling == path; }, true); equals(function() { return project.layers.length == 2; }, true); firstLayer.addChild(secondLayer); equals(function() { return project.layers.length == 1; }, true); }); test('insertAbove / insertBelow', function() { var project = paper.project; var firstLayer = project.activeLayer; var secondLayer = new Layer(); var thirdLayer = new Layer(); thirdLayer.insertBelow(firstLayer); equals(function() { return thirdLayer.previousSibling == null; }, true); equals(function() { return thirdLayer.nextSibling == firstLayer; }, true); secondLayer.insertBelow(firstLayer); equals(function() { return secondLayer.previousSibling == thirdLayer; }, true); equals(function() { return secondLayer.nextSibling == firstLayer; }, true); var path = new Path(); firstLayer.addChild(path); // move the layer above the path, inside the firstLayer. // 'Above' means visually appearing on top, thus with a larger index. secondLayer.insertAbove(path); equals(function() { return path.nextSibling == secondLayer; }, true); equals(function() { return secondLayer.parent == firstLayer; }, true); // There should now only be two layers left: equals(function() { return project.layers.length; }, 2); }); test('addChild / appendBottom / nesting', function() { var project = paper.project; var firstLayer = project.activeLayer; var secondLayer = new Layer(); // There should be two layers now in project.layers equals(function() { return project.layers.length; }, 2); firstLayer.addChild(secondLayer); equals(function() { return secondLayer.parent == firstLayer; }, true); // There should only be the firsLayer now in project.layers equals(function() { return project.layers.length; }, 1); equals(function() { return project.layers[0] == firstLayer; }, true); // Now move secondLayer bellow the first again, in which case it should // reappear in project.layers secondLayer.insertBelow(firstLayer); // There should be two layers now in project.layers again now equals(function() { return project.layers.length; }, 2); equals(function() { return project.layers[0] == secondLayer && project.layers[1] == firstLayer; }, true); });
'use strict'; angular.module('footieApp') .directive('helloWorld', function() { return { restrict: 'AE', replace: 'true', template: '<h3>Hello World!!</h3>' }; });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.eventMap = undefined; var _global = require('global'); exports.default = { alt: false, bubbles: true, button: 0, cancelable: true, clientX: 0, clientY: 0, ctrl: false, detail: 1, key: '13', isTrusted: true, meta: false, pageX: 0, pageY: 0, relatedTarget: null, touches: [], screenX: 0, screenY: 0, shift: false, view: _global.window, details: {} }; var eventMap = exports.eventMap = { MouseEvent: ['click', 'dblclick', 'mouseup', 'mousedown', 'mouseenter', 'mousemove', 'mouseleave'], KeyboardEvent: ['keypress', 'keydown', 'keyup'], TouchEvent: ['touchstart', 'touchmove', 'touchend', 'touchcancel'], CustomEvent: [] };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports["default"] = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); var _react = require("react"); var _Browser = _interopRequireDefault(require("../zhn-atoms/Browser")); var _CaptionRow = _interopRequireDefault(require("../zhn-atoms/CaptionRow")); var _ScrollPane = _interopRequireDefault(require("../zhn-atoms/ScrollPane")); var _MenuPart = _interopRequireDefault(require("./MenuPart")); var _jsxRuntime = require("react/jsx-runtime"); var S_BROWSER = { paddingRight: 0 }, S_SCROLL_DIV = { overflowY: 'auto', height: '92%', //height: 'calc(100vh - 90px)', paddingRight: 10 }; var MenuBrowserDynamic = /*#__PURE__*/function (_Component) { (0, _inheritsLoose2["default"])(MenuBrowserDynamic, _Component); /* static propTypes = { isInitShow: PropTypes.bool, browserType: PropTypes.string, caption: PropTypes.string, sourceMenuUrl: PropTypes.string, onLoadMenu: PropTypes.func, store: PropTypes.object, showAction: PropTypes.string, updateAction: PropTypes.string, loadCompletedAction: PropTypes.string } */ function MenuBrowserDynamic(props) { var _this; _this = _Component.call(this, props) || this; _this._loadMenu = function () { var _this$props = _this.props, browserType = _this$props.browserType, caption = _this$props.caption, sourceMenuUrl = _this$props.sourceMenuUrl, onLoadMenu = _this$props.onLoadMenu; onLoadMenu({ browserType: browserType, caption: caption, sourceMenuUrl: sourceMenuUrl }); }; _this._onStore = function (actionType, data) { var _this$props2 = _this.props, browserType = _this$props2.browserType, store = _this$props2.store, showAction = _this$props2.showAction, updateAction = _this$props2.updateAction, loadCompletedAction = _this$props2.loadCompletedAction; if (actionType === showAction && data === browserType) { _this._handleShow(); } else if (actionType === loadCompletedAction && data.browserType === browserType) { _this.setState({ menuItems: data.menuItems, isLoaded: true }); } else if (actionType === updateAction && data === browserType) { _this.setState({ menuItems: store.getBrowserMenu(browserType) }); } }; _this._handleHide = function () { _this.setState({ isShow: false }); }; _this._handleShow = function () { _this.setState({ isShow: true }); }; _this.state = { isShow: !!props.isInitShow, isLoaded: false, menuItems: [] }; return _this; } var _proto = MenuBrowserDynamic.prototype; _proto.componentDidMount = function componentDidMount() { this.unsubscribe = this.props.store.listen(this._onStore); this._loadMenu(); }; _proto.UNSAFE_componentWillUpdate = function UNSAFE_componentWillUpdate(nextProps, nextState) { if (!nextState.isLoaded && nextState.isShow) { this._loadMenu(); } }; _proto.componentWillUnmount = function componentWillUnmount() { this.unsubscribe(); }; _proto._renderMenuParts = function _renderMenuParts(rowClass, menuItems) { if (menuItems === void 0) { menuItems = []; } return menuItems.map(function (menuPart, index) { return /*#__PURE__*/(0, _react.createElement)(_MenuPart["default"], (0, _extends2["default"])({}, menuPart, { key: index, rowClass: rowClass })); }); }; _proto.render = function render() { var _this$props3 = this.props, caption = _this$props3.caption, children = _this$props3.children, rowClass = _this$props3.rowClass, _this$state = this.state, menuItems = _this$state.menuItems, isShow = _this$state.isShow; return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Browser["default"], { isShow: isShow, style: S_BROWSER, children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_CaptionRow["default"], { caption: caption, onClose: this._handleHide }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_ScrollPane["default"], { style: S_SCROLL_DIV, children: [this._renderMenuParts(rowClass, menuItems), children] })] }); }; return MenuBrowserDynamic; }(_react.Component); var _default = MenuBrowserDynamic; exports["default"] = _default; //# sourceMappingURL=MenuBrowserDynamic.js.map
"use strict"; describe('Repository', function() { require("./init").spec(); require("./ref").spec(); require("./update_index").spec(); require("./add").spec(); require("./remove").spec(); require("./move").spec(); require("./contents").spec(); require("./commit").spec(); require("./reset").spec(); require("./status").spec(); require("./diff").spec(); require("./branch").spec(); require("./checkout").spec(); require("./get_lca").spec(); require("./merge").spec(); require("./fetch").spec(); require("./pull").spec(); require("./push").spec(); });
/** * The MIT License (MIT) * * Copyright (c) 2014 Schmoopiie * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var serverList = { 'chat': { 80: ['199.9.250.229', '199.9.250.239', '199.9.252.120', '199.9.252.28', '199.9.253.165', '199.9.253.199', '199.9.253.210'], 443: ['199.9.250.229', '199.9.250.239', '199.9.252.120', '199.9.252.28', '199.9.253.165', '199.9.253.199', '199.9.253.210'] }, 'events': { 80: ['199.9.250.117', '199.9.251.213', '199.9.252.26'], 443: ['199.9.250.117', '199.9.251.213', '199.9.252.26'] }, 'groups': { 80: ['199.9.248.232', '199.9.248.248'], 443: ['199.9.248.232', '199.9.248.248'] } }; /** * Custom server pooling. It is better than using irc.twitch.tv. * @param type * @param server * @param port * @returns {string} */ var getServer = function getServer(type, server, port) { var serverType = type || 'chat'; var serverAddress = server || null; var serverPort = port || 443; if (serverAddress === null) { // Server type is valid. var serverTypes = ['chat', 'events', 'groups']; if (serverTypes.indexOf(serverType) === -1) { serverType = 'chat'; } // Port is valid. var serverPortsChat = [80,443]; var serverPorts = [80,443]; if (serverType === 'chat' && serverPortsChat.indexOf(serverPort) === -1) { serverPort = 443; } else if (serverType !== 'chat' && serverPorts.indexOf(serverPort) === -1) { serverPort = 443; } return serverList[serverType][serverPort][Math.floor(Math.random() * (serverList[serverType][serverPort].length - 1))]+':'+serverPort; } return serverAddress+':'+serverPort; } exports.getServer = getServer;
/** * Given a list of blocks, determine if a provided block * is the first child of its parent */ import siblingsOf from './siblingsOf' export default function(list, block, delta) { let siblings = siblingsOf(list, block) let index = siblings.indexOf(block) return index !== -1 ? siblings[index + delta] : null }
const path = require('path'); module.exports = { root: true, extends: [ 'eslint:recommended', 'prettier', 'plugin:import/errors', 'plugin:qunit/recommended', ], plugins: [ 'ember-internal', 'prettier', 'import', 'qunit', ], rules: { 'semi': 'error', 'no-unused-vars': 'error', 'no-throw-literal': 'error', 'no-useless-escape': 'off', // TODO: bring this back 'prettier/prettier': 'error', 'qunit/no-commented-tests': 'off', 'qunit/require-expect': 'off', }, settings: { 'import/core-modules': [ 'require', 'backburner', 'router', 'ember/version', 'node-module', ], 'import/parsers': { 'typescript-eslint-parser': ['.ts'], }, 'import/resolver': { node: { extensions: [ '.js', '.ts' ], paths: [ path.resolve('./packages/'), ] } } }, overrides: [ { files: [ '**/*.ts' ], parser: 'typescript-eslint-parser', parserOptions: { sourceType: 'module', } }, { files: [ 'packages/**/*.js' ], parserOptions: { ecmaVersion: 2017, sourceType: 'module', }, globals: { // A safe subset of 'browser:true': 'window': true, 'document': true, 'setTimeout': true, 'clearTimeout': true, 'setInterval': true, 'clearInterval': true, 'console': true, 'Map': true, 'Set': true, 'Symbol': true, 'WeakMap': true, }, rules: { 'ember-internal/require-yuidoc-access': 'error', 'ember-internal/no-const-outside-module-scope': 'error', 'semi': 'error', 'no-unused-vars': 'error', 'no-throw-literal': 'error', 'comma-dangle': 'off', }, }, { files: [ 'packages/*/tests/**/*.js', 'packages/@ember/*/tests/**/*.js', 'packages/@ember/-internals/*/tests/**/*.js', 'packages/internal-test-helpers/**/*.js', ], env: { qunit: true, }, globals: { 'expectAssertion': true, 'expectDeprecation': true, 'expectNoDeprecation': true, 'expectWarning': true, 'expectNoWarning': true, 'ignoreAssertion': true, 'ignoreDeprecation': true, }, }, { // matches all node-land files files: [ 'node-tests/**/*.js', 'tests/node/**/*.js', 'blueprints/**/*.js', 'bin/**/*.js', 'tests/docs/*.js', 'config/**/*.js', 'lib/**/*.js', 'server/**/*.js', 'testem.js', 'testem.travis-browsers.js', 'testem.browserstack.js', 'd8-runner.js', 'broccoli/**/*.js', 'ember-cli-build.js', 'rollup.config.js', ], parserOptions: { ecmaVersion: 2018, sourceType: 'script', }, env: { node: true, es6: true, }, plugins: ['node'], rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here 'no-process-exit': 'off', 'no-throw-literal': 'error' }), }, { // matches node-land files that aren't shipped to consumers (allows using Node 6+ features) files: [ 'broccoli/**/*.js', 'tests/node/**/*.js', 'ember-cli-build.js', 'rollup.config.js', 'd8-runner.js', ], rules: { 'node/no-unsupported-features': ['error', { version: 6 }], } }, { files: [ 'node-tests/**/*.js' ], env: { mocha: true, }, }, { files: [ 'tests/docs/**/*.js', 'tests/node/**/*.js', ], env: { qunit: true }, }, ] };
/** * angular-strap * @version v2.1.7 - 2015-10-19 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; angular.module('mgcrea.ngStrap.tooltip').run(['$templateCache', function($templateCache) { $templateCache.put('tooltip/tooltip.tpl.html', '<div class="tooltip in" ng-show="title"><div class="tooltip-arrow"></div><div class="tooltip-inner" ng-bind="title"></div></div>'); }]);
var songs = []; // Constructor function SongInMem(song) { // always initialize all instance properties this.username = song.username; this.title = song.title; this.artist = song.artist; this.text = song.text; this._id = null; } // class methods SongInMem.prototype.save = function(callback) { if (this._id == null) { this._id = songs.length; } songs[this._id] = { username:this.username, title:this.title, artist:this.artist, text:this.text, _id:this._id }; callback(null,this); }; SongInMem.prototype.findById = function(songId, callback) { this._id = null; for (i = 0; i < songs.length; i++) { if (songs[i]._id == songId) { this.username = songs[i].username; this.title = songs[i].title; this.artist = songs[i].artist; this.text = songs[i].text; this._id = songs[i]._id; } } var error = null; if (this._id == null) { error = true; } callback(error,this); }; // export the class module.exports = SongInMem;
app.controller('RentalController', ['$scope', 'EquipmentService', 'RentalService', function ($scope, equipmentService, rentalService) { $scope.model = { showCart: false, equipments: null, cart: [] }; $scope.rent = function (equipment) { console.log("Renting ..."); console.log(equipment); $scope.model.showCart = true; if ($scope.model.cart.indexOf(equipment) == -1) { $scope.model.cart.push(equipment); } console.log($scope.model.cart); }; $scope.mapType = function (typeId) { switch (typeId) { case 0: return "Heavy equipment"; case 1: return "Regular equipment"; case 2: return "Specialized equipment"; default: return "Unknown type"; } }; $scope.model.cartHasItems = function () { console.log("checking cart"); console.log($scope.model.cart); return $scope.model.cart.length > 0; }; $scope.remove = function (item) { var index = $scope.model.cart.indexOf(item); $scope.model.cart.splice(index, 1); }; $scope.order = function () { for (var i = 0; i < $scope.model.cart.length; i++) { var item = $scope.model.cart[i]; if (item.Days == undefined) { alert("Specify days for all items!"); return; } } rentalService.rent($scope.model.cart); }; (function init() { console.log("Rental controller initialized"); var set = equipmentService.getAll(function (data) { console.log(data); $scope.model.equipments = data; }) })(); }]);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createMeeting } from '../../../redux/meetings'; import MeetingEditor from './MeetingEditor'; class MeetingEditorContainer extends Component { render() { return ( <MeetingEditor isNew={true} onSave={(description, participantId) => this.props.createMeeting(this.props.selectedDate, description, participantId)} /> ); } } const mapStateToProps = state => ({ selectedDate: state.calendar.selectedDate }); const mapDispatchToProps = dispatch => ({ createMeeting: (...args) => dispatch(createMeeting(...args)) }) export default connect(mapStateToProps, mapDispatchToProps)(MeetingEditorContainer);
/* global it */ /* global describe */ 'use strict'; const Chai = require('chai'); const expect = Chai.expect; const valydet = require('../lib/valydet'); describe('default attribute test cases', () => { let UserSchema = new valydet.Schema({ id: { type: 'alphaNumeric', default: 1, required: true }, email: { type: 'email' }, createdAt: { type: 'date', default: new Date(), required: true }, updatedAt: { type: 'date', default: new Date(), required: true } }); let CommentSchema = new valydet.Schema({ id: { type: 'alphaNumeric', default: 1, required: true }, message: { type: 'string' } }); let PostSchema = new valydet.Schema({ id: { type: 'alphaNumeric', default: 1, required: true }, comments: { type: 'array', of: CommentSchema, default: [{ message: 'test' }] } }); it('should pass validation for defaults', (done) => { let instance = UserSchema.validate({ email: 'test@test.com' }); let failures = instance.failures(); expect(failures).to.not.be.undefined; expect(failures).to.not.be.null; expect(failures).to.have.length.of(0); done(); }); it('should set proper default value - Date', (done) => { let instance = UserSchema.validate({ email: 'test@test.com' }); let data = instance.get(); expect(data).to.not.be.undefined; expect(data).to.not.be.null; expect(data.createdAt instanceof Date).to.be.true; expect(data.updatedAt instanceof Date).to.be.true; done(); }); it('should set default value - Object', (done) => { let instance = PostSchema.validate({ id: 2 }); let data = instance.get(); expect(data).to.not.be.undefined; expect(data).to.not.be.null; expect(data.comments instanceof Array).to.be.true; done(); }); it('should set default value - Number', (done) => { let testSchema = new valydet.Schema({ id: { type: 'number', default: 2, required: true } }); let failures = testSchema.validate({}).failures(); expect(failures).to.not.be.undefined; expect(failures).to.not.be.null; expect(failures).to.have.length(0); done(); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { Menu: '菜单', 'Menu Items': '菜单项', 'Menu key is exists': '菜单KEY已经存在' };
/** @jsx React.DOM */ var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; var QuoteStream = React.createClass({displayName: 'QuoteStream', load: function() { $.ajax({ url: this.props.url, dataType: 'json', success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, componentDidMount: function() { this.load(); setInterval(this.load, this.props.pollInterval); }, getInitialState: function() { return ({data: []}); }, render: function() { var contentRow = []; var data = this.state.data; data.forEach(function(quotable) { contentRow.unshift(QuoteBox({quotable: quotable})); }.bind(this)); return ( React.DOM.div({className: "quoteStream"}, React.DOM.h1(null, " QuoteStream "), ReactCSSTransitionGroup({transitionName: "example"}, contentRow ) ) ); } }); var QuoteBox = React.createClass({displayName: 'QuoteBox', render: function() { return ( React.DOM.div({className: "quoteBox"}, QuoteText({text: this.props.quotable.text}), QuoteTitle({title: this.props.quotable.title, url: this.props.quotable.url}), QuoteUrl({url: this.props.quotable.url}), QuoteTime({time: this.props.quotable.createdAt}), React.DOM.br(null) ) ); } }); var QuoteText = React.createClass({displayName: 'QuoteText', render: function() { return ( React.DOM.blockquote({className: "quoteText"}, this.props.text ) ); } }); var QuoteTitle = React.createClass({displayName: 'QuoteTitle', render: function() { return ( React.DOM.div({className: "quoteTitle"}, React.DOM.strong(null, React.DOM.a({href: this.props.url}, this.props.title) ) ) ); } }); var QuoteUrl = React.createClass({displayName: 'QuoteUrl', render: function() { return ( React.DOM.small({className: "quoteTitle"}, this.props.url ) ); } }); var QuoteTime = React.createClass({displayName: 'QuoteTime', render: function() { return ( React.DOM.small({className: "quoteTime"}, this.props.time ) ); } }); var QuoteLogo = React.createClass({displayName: 'QuoteLogo', render: function() { return ( React.DOM.div({className: "quoteLogo"}, "This is the Quote Hovered Logo" ) ); } }); React.renderComponent( QuoteStream({url: "/quote", pollInterval: 2000}), document.getElementById("quoteStream") );
define(['text!templates/credits.html', 'text!templates/overlay.html', 'text!templates/popup.html', 'text!templates/popup_arrow.html', 'text!templates/popup_simple.html', 'text!templates/metodologia.html', 'text!templates/sql/click_feature.txt', 'text!templates/sql/click_feature_winner.txt', 'text!templates/sql/permalink.txt', 'text!templates/sql/draw_selection1.txt', 'text!templates/sql/draw_winner_selection2.txt', 'text!templates/sql/draw_selection2.txt', 'text!templates/sql/d3_geom.txt', 'text!templates/sql/d3_winner_query.txt', 'text!templates/sql/d3_diff_query.txt'], function(credits, overlay, popup, popup_arrow, popup_simple, metodologia, click_feature_sql, click_feature_winner_sql, permalink_sql, draw1_sql, draw2_winner_sql, draw2_sql, d3_geom_sql, d3_winner_sql, d3_diff_sql) { return { credits: credits, overlay: overlay, popup: popup, popup_arrow: popup_arrow, popup_simple: popup_simple, metodologia: metodologia, click_feature_sql: click_feature_sql, click_feature_winner_sql: click_feature_winner_sql, permalink_sql: permalink_sql, draw1_sql: draw1_sql, draw2_winner_sql: draw2_winner_sql, draw2_sql: draw2_sql, d3_geom_sql: d3_geom_sql, d3_winner_sql: d3_winner_sql, d3_diff_sql: d3_diff_sql }; });
/** * This module is the base for all controls that have the primary task of displaying either text, a graphic or both to the * user. * * @module jidejs/ui/control/Labeled * @abstract * @extends module:jidejs/ui/Control */ define([ './../../base/Class', './../../base/Util', './../../base/ObservableProperty', './../Control', './../Skin', './../../base/DOM', './../bind', './Templates', './../register' ], function(Class, _, Observable, Control, Skin, DOM, bind, Templates, register) { /** * Used by subclasses to initialize the Labeled control. * @memberof module:jidejs/ui/control/Labeled * @param {object} config The configuration * @constructor * @alias module:jidejs/ui/control/Labeled */ function Labeled(config) { installer(this); config = config || {}; Control.call(this, config); this.classList.add('jide-labeled'); } Class(Labeled).extends(Control).def({ /** * The text displayed by this Labeled control. * @type {string} */ text: '', /** * The text displayed by this Labeled control. * @type module:jidejs/base/ObservableProperty */ textProperty: null, /** * The Component displayed as the graphic of this Labeled control. * @type module:jidejs/ui/Component */ graphic: null, /** * The Component displayed as the graphic of this Labeled control. * @type module:jidejs/base/ObservableProperty */ graphicProperty: null, /** * Specifies how the content is displayed: * * - `top` * The graphic is shown above the text. * - `bottom` * The graphic is shown below the text. * - `left` * The graphic is shown left of the text. * - `right` * The graphic is shown right of the text. * @type string */ contentDisplay: null, /** * Specifies how the content is displayed. * @type module:jidejs/base/ObservableProperty * @see module:jidejs/ui/control/Labeled#contentDisplay */ contentDisplayProperty: null, /** * The amount of space between the graphic and the text in pixels. * * @type number */ graphicTextGap: null, /** * The amount of space between the graphic and the text in pixels. * * @type module:jidejs/base/ObservableProperty */ graphicTextGapProperty: null, dispose: function() { Control.prototype.dispose.call(this); installer.dispose(this); } }); Labeled.Skin = Skin.create(Skin, { graphic: null, text: null, template: Templates.Labeled, defaultElement: 'span', }); var installer = Observable.install(Labeled, 'text', 'contentDisplay', 'graphic', 'graphicTextGap'); register('jide-labeled', Labeled, Control, ['graphic', 'text', 'graphicTextGap'], []); return Labeled; });
function renderRadar() { var element = "detailSVG"; if (d3.select("#" + element).size() == 0) { d3.select(outerElement) .append("svg") .attr("id", element); } element = "#" + element; var radarData = getRadarData(); if (radarData.length == 0) { return d3.select(element).selectAll("*").remove(); } var formatted = $.map(radarData, function(variant, index) { var toPlot = []; for (var key in variant.xyz) { toPlot.push({ "axis" : key, "value" : variant.xyz[key] }); } return [toPlot]; }); var color = d3.scaleLinear() .range(["#EDC951","#CC333F","#00A0B0"]); var margin = {top: 50, right: 100, bottom: 100, left: 50}; var radarChartOptions = { w: 200, h: 200, margin: margin, levels: 5, roundStrokes: true, color: color }; RadarChart(element, formatted, radarChartOptions); } var lastRadarData = []; function getRadarData() { var keys = []; d3.selectAll(".selectedForRadar").each(function(element, index){ var id = d3.select(this).attr("id"); keys.push(parseInt(id.substring(id.indexOf("e") + 1)) - 1); //TODO: actually get key }); var selectedData = $.map(keys, key => data[key]); //the data actually selected by the user var indexOfLatestItem; //make sure latest add is last in array var finalData = []; $.grep(lastRadarData, function(element) { if ($.inArray(element, selectedData) != -1) { finalData.push(element); } }); $.grep(selectedData, function(element) { if ($.inArray(element, lastRadarData) == -1) { //put this new element at the end finalData.push(element); }; }); lastRadarData = finalData; return finalData; }