code
stringlengths
2
1.05M
/* # Agnostic scene composition for Lucidity */ 'use strict' const ShaderEffect = require ( './lib/ShaderEffect' ) const RecursiveShader = require ( './lib/RecursiveShader' ) const MixShader = require ( './lib/MixShader' ) const Anaglyph = require ( './lib/Anaglyph' ) const Multipass = require ( './lib/Multipass' ) const WebGLRenderer = require ( './lib/WebGLRenderer' ) module.exports = { ShaderEffect , RecursiveShader , MixShader , Anaglyph , Multipass , WebGLRenderer }
(function($){ 'use strict'; /** * get angle * @param {Object} self - 'this' object * @param {Object} point * @return {number} */ var get_angle = function(self, point){ var radians = 0 ,left = self.circle.center_abs_left - point.left ,top = self.circle.center_abs_top - point.top; //tan(radians) = y/x => radians = atan(y/x) radians = Math.atan(top/left); //in radians if(left>=0){ radians += Math.PI; } return radians; }; /** * get point * @param {Object} self - 'this' object * @param {number} radians * @return {Object} */ var get_point = function(self, radians){ var point = new $.fn.round_slider.point(0, 0) ,distance = self.circle.radius - self.weel_radius; point.left = self.circle.radius * Math.cos(radians) + distance; point.top = self.circle.radius * Math.sin(radians) + distance; return point; }; /** * get degrees * @param {Object} self - 'this' object * @param {number} radians * @return {number} */ var get_degrees = function(self, radians){ var angle = Math.round(radians*180/Math.PI); if(angle>360){ angle = angle % 360; } if(angle<0){ angle = 360 + angle; } return angle; }; /** * get radians * @param {Object} self - 'this' object * @param {number} degrees * @return {number} */ var get_radians = function(self, degrees){ return degrees*Math.PI/180; }; /** * init * @constructor * @param {Object} options * @param {Object} circle * @param {number} weel_radius * @return {Object} */ var init = function(options, circle, weel_radius){ var self = { options: options ,circle: circle ,weel_radius: weel_radius }; return $.extend(this, self); }; //API ------------------------------------------- /** * get angle * @param {Object} point * @return {number} */ init.prototype.get_angle = function(point){ return get_angle(this, point); }; /** * get point * @param {number} radians * @return {Object} */ init.prototype.get_point = function(radians){ return get_point(this, radians); }; /** * get degrees * @param {number} radians * @return {number} */ init.prototype.get_degrees = function(radians){ return get_degrees(this, radians); }; /** * get radians * @param {number} degrees * @return {number} */ init.prototype.get_radians = function(degrees){ return get_radians(this, degrees); }; /** * movement * @constructor * @param {Object} options * @param {Object} circle * @param {number} weel_radius * @return {Object} */ $.fn.round_slider.movement = function(options, circle, weel_radius){ return new init(options, circle, weel_radius); }; })(jQuery);
"use strict"; var random = require("../core/random"); var MIN_INTEGER = -100000000, MAX_INTEGER = 100000000; var numberType = function numberType(value) { var min = typeof value.minimum === 'undefined' ? MIN_INTEGER : value.minimum, max = typeof value.maximum === 'undefined' ? MAX_INTEGER : value.maximum, multipleOf = value.multipleOf; if (multipleOf) { max = Math.floor(max / multipleOf) * multipleOf; min = Math.ceil(min / multipleOf) * multipleOf; } if (value.exclusiveMinimum && value.minimum && min === value.minimum) { min += multipleOf || 1; } if (value.exclusiveMaximum && value.maximum && max === value.maximum) { max -= multipleOf || 1; } if (min > max) { return NaN; } if (multipleOf) { return Math.floor(random.number(min, max) / multipleOf) * multipleOf; } return random.number(min, max, undefined, undefined, true); }; module.exports = numberType;
var JasmineXMLReporter = { output_dir: './', junitreport: false, filePrefix: 'results', detect: function(arguments){ arguments.forEach(function (param, i, args) { var pair = param.split('='); var name = pair[0]; var value = pair.length > 1 ? pair[1] : ''; switch(name){ case '--filePrefix': if(value) JasmineXMLReporter.filePrefix = value; return JasmineXMLReporter.remove(param); case '--output': if(value) JasmineXMLReporter.output_dir = value; return JasmineXMLReporter.remove(param); case '--junitreport': JasmineXMLReporter.junitreport = true; return JasmineXMLReporter.remove(param); } }); return this.junitreport; }, remove: function(argument){ var index = process.argv.indexOf(argument); if(index !== -1) return process.argv.splice(index, 1); return false; }, attach_to: function(runner){ var reporters = require('jasmine-reporters'); var junitReporter = new reporters.JUnitXmlReporter({ savePath: this.output_dir, filePrefix: this.filePrefix }); runner.getEnv().addReporter(junitReporter); } }; if(JasmineXMLReporter.detect(process.argv.slice(2))){ JasmineXMLReporter.attach_to(jasmine); }
const isError = require('iserror') const allowedMapObjectTypes = [ 'string', 'number', 'boolean' ] /** * Convert an object into a structure with types suitable for serializing * across to native code. */ const serializeForNativeLayer = (map, maxDepth = 10, depth = 0, seen = new Set()) => { seen.add(map) const output = {} if (isError(map)) { map = extractErrorDetails(map) } for (const key in map) { if (!{}.hasOwnProperty.call(map, key)) continue const value = map[key] // Checks for `null`, NaN, and `undefined`. if ([ undefined, null ].includes(value) || (typeof value === 'number' && isNaN(value))) { output[key] = { type: 'string', value: String(value) } } else if (typeof value === 'object') { if (seen.has(value)) { output[key] = { type: 'string', value: '[circular]' } } else if (depth === maxDepth) { output[key] = { type: 'string', value: '[max depth exceeded]' } } else { output[key] = { type: 'map', value: serializeForNativeLayer(value, maxDepth, depth + 1, seen) } } } else { const type = typeof value if (allowedMapObjectTypes.includes(type)) { output[key] = { type: type, value: value } } else { console.warn(`Could not serialize breadcrumb data for '${key}': Invalid type '${type}'`) } } } return output } const extractErrorDetails = (err) => { const { message, stack, name } = err return { message, stack, name } } module.exports = serializeForNativeLayer
#!/usr/bin/env node const program = require('commander'); const chalk = require('chalk'); const cloudformation = require('./cloudformation'); const yaml = require('js-yaml'); const log = console.log; const tools = require('./tools'); const meta = require('../package.json'); let stackFilter; program .version(meta.version) .arguments('<stack>') .action(function (filter) { stackFilter = filter; }) program.parse(process.argv); let args = program.parse(process.argv).args; if (args.length === 0 && tools.inProjectDir()) { console.log('stack name must be provided') process.exit(0); } function listOutput(stackId) { return cloudformation.describeStack(stackId) .then(stack => { console.log(JSON.stringify(stack ? stack.Outputs: {}, null, 2)); }) .catch(err => tools.handleError(err)); } tools.inProjectDir() ? listOutput(args[0]) : listOutput(tools.stackId() || tools.stackName());
(function (angular) { 'use strict'; angular.module('jcs-autoValidateWithDirty') .factory('bootstrap3ElementModifier', [ '$log', function ($log) { var reset = function (el) { angular.forEach(el.find('span'), function (spanEl) { spanEl = angular.element(spanEl); if (spanEl.hasClass('error-msg') || spanEl.hasClass('form-control-feedback') || spanEl.hasClass('control-feedback')) { spanEl.remove(); } }); el.removeClass('has-success has-error has-feedback'); }, findWithClassElementAsc = function (el, klass) { var returnEl, parent = el; for (var i = 0; i <= 10; i += 1) { if (parent !== undefined && parent.hasClass(klass)) { returnEl = parent; break; } else if (parent !== undefined) { parent = parent.parent(); } } return returnEl; }, findWithClassElementDesc = function (el, klass) { var child; for (var i = 0; i < el.children.length; i += 1) { child = el.children[i]; if (child !== undefined && angular.element(child).hasClass(klass)) { break; } else if (child.children !== undefined) { child = findWithClassElementDesc(child, klass); if (child.length > 0) { break; } } } return angular.element(child); }, findFormGroupElement = function (el) { return findWithClassElementAsc(el, 'form-group'); }, findInputGroupElement = function (el) { return findWithClassElementDesc(el, 'input-group'); }, insertAfter = function (referenceNode, newNode) { referenceNode[0].parentNode.insertBefore(newNode[0], referenceNode[0].nextSibling); }, /** * @ngdoc property * @name bootstrap3ElementModifier#addValidationStateIcons * @propertyOf bootstrap3ElementModifier * @returns {bool} True if an state icon will be added to the element in the valid and invalid control * states. The default is false. */ addValidationStateIcons = false, /** * @ngdoc function * @name bootstrap3ElementModifier#enableValidationStateIcons * @methodOf bootstrap3ElementModifier * * @description * Makes an element appear invalid by apply an icon to the input element. * * @param {bool} enable - True to enable the icon otherwise false. */ enableValidationStateIcons = function (enable) { addValidationStateIcons = enable; }, /** * @ngdoc function * @name bootstrap3ElementModifier#makeValid * @methodOf bootstrap3ElementModifier * * @description * Makes an element appear valid by apply bootstrap 3 specific styles and child elements. If the service * property 'addValidationStateIcons' is true it will also append validation glyphicon to the element. * See: http://getbootstrap.com/css/#forms-control-validation * * @param {Element} el - The input control element that is the target of the validation. */ makeValid = function (el) { var frmGroupEl = findFormGroupElement(el), inputGroupEl; if (frmGroupEl) { reset(frmGroupEl); inputGroupEl = findInputGroupElement(frmGroupEl[0]); frmGroupEl.addClass('has-success ' + (inputGroupEl.length > 0 ? '' : 'has-feedback')); if (addValidationStateIcons) { var iconElText = '<span class="glyphicon glyphicon-ok form-control-feedback"></span>'; if (inputGroupEl.length > 0) { iconElText = iconElText.replace('form-', ''); iconElText = '<span class="input-group-addon control-feedback">' + iconElText + '</span'; } insertAfter(el, angular.element(iconElText)); } } else { $log.error('Angular-auto-validate: invalid bs3 form structure elements must be wrapped by a form-group class'); } }, /** * @ngdoc function * @name bootstrap3ElementModifier#makeInvalid * @methodOf bootstrap3ElementModifier * * @description * Makes an element appear invalid by apply bootstrap 3 specific styles and child elements. If the service * property 'addValidationStateIcons' is true it will also append validation glyphicon to the element. * See: http://getbootstrap.com/css/#forms-control-validation * * @param {Element} el - The input control element that is the target of the validation. */ makeInvalid = function (el, errorMsg) { var frmGroupEl = findFormGroupElement(el), helpTextEl = angular.element('<span class="help-block has-error error-msg">' + errorMsg + '</span>'), inputGroupEl; if (frmGroupEl) { reset(frmGroupEl); inputGroupEl = findInputGroupElement(frmGroupEl[0]); frmGroupEl.addClass('has-error ' + (inputGroupEl.length > 0 ? '' : 'has-feedback')); insertAfter(inputGroupEl.length > 0 ? inputGroupEl : el, helpTextEl); if (addValidationStateIcons) { var iconElText = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>'; if (inputGroupEl.length > 0) { iconElText = iconElText.replace('form-', ''); iconElText = '<span class="input-group-addon control-feedback">' + iconElText + '</span'; } insertAfter(el, angular.element(iconElText)); } } else { $log.error('Angular-auto-validate: invalid bs3 form structure elements must be wrapped by a form-group class'); } }, /** * @ngdoc function * @name bootstrap3ElementModifier#makeDefault * @methodOf bootstrap3ElementModifier * * @description * Makes an element appear in its default visual state by apply bootstrap 3 specific styles and child elements. * * @param {Element} el - The input control element that is the target of the validation. */ makeDefault = function (el) { var frmGroupEl = findFormGroupElement(el); if (frmGroupEl) { reset(frmGroupEl); } else { $log.error('Angular-auto-validate: invalid bs3 form structure elements must be wrapped by a form-group class'); } }; return { makeValid: makeValid, makeInvalid: makeInvalid, makeDefault: makeDefault, enableValidationStateIcons: enableValidationStateIcons, key: 'bs3' }; } ]); }(angular));
import { connect } from 'react-redux'; import { increment, doubleAsync } from '../modules/counter'; /* This is a container component. Notice it does not contain any JSX, nor does it import React. This component is **only** responsible for wiring in the actions and state necessary to render a presentational component - in this case, the counter: */ import Counter from '../components/Counter'; /* Object of action creators (can also be function that returns object). Keys will be passed as props to presentational components. Here we are implementing our wrapper around increment; the component doesn't care */ const mapDispatchToProps = { increment : () => increment(1), doubleAsync, }; const mapStateToProps = state => ({ counter : state.counter, }); /* Note: mapStateToProps is where you should use `reselect` to create selectors, ie: import { createSelector } from 'reselect' const counter = (state) => state.counter const tripleCount = createSelector(counter, (count) => count * 3) const mapStateToProps = (state) => ({ counter: tripleCount(state) }) Selectors can compute derived data, allowing Redux to store the minimal possible state. Selectors are efficient. A selector is not recomputed unless one of its arguments change. Selectors are composable. They can be used as input to other selectors. https://github.com/reactjs/reselect */ export default connect(mapStateToProps, mapDispatchToProps)(Counter);
import React from 'react' import { Dimensions, FlatList, Image } from 'react-native' import { formatPhotoUri } from '../api/picsum' export default function PhotoGrid({ photos, numColumns, onEndReached }) { const { width } = Dimensions.get('window') const size = width / numColumns // ... }
import { defineMessages } from 'react-intl'; export default defineMessages({ details: { id: 'component.city-weather.details', defaultMessage: 'Details', }, temperature: { id: 'component.city-weather.temperature', defaultMessage: 'Temperature', }, minTemperature: { id: 'component.city-weather.min-temperature', defaultMessage: 'Min Temperature', }, maxTemperature: { id: 'component.city-weather.max-temperature', defaultMessage: 'Max Temperature', }, pressure: { id: 'component.city-weather.pressure', defaultMessage: 'Pressure', }, windSpeed: { id: 'component.city-weather.wind-speed', defaultMessage: 'Wind Speed', }, cloudiness: { id: 'component.city-weather.cloudiness', defaultMessage: 'Humidity', }, calculatedAt: { id: 'component.city-weather.calculated-at', defaultMessage: 'Last calculation', }, });
describe('show: after clearing', () => { beforeEach(playbyplay.clear); it('should show the empty label', done => { function onShow(err) { expect(err).to.be.null; expect($('.playbyplay-empty')).to.exist; expect($('.playbyplay-run')).to.not.exist; done(); } function callback() { assert.fail(); } playbyplay.show({onShow: onShow}, callback); }); describe('and appending a first run', () => { const first = {input: 'i1', output: 'o1', status: 's1'}; beforeEach(done => { playbyplay.append(first, done); }); it('should show the first run', done => { function onShow(err) { expect(err).to.be.null; expect($('.playbyplay-empty')).to.not.exist; utils.expectRuns([first]); done(); } function callback() { assert.fail(); } playbyplay.show({onShow: onShow}, callback); }); describe('and appending a second run', () => { const second = {input: 'i2', output: 'o2', status: 's2'}; beforeEach(done => { playbyplay.append(second, done); }); it('should show the second then first run', done => { function onShow(err) { expect(err).to.be.null; expect($('.playbyplay-empty')).to.not.exist; utils.expectRuns([second, first]); done(); } function callback() { assert.fail(); } playbyplay.show({onShow: onShow}, callback); }); }); }); after(playbyplay.clear); });
"use strict"; const ElementInstance = require('./elementInstance'); /** * An instance of the Button form element. * @class * @extends Defiant.Plugin.FormApi.ElementInstance * @memberOf Defiant.Plugin.FormApi */ class ButtonInstance extends ElementInstance { /** * When this function is finished, then the form should be ready to * be rendered as a string. * @function * @async * @param {Object} [data={}] * The initialization data. */ async init(data={}) { const TagPair = this.context.theme.getRenderable('TagPair'); let button = TagPair.newInstance(this.context, { name: this.name, data: { tag: 'button', attributes: { value: this.data.value, name: this.name, class: new Set(['btn']), }, content: this.data.content || this.name, }, }); this.addInstance(button); await super.init(data); } } module.exports = ButtonInstance;
const path = require("path"); const packageName = require("./package.json").name; const webpackConfig = require("./webpack.config"); webpackConfig.resolve.alias = { "rsg-components/Wrapper": path.join(__dirname, 'utils', 'ExampleWrapper.tsx') }; module.exports = { propsParser: require("react-docgen-typescript").parse, components: "src/components/**/[A-Z]*.tsx", ignore: ["**/*.test.tsx"], showCode: true, showUsage: true, getComponentPathLine(componentPath) { const name = path.basename(componentPath, ".js").replace(".tsx", ""); const dir = path .dirname(componentPath) .replace("src/components", packageName); return `import ${name} from '${dir}';`; }, webpackConfig, sections: [ { name: "Introduction", content: "docs/introduction.md" }, { name: "Usage", content: "docs/Usage.md" }, { name: "Components", components: "src/components/**/[A-Z]*.tsx" }, { name: "Contributing", content: "docs/Contributing.md" } ] };
var gulp = require('gulp'); var gutil = require('gulp-util'); var args = require('yargs').argv; var mmhtConfig = require("./mmhtConfig.json"); var clean = require('./lib/clean'); var compile = require("./lib/compile"); var update = require("./lib/update"); var test = require("./lib/test"); var pull = require("./lib/pull"); if (args.lang) { mmhtConfig.HANDLEBARS_KEY = args.lang; } gulp.task('default', function () { // Default task code gutil.log('-------------------------------------------------------'); gutil.log('------------- ', gutil.colors.red('Warning Experimental Tool'), '--------------'); gutil.log('-------------------------------------------------------'); gutil.log(gutil.colors.magenta('gulp clean '), ' -- removes all *.mc.html files (mailchimp ready templates)'); gutil.log(gutil.colors.magenta('gulp compile --lang zh'), ' -- builds your templates (defaults to en).'); gutil.log(gutil.colors.magenta('gulp update '), ' -- pushes your templates to mandrill.'); gutil.log(gutil.colors.magenta('gulp pull '), ' -- download current templates from mandrill and format them.'); gutil.log(gutil.colors.magenta('gulp test '), ' -- sends you a test email from mandrill.'); gutil.log('-------------------------------------------------------'); }); gulp.task('clean', function () { clean(mmhtConfig); }); gulp.task('compile', ['clean'], function () { compile(mmhtConfig); }); gulp.task('update', function () { update(mmhtConfig); }); gulp.task('test', function () { test(mmhtConfig); }); gulp.task('pull', ['clean'], function () { pull(mmhtConfig); });
export const authSecret = '*SECRET*'
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.get('/user', (req, res) => { res.send('user'); }); const server = app.listen(8080, () => { const host = server.address().address; const port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
/* ************************************************************************ Copyright: 2013 Hericus Software, LLC License: The MIT License (MIT) Authors: Steven M. Cherry ************************************************************************ */ qx.Class.define("welcome.Singleton", { type: "singleton", extend: qx.core.Object, construct: function () { this.base(arguments); }, properties: { userProperties: { init: {} }, systemProperties: { init: {} }, newMenus: { init: {} }, viewMenus: { init: {} }, serverSettingsInternal: { init: [] }, buildServersXML: { init: null } }, members: { /** This is a wrapper method around our internal server settings. * If we find that they haven't yet been pulled from the server, we'll * do that, and populate our internal list. If they've already been * populated, we'll return them directly. * * @return Array<welcome.admin.sqldo.Setting> */ getServerSettings: function () { if (this.getServerSettingsInternal().length === 0) { this.refreshServerSettings(); } return this.getServerSettingsInternal(); }, /** Use this method to signal us that our server settings list needs to * be refreshed from the server. */ refreshServerSettings: function () { // retrieve the settings from the Server: welcome.Api.selectAllSettings(function (response) { var ret = welcome.sqldo.Setting.readElementChildren(response); var our = []; for (var i = 0, l = ret.length; i < l; i++) { var obj = ret[i]; our[obj.getName()] = obj.getValue(); } this.setServerSettingsInternal(our); }, this); }, getSystemProperty: function (whichProp) { return this.getSystemProperties[whichProp]; } }, statics: { /** Constant string used to look up a value from systemProperties */ AreWeHomeBase: "AreWeHomeBase" }, destruct: function () { } });
// Generated by CoffeeScript 1.10.0 (function() { var BinaryXmlParser; BinaryXmlParser = (function() { var ChunkType, NodeType, StringFlags, TypedValue; NodeType = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, CDATA_SECTION_NODE: 4 }; ChunkType = { NULL: 0x0000, STRING_POOL: 0x0001, TABLE: 0x0002, XML: 0x0003, XML_FIRST_CHUNK: 0x0100, XML_START_NAMESPACE: 0x0100, XML_END_NAMESPACE: 0x0101, XML_START_ELEMENT: 0x0102, XML_END_ELEMENT: 0x0103, XML_CDATA: 0x0104, XML_LAST_CHUNK: 0x017f, XML_RESOURCE_MAP: 0x0180, TABLE_PACKAGE: 0x0200, TABLE_TYPE: 0x0201, TABLE_TYPE_SPEC: 0x0202 }; StringFlags = { SORTED: 1 << 0, UTF8: 1 << 8 }; TypedValue = { COMPLEX_MANTISSA_MASK: 0x00ffffff, COMPLEX_MANTISSA_SHIFT: 0x00000008, COMPLEX_RADIX_0p23: 0x00000003, COMPLEX_RADIX_16p7: 0x00000001, COMPLEX_RADIX_23p0: 0x00000000, COMPLEX_RADIX_8p15: 0x00000002, COMPLEX_RADIX_MASK: 0x00000003, COMPLEX_RADIX_SHIFT: 0x00000004, COMPLEX_UNIT_DIP: 0x00000001, COMPLEX_UNIT_FRACTION: 0x00000000, COMPLEX_UNIT_FRACTION_PARENT: 0x00000001, COMPLEX_UNIT_IN: 0x00000004, COMPLEX_UNIT_MASK: 0x0000000f, COMPLEX_UNIT_MM: 0x00000005, COMPLEX_UNIT_PT: 0x00000003, COMPLEX_UNIT_PX: 0x00000000, COMPLEX_UNIT_SHIFT: 0x00000000, COMPLEX_UNIT_SP: 0x00000002, DENSITY_DEFAULT: 0x00000000, DENSITY_NONE: 0x0000ffff, TYPE_ATTRIBUTE: 0x00000002, TYPE_DIMENSION: 0x00000005, TYPE_FIRST_COLOR_INT: 0x0000001c, TYPE_FIRST_INT: 0x00000010, TYPE_FLOAT: 0x00000004, TYPE_FRACTION: 0x00000006, TYPE_INT_BOOLEAN: 0x00000012, TYPE_INT_COLOR_ARGB4: 0x0000001e, TYPE_INT_COLOR_ARGB8: 0x0000001c, TYPE_INT_COLOR_RGB4: 0x0000001f, TYPE_INT_COLOR_RGB8: 0x0000001d, TYPE_INT_DEC: 0x00000010, TYPE_INT_HEX: 0x00000011, TYPE_LAST_COLOR_INT: 0x0000001f, TYPE_LAST_INT: 0x0000001f, TYPE_NULL: 0x00000000, TYPE_REFERENCE: 0x00000001, TYPE_STRING: 0x00000003 }; function BinaryXmlParser(buffer) { this.buffer = buffer; this.cursor = 0; this.strings = []; this.resources = []; this.document = null; this.parent = null; this.stack = []; } BinaryXmlParser.prototype.readU8 = function() { var val; val = this.buffer[this.cursor]; this.cursor += 1; return val; }; BinaryXmlParser.prototype.readU16 = function() { var val; val = this.buffer.readUInt16LE(this.cursor); this.cursor += 2; return val; }; BinaryXmlParser.prototype.readS32 = function() { var val; val = this.buffer.readInt32LE(this.cursor); this.cursor += 4; return val; }; BinaryXmlParser.prototype.readU32 = function() { var val; val = this.buffer.readUInt32LE(this.cursor); this.cursor += 4; return val; }; BinaryXmlParser.prototype.readLength8 = function() { var len; len = this.readU8(); if (len & 0x80) { len = (len & 0x7f) << 7; len += this.readU8(); } return len; }; BinaryXmlParser.prototype.readLength16 = function() { var len; len = this.readU16(); if (len & 0x8000) { len = (len & 0x7fff) << 15; len += this.readU16(); } return len; }; BinaryXmlParser.prototype.readDimension = function() { var dimension, unit, value; dimension = { value: null, unit: null, rawUnit: null }; value = this.readU32(); unit = dimension.value & 0xff; dimension.value = value >> 8; dimension.rawUnit = unit; switch (unit) { case TypedValue.COMPLEX_UNIT_MM: dimension.unit = 'mm'; break; case TypedValue.COMPLEX_UNIT_PX: dimension.unit = 'px'; break; case TypedValue.COMPLEX_UNIT_DIP: dimension.unit = 'dp'; break; case TypedValue.COMPLEX_UNIT_SP: dimension.unit = 'sp'; break; case TypedValue.COMPLEX_UNIT_PT: dimension.unit = 'pt'; break; case TypedValue.COMPLEX_UNIT_IN: dimension.unit = 'in'; } return dimension; }; BinaryXmlParser.prototype.readFraction = function() { var fraction, type, value; fraction = { value: null, type: null, rawType: null }; value = this.readU32(); type = value & 0xf; fraction.value = this.convertIntToFloat(value >> 4); fraction.rawType = type; switch (type) { case TypedValue.COMPLEX_UNIT_FRACTION: fraction.type = '%'; break; case TypedValue.COMPLEX_UNIT_FRACTION_PARENT: fraction.type = '%p'; } return fraction; }; BinaryXmlParser.prototype.readHex24 = function() { return (this.readU32() & 0xffffff).toString(16); }; BinaryXmlParser.prototype.readHex32 = function() { return this.readU32().toString(16); }; BinaryXmlParser.prototype.readTypedValue = function() { var dataType, diff, end, id, ref, size, start, type, typedValue, zero; typedValue = { value: null, type: null, rawType: null }; start = this.cursor; size = this.readU16(); zero = this.readU8(); dataType = this.readU8(); typedValue.rawType = dataType; switch (dataType) { case TypedValue.TYPE_INT_DEC: typedValue.value = this.readS32(); typedValue.type = 'int_dec'; break; case TypedValue.TYPE_INT_HEX: typedValue.value = this.readS32(); typedValue.type = 'int_hex'; break; case TypedValue.TYPE_STRING: ref = this.readS32(); typedValue.value = ref > 0 ? this.strings[ref] : ''; typedValue.type = 'string'; break; case TypedValue.TYPE_REFERENCE: id = this.readU32(); typedValue.value = "resourceId:0x" + (id.toString(16)); typedValue.type = 'reference'; break; case TypedValue.TYPE_INT_BOOLEAN: typedValue.value = this.readS32() !== 0; typedValue.type = 'boolean'; break; case TypedValue.TYPE_NULL: this.readU32(); typedValue.value = null; typedValue.type = 'null'; break; case TypedValue.TYPE_INT_COLOR_RGB8: typedValue.value = this.readHex24(); typedValue.type = 'rgb8'; break; case TypedValue.TYPE_INT_COLOR_RGB4: typedValue.value = this.readHex24(); typedValue.type = 'rgb4'; break; case TypedValue.TYPE_INT_COLOR_ARGB8: typedValue.value = this.readHex32(); typedValue.type = 'argb8'; break; case TypedValue.TYPE_INT_COLOR_ARGB4: typedValue.value = this.readHex32(); typedValue.type = 'argb4'; break; case TypedValue.TYPE_DIMENSION: typedValue.value = this.readDimension(); typedValue.type = 'dimension'; break; case TypedValue.TYPE_FRACTION: typedValue.value = this.readFraction(); typedValue.type = 'fraction'; break; default: type = dataType.toString(16); typedValue.value = this.readU32(); typedValue.type = 'unknown'; } end = start + size; if (this.cursor !== end) { type = dataType.toString(16); diff = end - this.cursor; this.cursor = end; } return typedValue; }; BinaryXmlParser.prototype.convertIntToFloat = function(int) { var buf; buf = new ArrayBuffer(4); new (Int32Array(buf)[0] = buf); return new Float32Array(buf)[0]; }; BinaryXmlParser.prototype.readString = function(encoding) { var byteLength, stringLength, value; switch (encoding) { case 'utf-8': stringLength = this.readLength8(encoding); byteLength = this.readLength8(encoding); value = this.buffer.toString(encoding, this.cursor, this.cursor += byteLength); this.readU16(); return value; case 'ucs2': stringLength = this.readLength16(encoding); byteLength = stringLength * 2; value = this.buffer.toString(encoding, this.cursor, this.cursor += byteLength); this.readU16(); return value; default: throw new Error("Unsupported encoding '" + encoding + "'"); } }; BinaryXmlParser.prototype.readChunkHeader = function() { return { chunkType: this.readU16(), headerSize: this.readU16(), chunkSize: this.readU32() }; }; BinaryXmlParser.prototype.readStringPool = function(header) { var anchor, encoding, i, j, offsets, ref1, ref2; header.stringCount = this.readU32(); header.styleCount = this.readU32(); header.flags = this.readU32(); header.stringsStart = this.readU32(); header.stylesStart = this.readU32(); if (header.chunkType !== ChunkType.STRING_POOL) { throw new Error('Invalid string pool header'); } anchor = this.cursor; offsets = []; for (i = 0, ref1 = header.stringCount; 0 <= ref1 ? i < ref1 : i > ref1; 0 <= ref1 ? i++ : i--) { offsets.push(this.readU32()); } encoding = header.flags & StringFlags.UTF8 ? 'utf-8' : 'ucs2'; this.cursor = anchor + header.stringsStart - header.headerSize; for (j = 0, ref2 = header.stringCount; 0 <= ref2 ? j < ref2 : j > ref2; 0 <= ref2 ? j++ : j--) { this.strings.push(this.readString(encoding)); } this.cursor = anchor + header.chunkSize - header.headerSize; return null; }; BinaryXmlParser.prototype.readResourceMap = function(header) { var count, i, ref1; count = Math.floor((header.chunkSize - header.headerSize) / 4); for (i = 0, ref1 = count; 0 <= ref1 ? i < ref1 : i > ref1; 0 <= ref1 ? i++ : i--) { this.resources.push(this.readU32()); } return null; }; BinaryXmlParser.prototype.readXmlNamespaceStart = function(header) { var commentRef, line, prefixRef, uriRef; line = this.readU32(); commentRef = this.readU32(); prefixRef = this.readS32(); uriRef = this.readS32(); return null; }; BinaryXmlParser.prototype.readXmlNamespaceEnd = function(header) { var commentRef, line, prefixRef, uriRef; line = this.readU32(); commentRef = this.readU32(); prefixRef = this.readS32(); uriRef = this.readS32(); return null; }; BinaryXmlParser.prototype.readXmlElementStart = function(header) { var attrCount, attrSize, attrStart, classIndex, commentRef, i, idIndex, line, nameRef, node, nsRef, ref1, styleIndex; node = { namespaceURI: null, nodeType: NodeType.ELEMENT_NODE, nodeName: null, attributes: [], childNodes: [] }; line = this.readU32(); commentRef = this.readU32(); nsRef = this.readS32(); nameRef = this.readS32(); if (nsRef > 0) { node.namespaceURI = this.strings[nsRef]; } node.nodeName = this.strings[nameRef]; attrStart = this.readU16(); attrSize = this.readU16(); attrCount = this.readU16(); idIndex = this.readU16(); classIndex = this.readU16(); styleIndex = this.readU16(); for (i = 0, ref1 = attrCount; 0 <= ref1 ? i < ref1 : i > ref1; 0 <= ref1 ? i++ : i--) { node.attributes.push(this.readXmlAttribute()); } if (this.document) { this.parent.childNodes.push(node); this.parent = node; } else { this.document = this.parent = node; } this.stack.push(node); return node; }; BinaryXmlParser.prototype.readXmlAttribute = function() { var attr, nameRef, nsRef, valueRef; attr = { namespaceURI: null, nodeType: NodeType.ATTRIBUTE_NODE, nodeName: null, name: null, value: null, typedValue: null }; nsRef = this.readS32(); nameRef = this.readS32(); valueRef = this.readS32(); if (nsRef > 0) { attr.namespaceURI = this.strings[nsRef]; } attr.nodeName = attr.name = this.strings[nameRef]; if (valueRef > 0) { attr.value = this.strings[valueRef]; } attr.typedValue = this.readTypedValue(); return attr; }; BinaryXmlParser.prototype.readXmlElementEnd = function(header) { var commentRef, line, nameRef, nsRef; line = this.readU32(); commentRef = this.readU32(); nsRef = this.readS32(); nameRef = this.readS32(); this.stack.pop(); this.parent = this.stack[this.stack.length - 1]; return null; }; BinaryXmlParser.prototype.readXmlCData = function(header) { var cdata, commentRef, dataRef, line; cdata = { namespaceURI: null, nodeType: NodeType.CDATA_SECTION_NODE, nodeName: '#cdata', data: null, typedValue: null }; line = this.readU32(); commentRef = this.readU32(); dataRef = this.readS32(); if (dataRef > 0) { cdata.data = this.strings[dataRef]; } cdata.typedValue = this.readTypedValue(); this.parent.childNodes.push(cdata); return cdata; }; BinaryXmlParser.prototype.readNull = function(header) { this.cursor += header.chunkSize - header.headerSize; return null; }; BinaryXmlParser.prototype.parse = function() { var diff, end, header, resMapHeader, start, type, xmlHeader; xmlHeader = this.readChunkHeader(); if (xmlHeader.chunkType !== ChunkType.XML) { throw new Error('Invalid XML header'); } this.readStringPool(this.readChunkHeader()); resMapHeader = this.readChunkHeader(); if (resMapHeader.chunkType === ChunkType.XML_RESOURCE_MAP) { this.readResourceMap(resMapHeader); this.readXmlNamespaceStart(this.readChunkHeader()); } else { this.readXmlNamespaceStart(resMapHeader); } while (this.cursor < this.buffer.length) { start = this.cursor; header = this.readChunkHeader(); switch (header.chunkType) { case ChunkType.XML_START_NAMESPACE: this.readXmlNamespaceStart(header); break; case ChunkType.XML_END_NAMESPACE: this.readXmlNamespaceEnd(header); break; case ChunkType.XML_START_ELEMENT: this.readXmlElementStart(header); break; case ChunkType.XML_END_ELEMENT: this.readXmlElementEnd(header); break; case ChunkType.XML_CDATA: this.readXmlCData(header); break; case ChunkType.NULL: this.readNull(header); break; default: throw new Error("Unsupported chunk type '" + header.chunkType + "'"); } end = start + header.chunkSize; if (this.cursor !== end) { diff = end - this.cursor; type = header.chunkType.toString(16); this.cursor = end; } } return this.document; }; BinaryXmlParser.prototype.simpleParse = function() { var data, document; document = this.parse(); data = {}; this._simplifyDocumentData(data, document); return data; }; BinaryXmlParser.prototype._simplifyDocumentData = function(data, document) { var attr, i, len1, ref1, results; data[document.nodeName] = {}; ref1 = document.attributes; results = []; for (i = 0, len1 = ref1.length; i < len1; i++) { attr = ref1[i]; results.push(data[document.nodeName][attr.nodeName] = attr.typedValue.value); } return results; }; return BinaryXmlParser; })(); module.exports = BinaryXmlParser; }).call(this);
//----------------------------------------------------- // // Author: Daeren Torn // Site: 666.io // //----------------------------------------------------- "use strict"; //----------------------------------------------------- require("../index"); //----------------------------------------------------- var schUser = {"name": "string", "score": "integer"}; var tpzUser = $typenize(schUser), snzUser = $sanitize(schUser), vldUser = $validate(schUser); var data = {"name": "DT", "score": 13.7, "someData": 999}; console.log( tpzUser(data) //_ Rewrite ); console.log( tpzUser.format("My name: {name};\nMy score: {score};", data) ); console.log("\n"); console.log( snzUser(data) //_ New object ); console.log( snzUser.format("My name: {name};\nMy score: {score};", data) ); console.log("\n"); console.log( data, vldUser(data), vldUser(tpzUser(data)), vldUser(snzUser(data)) ); console.log( vldUser.format("vldUser: {}", data) ); console.log("\n"); console.log( $typenize("hashTable").format("{video}: {views}", '{"video": "cats", "views": 100500}') ); console.log( $sanitize("array").format("Array: {2}, {1}, {0}", "[11, 12, 13]", {"max": 2}) ); console.log( $typenize("string").format("Date: {}", new Date()) ); return; // <--------------- ! console.log( $typenize.format({"name": "DT", "score": 12.2}, "My name: {name};\nMy score: {score};") ); console.log( $typenize.format("My name: {0};\nMy score: {1};", "DT", 11.1) ); return; // <--------------- ! //----------------------------------------------------- var data = { "data": [2.2, "name", "[skip/del]ThisElem"] }; console.log( $typenize({"data": {"type": "array", "schema": ["integer", "string"]}}, data) ); console.log( $sanitize({"data": {"type": "array", "schema": ["integer", "string"]}}, data) ); //-----------]> var data = [6.9, "name", "delThisElem"]; console.log( $sanitize("array", data, {"schema": ["integer", "string"]}) ); //-----------]> var data = { "data": [{"pts": 2.2}, "name"] }; console.log( $typenize({"data": {"type": "array", "schema": [{"pts": "integer"}]}}, data) ); console.log( $sanitize({"data": {"type": "array", "schema": [{"pts": "integer"}]}}, data) ); console.log("\n\n"); //-----------]> var schema = { "data": { "type": "hashTable", "schema": { "login": "string", "password": "string", "more": { "type": "hashTable", "schema": { "someData": "string" } } } } }; var data = { "test": 1, "data": JSON.stringify({ "login": 1, "tex": 2 }) }; console.log($sanitize(schema, data)); console.log($typenize(schema, data)); console.log("\n\n"); var data = { "test": 1, "data": { "login": 1, "tex": 2 } }; console.log($typenize(schema, data)); console.log($sanitize(schema, data)); console.log("\n\n"); //----------------------------------------------------- console.log("+-------------------------+"); console.log("| Schema"); console.log("+-------------------------+"); var schema = { "name": { "type": "string", "rule": "required", "max": 3, "trim": true }, "status": "?string", "pts": { "use": "integer", "max": 30, "abs": true }, "data": { "type": "hashTable", "schema": { "login": "string", "password": "string", "more": { "type": "hashTable", "schema": { "someData": "string" } } } } }, data = {"name": " XX + ", "pts": "-60", "delThisField": "data"}; console.log(JSON.stringify({ "T0": $typenize(schema, data), //_ { name: ' XX + ', pts: -60, ...} "T1": $sanitize(schema, data) //_ { name: 'XX', pts: 30, ... } //"T2": $validate(schema, data) //_ error ("data" without "rule") }, null, "\t")); console.log("+-------------------------+"); console.log("| Store"); console.log("+-------------------------+"); $typenize.set("myName", {"name": "string"}); console.log("0#", $typenize.run("myName", {"name": [1,2,3]})); console.log("1#", $typenize.get("myName")); $sanitize.set("myName", {"name": "string"}); console.log("0#", $sanitize.run("myName", {"name": [1,2,3]})); console.log("1#", $sanitize.get("myName")); $validate.set("myName", {"name": "string"}); console.log("0#", $validate.run("myName", {"name": [1,2,3]})); console.log("1#", $validate.get("myName")); console.log("+-------------------------+"); console.log("| T: Schema"); console.log("+-------------------------+"); console.log("0#", $typenize("string", 10) + 10); var schema = { "name": "?string", "data": { "type": "hashTable", "schema": { "login": "string", "password": "string", "deep": { "type": "hashTable", "schema": { "someData": "string" } } } } }, data = { "name": "XX"/*, "data": { "login": new Date(), "password": /s+/g, "deep": { "someData": [1,2,3] } } */ }; console.log("1#", $typenize(schema, data)); console.log("+-------------------------+"); console.log("| S: Custom"); console.log("+-------------------------+"); $sanitize.type("testTypeDateEasy", function(input, options) { return new Date(input); }); console.log("0#", $sanitize("testTypeDateEasy", "Thu, 01 Jan 1970 00:00:00 GMT-0400")); console.log("1#", $sanitize("testTypeDateEasy", "---")); console.log("+-------------------------+"); console.log("| S: String"); console.log("+-------------------------+"); console.log(JSON.stringify({ "T0": $sanitize("string", 10), "T1": $sanitize("integer", "80", {"max": 50}), "T2": $sanitize("array", "[1,2,3]", {"max": 2}), "T3": $sanitize("integer", "50.5", {"enum": [10, 50]}), "T4": $sanitize("integer", "60.5", {"enum": [10, 50]}) }, null, "\t")); console.log("+-------------------------+"); console.log("| S: HashTable"); console.log("+-------------------------+"); var schema = { "name": {"type": "string", "rule": "required", "max": 3, "trim": true}, "status": "?string", "pts": {"use": "integer", "max": 30, "abs": true} }, data = {"name": " XX + ", "pts": "-60", "delThisField": "data"}; console.log("0#", $typenize(schema, data)); console.log("1#", $sanitize(schema, data)); console.log("2#", $validate(schema, data)); console.log("3#", $validate(schema, $sanitize(schema, data))); console.log("+-------------------------+"); console.log("| V: Custom"); console.log("+-------------------------+"); $validate.rule("testRuleMax10", function(input, options) { return input < 10; }); console.log("0#", $validate("testRuleMax10", 50)); console.log("1#", $validate("testRuleMax10", 8)); console.log("+-------------------------+"); console.log("| V: String"); console.log("+-------------------------+"); console.log(JSON.stringify({ "T0": $validate("string", 10), "T1": $validate("integer", "10"), "T2": $validate("email", "0d@root.pop"), "T3": $validate("email", "0d-root.pop"), "T4": $validate("?email", undefined) }, null, "\t")); console.log("+-------------------------+"); console.log("| V: HashTable"); console.log("+-------------------------+"); var schema = { "name": "string", "pswd": "string", "pswdCheck": {"use": "equal", "field": "pswd"}, //_ #1 //"pswdCheck": {"use": "equal", "value": "/\\w+/g"}, //_ #2 "status": "?string", "pts": "integer" }, data = {"name": "DT", "pts": "32", "pswd": "/\\s+/g", "pswdCheck": /\s+/g}; //_ #1 //data = {"name": "DT", "pts": "32", "pswd": "", "pswdCheck": /\w+/g}; //_ #2 console.log("1#", $validate(schema, data)); console.log("2#", $validate(schema, data, {"errors": true})); var schema = { "info": { "rule": "hashTable", "schema": { "login": { "rule": "hashTable", "schema": { "login": "string" } } } } }; console.log(JSON.stringify({ "T0": $validate(schema, {"info": {"login": {"login": 1}}}), "T1": $validate(schema, {"info": {}}), "T2": $validate(schema, {}), "T3": $validate(schema, {"info": {"login": {"login": 1}}}, {"errors": true}), "T4": $validate(schema, {"info": {"login": {"login": "test"}}}) }, null, "\t"));
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: { dist: [ 'assets/js/scripts.min.js', 'assets/svg/compressed', 'assets/svg/output' ] }, sass: { // Task dist: { // Target options: { // Target options style: 'compressed', sourcemap:'file' }, files: { // Dictionary of files 'assets/css/main.min.css': 'assets/sass/app.scss' // 'destination': 'source' } } }, grunticon: { //makes SVG icons into a CSS file myIcons: { files: [{ expand: true, cwd: 'assets/svg/compressed', src: ['*.svg'], dest: 'assets/svg/output' }], options: { cssprefix: '.icon-', colors: { brand_dark: '#302b36', brand_bright_green: '#99b41e' } } } }, rename: { moveThis: { src: 'assets/svg/output/icons.data.svg.css', dest: 'assets/svg/output/icons.data.svg.scss' } }, svgmin: { //minimize SVG files options: { plugins: [ { removeViewBox: false }, { removeUselessStrokeAndFill: false } ] }, dist: { expand: true, cwd: 'assets/svg/raw', src: ['*.svg'], dest: 'assets/svg/compressed', ext: '.colors-brand_dark-brand_bright_green.svg' } }, watch: { sass: { files: [ 'assets/sass/*.scss' ], tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-grunticon'); grunt.loadNpmTasks('grunt-rename'); grunt.loadNpmTasks('grunt-svgmin'); // Default task(s). grunt.registerTask('default', ['clean', 'svgmin', 'grunticon', 'rename', 'sass']); grunt.registerTask('dev', ['watch']); };
/* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ (function ( $ ) { 'use strict'; $.fn.extend({ provinceField: function () { $('select[name$="[countryCode]"]').on('change', function(event) { var $select = $(event.currentTarget); var $provinceContainer = $select.parents('.field').next('div.province-container'); var provinceSelectFieldName = $select.attr('name').replace('country', 'province'); var provinceInputFieldName = $select.attr('name').replace('countryCode', 'provinceName'); if ('' === $select.val()) { $provinceContainer.fadeOut('slow', function () { $provinceContainer.html(''); }); return; } $.get($provinceContainer.attr('data-url'), {countryCode: $(this).val()}, function (response) { if (!response.content) { $provinceContainer.fadeOut('slow', function () { $provinceContainer.html(''); }); } else if (-1 !== response.content.indexOf('select')) { $provinceContainer.fadeOut('slow', function () { $provinceContainer.html(response.content.replace( 'name="sylius_address_province"', 'name="' + provinceSelectFieldName + '"' )); $provinceContainer.fadeIn(); }); } else { $provinceContainer.fadeOut('slow', function () { $provinceContainer.html(response.content.replace( 'name="sylius_address_province"', 'name="' + provinceInputFieldName + '"' )); $provinceContainer.fadeIn(); }); } }); }); if('' !== $('select[name$="[countryCode]"]').val()) { $('select[name$="[countryCode]"]').trigger('change'); } if('' === $.trim($('div.province-container').text())) { $('select.country-select').trigger('change'); } var $billingAddressCheckbox = $('input[type="checkbox"][name$="[differentBillingAddress]"]'); var $billingAddressContainer = $('#sylius-billing-address-container'); var toggleBillingAddress = function() { $billingAddressContainer.toggle($billingAddressCheckbox.prop('checked')); }; toggleBillingAddress(); $billingAddressCheckbox.on('change', toggleBillingAddress); } }); })( jQuery );
var Prefab = Class.extend({ isPrefab: true, id: null, fullyLoaded: false, data: { }, layers: [ ], widthTiles: 0, heightTiles: 0, widthPx: 0, heightPx: 0, tileset: null, tilesPerRow: 0, blockedRects: [], ladderRects: [], init: function (id) { this.id = id; this.data = { }; this.layers = [ ]; this.widthTiles = 0; this.heightTiles = 0; this.widthPx = 0; this.heightPx = 0; this.tilesPerRow = 0; this.fullyLoaded = false; }, getWidth: function () { return this.widthPx; }, getHeight: function () { return this.heightPx; }, isRectBlocked: function (ourRect, adjustedX, adjustedY) { var blockedRectsLength = this.blockedRects.length; for (var i = 0; i < blockedRectsLength; i++) { var r = this.blockedRects[i]; var rectCopy = { left: r.left + adjustedX, right: r.right + adjustedX, top: r.top + adjustedY, bottom: r.bottom + adjustedY }; if (Utils.rectIntersects(ourRect, rectCopy)) { return true; } } return false; }, isRectLadder: function (ourRect, adjustedX, adjustedY) { var ladderRectsLength = this.ladderRects.length; for (var i = 0; i < ladderRectsLength; i++) { var r = this.ladderRects[i]; var rectCopy = { left: r.left + adjustedX, right: r.right + adjustedX, top: r.top + adjustedY, bottom: r.bottom + adjustedY }; if (Utils.rectIntersects(ourRect, rectCopy)) { return true; } } return false; }, draw: function (ctx, posX, posY) { this.drawBackground(ctx); }, drawBackground: function (ctx) { var layerCount = this.layers.length; for (var i = 0; i < layerCount; i++) { var layer = this.layers[i]; if (layer.type != 'tilelayer') { continue; } var layerDataLength = layer.data.length; var x = -1; var y = 0; var isBlocking = Settings.drawCollisions && typeof(layer.properties) != 'undefined' && layer.properties.blocked == '1'; if (!Settings.drawCollisions && !layer.visible) { continue; } for (var tileIdx = 0; tileIdx < layerDataLength; tileIdx++) { var tid = layer.data[tileIdx]; x++; if (x >= this.widthTiles) { y++; x = 0; } if (tid === 0) { // Invisible (no tile set for this position) continue; } tid--; // tid is offset by one, for calculation purposes we need it to start at zero var fullRows = Math.floor(tid / this.tilesPerRow); var srcY = fullRows * Settings.TileSize; var srcX = (tid * Settings.TileSize) - (fullRows * this.tilesPerRow * Settings.TileSize); var destX = x * Settings.TileSize; var destY = y * Settings.TileSize; ctx.drawImage(this.tileset, srcX, srcY, Settings.TileSize, Settings.TileSize, destX, destY, Settings.TileSize, Settings.TileSize); if (isBlocking) { ctx.beginPath(); ctx.rect(destX, destY, Settings.TileSize, Settings.TileSize); ctx.strokeStyle = "#FCEB77"; ctx.stroke(); ctx.closePath(); } } } } });
import { connect } from 'react-redux'; import { actions, VisibilityFilters } from '../modules/todolist'; import TodoList from '../components/TodoList'; const getTodos = (todos, filter) => { switch (filter) { case VisibilityFilters.SHOW_COMPLETED : return todos.filter(todo => todo.completed); case VisibilityFilters.SHOW_ACTIVE : return todos.filter(todo => !todo.completed); case VisibilityFilters.SHOW_ALL : default: return todos; } }; const mapStateToProps = (state) => { return { todos: getTodos( state.todolist.get('todos'), state.todolist.get('filter') ) }; }; const mapDispatchToProps = (dispatch) => { return { onTodoClick: (id) => { dispatch(actions.toggleTodo(id)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
'use strict' require('./index.scss') import React from 'react' import {log, toString, getInstace} from 'custom/utils' import statsStore from '../../stores/stats' import instanceStore from '../../stores/instance' import InstancesNumberManager from '../instances-number-manager' import charts from './charts' const {createShiftingBarChart, createShiftingLineChart} = charts const InstancesTypesStats = React.createClass({ getInitialState () { return { instancesTypes: {} } }, createCharts (type) { const periods = 30 const tickerTimeout = statsStore.emitter.getTickerTimeout() const endTimestamp = Date.now() const startTimestamp = endTimestamp - periods * tickerTimeout /* 0 values cannot be drawn in a chart */ const minValue = 1 const that = this statsStore.getServiceTypeSegregatedResponseStatsFromTimestamp({ serviceType: type, timestamp: startTimestamp }) .then((segregatedStats) => { ;(function createBarChart () { /* Strip most of the stats properties while leaving only the data used for the Bar Chart */ const dataSet = Array.from({length: periods}) .map((value, index) => { const time = Math.floor((startTimestamp + index * tickerTimeout) / 1000) return segregatedStats[time] && typeof segregatedStats[time] === 'object' ? segregatedStats[time].total : minValue }) /* Create a Bar Chart in a predefined placeholder w/ the calculated states data */ const barChart = createShiftingBarChart({ uiSelector: `.instanceType-${type} .stats-total`, width: 1000, height: 300, maxValue: 400, duration: tickerTimeout * 0.98, /* Keep the animation slightly faster in order to prevent overlapping insertion of "not animated" data */ maxVisibleBars: periods - 2 /* These 2 additional periods needs to be inserted into the 'dataSet' but not set as "visible" coz they'll be on the most left and most right side of the chart */ }) /* Subscribe the Chart for all Stats Updates that may come in future */ barChart.statsUpdater = function statsUpdater (stats) { if (!stats || typeof stats !== 'object' ) { log(new TypeError(`1st argument "stats" of type "${type}" must be {Object} but same is {${getInstace(stats)}} ${toString(stats)}`)) return } barChart.addOneDataItem(stats.total || minValue) barChart.draw() } /* Set the initial data and kickoff with the drawing animation */ /* NOTE: We gonna subscribe for new stats data only when we've finished animating the current one in order to prevent overlapping insertion of "not animated" data */ barChart.setData(dataSet) barChart.draw(() => { if (barChart.isChartDestroyed()) { return } statsStore.emitter.on(`${type}/responseStats`, barChart.statsUpdater) }) /* Register the newly created chart in the state so all other processes can have access to it */ const instancesTypes = that.state.instancesTypes instancesTypes[type].barChart = barChart that.setState({instancesTypes}) })() ;(function createLineChart () { function getAverageDuasion (stats) { if (!stats || typeof stats !== 'object' || !(stats.durations instanceof Array) ) { return minValue } const durationsSum = stats.durations .reduce((sum, duration) => sum + duration) return durationsSum / stats.durations.length } /* Strip most of the stats properties while leaving only the data used for the Line Chart */ const dataSet = Array.from({length: periods}) .map((value, index) => { const time = Math.floor((startTimestamp + index * tickerTimeout) / 1000) return getAverageDuasion(segregatedStats[time]) }) /* Create a Line Chart in a predefined placeholder w/ the calculated states data */ const lineChart = createShiftingLineChart({ uiSelector: `.instanceType-${type} .stats-duration`, width: 1000, customScaleWidth: 1000 + periods * 3.5, height: 280, maxValue: 12000, duration: tickerTimeout * 0.98, /* Keep the animation slightly faster in order to prevent overlapping insertion of "not animated" data */ maxVisibleLines: periods, defaultStyle: { strokeColor: '#F0B', strokeWidth: 3 } }) /* Subscribe the Chart for all Stats Updates that may come in future */ lineChart.statsUpdater = function statsUpdater (stats) { if (!stats || typeof stats !== 'object' ) { log(new TypeError(`1st argument "stats" of type "${type}" must be {Object} but same is {${getInstace(stats)}} ${toString(stats)}`)) return } const averageDuasion = (stats.duration || {average: 0}).average || minValue lineChart.addOneDataItem(averageDuasion) lineChart.draw() } /* Set the initial data and kickoff with the drawing animation */ /* NOTE: We gonna subscribe for new stats data only when we've finished animating the current one in order to prevent overlapping insertion of "not animated" data */ lineChart.setData(dataSet) lineChart.draw(() => { if (lineChart.isChartDestroyed()) { return } statsStore.emitter.on(`${type}/responseStats`, lineChart.statsUpdater) }) /* Register the newly created chart in the state so all other processes can have access to it */ const instancesTypes = that.state.instancesTypes instancesTypes[type].lineChart = lineChart that.setState({instancesTypes}) })() }) }, componentDidMount () { instanceStore.getAllInstancesTypes() .then((types) => { types /* Convert all types from {String}s into {Object}s */ .map((type) => ({type})) /* Assign Instance Type objects into the local State */ .map((instanceType) => { const instancesTypes = this.state.instancesTypes instancesTypes[instanceType.type] = instanceType this.setState({instancesTypes}) return instanceType }) .map((instanceType) => { this.createCharts(instanceType.type) return instanceType }) /* Set all "Instance Number Manager" fields as initially hidden */ .map((instanceType) => { const instancesTypes = this.state.instancesTypes Object.assign(instancesTypes[instanceType.type], { isManagerVisible: false }) this.setState({instancesTypes}) }) }) .catch((error) => log(`Error: Unable to get all Runing Service Instances: ${toString(error)}`)) }, componentWillUnmount () { /* Unbind from all stats events we take data from */ const instancesTypes = this.state.instancesTypes Object.keys(instancesTypes) .forEach((type) => { const barChart = instancesTypes[type].barChart statsStore.emitter.off(`${type}/responseStats`, barChart.statsUpdater) barChart.destroy() const lineChart = instancesTypes[type].lineChart statsStore.emitter.off(`${type}/responseStats`, lineChart.statsUpdater) lineChart.destroy() }) }, toggleManagerVisibility (type) { const instancesTypes = this.state.instancesTypes Object.assign(instancesTypes[type], { isManagerVisible: !instancesTypes[type].isManagerVisible }) this.setState({instancesTypes}) }, render () { const instancesTypes = this.state.instancesTypes return ( <div className='instances-types-stats'> { Object.keys(instancesTypes) .map((type) => { return (<div key={type} className={`instanceType instanceType-${type}`}> <strong> Service Type: <em>{type}</em> <button className='toggle-manager' onClick={() => this.toggleManagerVisibility(type)}>+</button> {instancesTypes[type].isManagerVisible && <InstancesNumberManager type={type} /> } </strong> <br /> <svg className='stats stats-duration'></svg> <svg className='stats stats-total'></svg> </div>) }) } </div> ) } }) export default InstancesTypesStats
const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: __dirname + "/dist/", filename: "pcloudsdk.js", library: "pCloudSdk", libraryTarget: "umd", umdNamedDefine: true, }, devtool: "source-map", mode: "production", module: { rules: [ { test: /\.js$/, enforce: "pre", loader: "source-map-loader", }, { test: /\.js$/, loader: "babel-loader", }, ], }, resolve: { aliasFields: ["browser"] }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("web"), }), ], };
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define("require exports ../core/tsSupport/declareExtendsHelper ../core/tsSupport/decorateHelper ./Accessor ./Handles ./accessorSupport/decorators ../views/support/WatchUpdatingTracking".split(" "),function(g,e,h,f,k,l,c,m){Object.defineProperty(e,"__esModule",{value:!0});e.HandleOwnerMixin=function(d){return function(b){function a(){return null!==b&&b.apply(this,arguments)||this}h(a,b);a.prototype.destroy=function(){this.destroyed||(this.handles.destroy(),this.updatingHandles.destroy())};Object.defineProperty(a.prototype, "handles",{get:function(){return this._get("handles")||new l},enumerable:!0,configurable:!0});Object.defineProperty(a.prototype,"updatingHandles",{get:function(){return this._get("updatingHandles")||new m.WatchUpdatingTracking},enumerable:!0,configurable:!0});f([c.property({readOnly:!0})],a.prototype,"handles",null);f([c.property({readOnly:!0})],a.prototype,"updatingHandles",null);return a=f([c.subclass("esri.core.HandleOwner")],a)}(c.declared(d))};g=function(d){function b(){return null!==d&&d.apply(this, arguments)||this}h(b,d);return b=f([c.subclass("esri.core.HandleOwner")],b)}(c.declared(e.HandleOwnerMixin(k)));e.HandleOwner=g});
export const u1F1FD = {"viewBox":"0 0 2600 2760.837","children":[{"name":"path","attribs":{"d":"M2182 2275q5 7 6 12t1 12q0 17-12 29t-29 12h-512q-11 0-20.5-4.5T1601 2322l-301-445-300 445q-12 18-34 18H452q-19 0-30-12.5t-11-30.5q0-10 7-22l582-846-578-859q-5-5-6-11t-1-13q0-18 12-29.5t29-11.5h488q21 0 34 18l322 469 322-469q13-18 34-18h489q17 0 29 12.5t12 30.5q0 12-6 22l-579 859z"},"children":[]}]};
import http from 'http'; import fs from 'fs'; import WebSocket from 'ws'; const Methods = { GET: 1, POST: 2, PUT: 3, DELETE: 4, OPTIONS: 5, }; const Conn = { req: null, res: null, hedares: null, method: null, url: null, }; const messages = []; let requests = []; const server = http.createServer((req, res) => { const headers = req.headers; const method = req.method; const url = req.url; Conn.req = req; Conn.res = res; Conn.headers = headers; Conn.method = method; Conn.url = url; const body = []; req.on('data', chunk => { body.push(chunk); }).on('end', () => { Conn.body = body.join(''); router(Methods[method], url, Conn.body); }); }); const router = (method, url, data) => { fs.readFile('./tut5/index2.html', (err, html) => { if (err) { Conn.res.statusCode = 404; Conn.res.end(); return; } Conn.res.writeHeader(200, {'Content-Type': 'text/html'}); Conn.res.write(html); Conn.res.end(); }); } const wss = new WebSocket.Server({ server }); wss.broadcast = function broadcast(data) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(data); } }); }; wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { // Broadcast to everyone else. wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(data)); } }); }); }); server.listen(8080, function() { console.log('server started on http://localhost:8080'); });
'use strict'; var assign = require('object-assign'); var defaultConfig = require('../config/default'); var envConfig; var path = require('path'); var pkg = require('../package.json'); //this if waterfall sucks, but it's needed for browserify if (process.env.NODE_ENV === 'development') { envConfig = require('../config/development'); } if (process.env.NODE_ENV === 'test') { envConfig = require('../config/test'); } if (process.env.NODE_ENV === 'production') { envConfig = require('../config/production'); } function buildConfig(isNode) { var data = assign(defaultConfig, envConfig); data.env = process.env.NODE_ENV; data.version = pkg.version; if (isNode) { data.appRoot = process.cwd(); data.log.file = path.resolve(data.appRoot, 'content/logs', data.log.file); data.contentPath = path.resolve(data.appRoot, 'content'); } return data; } module.exports = buildConfig(typeof window === 'undefined');
(function(){ var PokemonController = function($scope, $rootScope, $routeParams, $location, PokeFact){ var urlImages = "images/pokedex/", pokeName = $routeParams.name; $rootScope.appTitle= pokeName+" stats, abilities and evolutions"; $scope.pokemon = {}; PokeFact.getSinglePokeName( pokeName ) .then(function (data){ $scope.pokemon = data; // when $q rejected the promise, then() never executed }) .catch(function(){ $rootScope.appTitle="pokemon not found"; }); $scope.getUrlImg = function( pokeId ){ return urlImages+pokeId; }; }; var TabsController = function($scope){ $scope.tab = 1; $scope.selecTab = function( tab ){ $scope.tab = tab; }; $scope.isActive = function( tab ){ return ( $scope.tab === tab ) && 'active'; }; }; angular.module('pokeBoxApp.pokemon.controllers', []) .controller('PokemonCtrl', ['$scope', '$rootScope', '$routeParams', '$location', 'PokeFact', PokemonController]) .controller('TabsCtrl', ['$scope', TabsController]); }());
var rest = require('restler'); var auth = require('./auth'); var util = require('./util'); function getEvents(callback) { var spacesURL = 'http://www.nususc.com/USCWebsiteInformationAPI.asmx/GetAllEvents'; var data = { authenticationCode: 'USC$2016DevTool' }; rest.postJson(spacesURL, data, { timeout: 5000 }).on('timeout', x => callback('USC website is taking too long to respond. Please try again later 😊')) .on('complete', function(data, response) { var header = 'Upcoming Events:\n'; header += '==============\n\n'; var msg = filterEvents(data); if (msg !== '') { return callback(header + msg); } callback('No Upcoming Events'); }).on('error', err => console.log(err)); } function filterEvents(data) { var filteredMsg = ''; for (var i = 0; i < Math.min(data.d.length, 4); i++) { var event = data.d[i]; filteredMsg += event.EventName + '\n'; filteredMsg += event.Venue + '\n'; filteredMsg += event.Date + ' ' + event.StartTime + ' to ' + event.EndTime + '\n'; filteredMsg += 'http://www.nususc.com/EventRegistration.aspx?id=' + event.ID + '\n\n'; } return filteredMsg; } function getAllSpaces(chatId, callback) { function authCallback(row) { if (!row) { callback('Sorry you\'re not registered. Type /register to register.'); // } else if (!row.isCinnamonResident) { // callback('Sorry you must be a Cinnamon resident to use this feature :('); } else { getSpaces(1, callback); getSpaces(2, callback); getSpaces(3, callback); getSpaces(4, callback); getSpaces(6, callback); } } auth.isCinnamonResident(chatId, authCallback); } function getSpaces(id, callback) { var spacesURL = 'http://www.nususc.com/USCWebsiteInformationAPI.asmx/GetSpacesBookingRecord'; var data = { 'facilityID': id }; rest.postJson(spacesURL, data).on('complete', function(data, response) { var header; switch (id) { case 1: header = 'Theme Room 1:\n'; break; case 2: header = 'Theme Room 2:\n'; break; case 3: header = 'CTPH:\n'; break; case 4: header = 'Amphitheatre:\n'; break; case 6: header = 'Chatterbox:\n'; break; } header += '==============\n\n'; var msg = filterSpaces(data); if (msg !== '') { callback(header + msg); } else { callback(header + 'No Upcoming Events.'); } }); } function filterSpaces(data) { var filteredMsg = ''; var today = new Date(); var threeDays = new Date(); var timeOffset = 8 * 60 * 60 * 1000; threeDays.setDate(threeDays.getDate() + 3); data.d.forEach(event => { var startTime = new Date((new Date(event.start)).getTime() - timeOffset); var endTime = new Date((new Date(event.end)).getTime() - timeOffset); if (startTime < threeDays && startTime > today) { filteredMsg += event.title + '\n' + util.formatDate(startTime) + ' from ' + util.formatTime(startTime) + ' to ' + util.formatTime(endTime) + '\n\n'; } }); return filteredMsg; } module.exports = { getEvents, getAllSpaces, getSpaces };
const config = require('./../../config/config'); const initDebug = require('debug')('server:init'); const debug = require('debug')('server:request'); const bodyParser = require('body-parser'); module.exports = (app) => { initDebug('bootstrap app'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(require('morgan')('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(require('express-validator')()); app.use(require('cookie-parser')()); app.use((req, res, next) => { debug(req.body); res.header('Access-Control-Allow-Origin', config.server.origin); res.header('Access-Control-Request-Headers', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); res.header('Access-Control-Allow-Credentials', 'true'); next(); }); };
// Generated by CoffeeScript 1.9.3 var COMMON_REQUEST_HEADERS, COMMON_RESPONSE_HEADERS, QUICK_CONTENT_TYPES, contentType, fn, fn1, fn2, header, identifier, hasProp = {}.hasOwnProperty; COMMON_REQUEST_HEADERS = require('../common-request-headers'); COMMON_RESPONSE_HEADERS = require('../common-response-headers'); module.exports.fragments_getHeader = function(fragments_req) { return function(name) { return fragments_req.headers[name.toLowerCase()] || null; }; }; fn = function(identifier, header) { var lowerCaseHeader; lowerCaseHeader = header.toLowerCase(); return module.exports["fragments_header" + identifier] = function(fragments_req) { return fragments_req.headers[lowerCaseHeader] || null; }; }; for (identifier in COMMON_REQUEST_HEADERS) { header = COMMON_REQUEST_HEADERS[identifier]; fn(identifier, header); } module.exports.fragments_setHeader = function(fragments_res) { return function(key, value) { if (!((key != null) && (value != null))) { throw new Error('needs exactly two arguments'); } return fragments_res.setHeader(key, value); }; }; fn1 = function(identifier, header) { return module.exports["fragments_setHeader" + identifier] = function(fragments_res) { return function(value) { if (arguments.length !== 1) { throw new Error('needs exactly one argument'); } return fragments_res.setHeader(header, value); }; }; }; for (identifier in COMMON_RESPONSE_HEADERS) { header = COMMON_RESPONSE_HEADERS[identifier]; fn1(identifier, header); } module.exports.fragments_setHeaders = function(fragments_setHeader) { return function(headers) { var key, results, value; if ('object' !== typeof headers) { throw new Error('needs one argument which must be an object'); } results = []; for (key in headers) { if (!hasProp.call(headers, key)) continue; value = headers[key]; results.push(fragments_setHeader(key, value)); } return results; }; }; QUICK_CONTENT_TYPES = { HTML: 'text/html; charset=utf-8', JSON: 'application/json; charset=utf-8', XML: 'application/xml; charset=utf-8', Text: 'text/plain; charset=utf-8' }; fn2 = function(identifier, contentType) { return module.exports["fragments_setHeaderContentType" + identifier] = function(fragments_setHeaderContentType) { return function() { return fragments_setHeaderContentType(contentType); }; }; }; for (identifier in QUICK_CONTENT_TYPES) { contentType = QUICK_CONTENT_TYPES[identifier]; fn2(identifier, contentType); }
import m from "mithril" import { bulmify } from '../common' export const Progress = { view: vnode => m("progress.progress", bulmify(vnode.attrs, ['state', 'max']), vnode.children ) }
/** * Copyright (c) 2016, Lee Byron * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @ignore */ /** * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) * is a *protocol* which describes a standard way to produce a sequence of * values, typically the values of the Iterable represented by this Iterator. * * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) * it can be utilized by any version of JavaScript. * * @typedef {Object} Iterator * @template T The type of each iterated value * @property {function (): { value: T, done: boolean }} next * A method which produces either the next value in a sequence or a result * where the `done` property is `true` indicating the end of the Iterator. */ /** * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) * is a *protocol* which when implemented allows a JavaScript object to define * their iteration behavior, such as what values are looped over in a `for..of` * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) * implement the Iterable protocol, including `Array` and `Map`. * * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) * it can be utilized by any version of JavaScript. * * @typedef {Object} Iterable * @template T The type of each iterated value * @property {function (): Iterator<T>} Symbol.iterator * A method which produces an Iterator for this Iterable. */ // In ES2015 (or a polyfilled) environment, this will be Symbol.iterator var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator; /** * Returns true if the provided object implements the Array-like protocol via * defining a positive-integer `length` property. * * @example * * var isArrayLike = require('iterall').isArrayLike * isArrayLike([ 1, 2, 3 ]) // true * isArrayLike('ABC') // true * isArrayLike({ length: 1, 0: 'Alpha' }) // true * isArrayLike({ key: 'value' }) // false * isArrayLike(new Map()) // false * * @param obj * A value which might implement the Array-like protocol. * @return {boolean} true if Array-like. */ function isArrayLike(obj) { var length = obj != null && obj.length; return typeof length === 'number' && length >= 0 && length % 1 === 0 } /** * If the provided object implements the Iterator protocol, its Iterator object * is returned. Otherwise returns undefined. * * @example * * var getIterator = require('iterall').getIterator * var iterator = getIterator([ 1, 2, 3 ]) * iterator.next() // { value: 1, done: false } * iterator.next() // { value: 2, done: false } * iterator.next() // { value: 3, done: false } * iterator.next() // { value: undefined, done: true } * * @template T the type of each iterated value * @param {Iterable<T>} iterable * An Iterable object which is the source of an Iterator. * @return {Iterator<T>} new Iterator instance. */ function getIterator(iterable) { var method = getIteratorMethod(iterable); if (method) { return method.call(iterable) } } /** * If the provided object implements the Iterator protocol, the method * responsible for producing its Iterator object is returned. * * This is used in rare cases for performance tuning. This method must be called * with obj as the contextual this-argument. * * @example * * var getIteratorMethod = require('iterall').getIteratorMethod * var myArray = [ 1, 2, 3 ] * var method = getIteratorMethod(myArray) * if (method) { * var iterator = method.call(myArray) * } * * @template T the type of each iterated value * @param {Iterable<T>} iterable * An Iterable object which defines an `@@iterator` method. * @return {function(): Iterator<T>} `@@iterator` method. */ function getIteratorMethod(iterable) { if (iterable != null) { var method = (SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator']; if (typeof method === 'function') { return method } } } /** * Given an object which either implements the Iterable protocol or is * Array-like, iterate over it, calling the `callback` at each iteration. * * Use `forEach` where you would expect to use a `for ... of` loop in ES6. * However `forEach` adheres to the behavior of [Array#forEach][] described in * the ECMAScript specification, skipping over "holes" in Array-likes. It will * also delegate to a `forEach` method on `collection` if one is defined, * ensuring native performance for `Arrays`. * * Similar to [Array#forEach][], the `callback` function accepts three * arguments, and is provided with `thisArg` as the calling context. * * Note: providing an infinite Iterator to forEach will produce an error. * * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach * * @example * * var forEach = require('iterall').forEach * * forEach(myIterable, function (value, index, iterable) { * console.log(value, index, iterable === myIterable) * }) * * @example * * // ES6: * for (let value of myIterable) { * console.log(value) * } * * // Any JavaScript environment: * forEach(myIterable, function (value) { * console.log(value) * }) * * @template T the type of each iterated value * @param {Iterable<T>|{ length: number }} collection * The Iterable or array to iterate over. * @param {function(T, number, object)} callback * Function to execute for each iteration, taking up to three arguments * @param [thisArg] * Optional. Value to use as `this` when executing `callback`. */ function forEach(collection, callback, thisArg) { if (collection != null) { if (typeof collection.forEach === 'function') { return collection.forEach(callback, thisArg) } var i = 0; var iterator = getIterator(collection); if (iterator) { var step; while (!(step = iterator.next()).done) { callback.call(thisArg, step.value, i++, collection); // Infinite Iterators could cause forEach to run forever. // After a very large number of iterations, produce an error. /* istanbul ignore if */ if (i > 9999999) { throw new TypeError('Near-infinite iteration.') } } } else if (isArrayLike(collection)) { for (; i < collection.length; i++) { if (collection.hasOwnProperty(i)) { callback.call(thisArg, collection[i], i, collection); } } } } } var forEach_1 = forEach; // var selectionPrototype = { data: function(data , getKey) { var this$1 = this; if ( getKey === void 0 ) getKey = function (value, index) { return index; }; // flush // exit will receive by default previous enter and update // we'll remove values from it over iteration // enter and update are flushed // and will be populated over iteration this.__data.exit = Object.assign({}, this.__data.enter, this.__data.update); this.__data.enter = {}; this.__data.update = {}; forEach_1(data, function (value, index) { var key = getKey(value, index); // already exists: // --> add in update pool // --> remove from exit if (key in this$1.__data.exit) { this$1.__data.update[key] = value; delete this$1.__data.exit[key]; } // else we add it else { this$1.__data.enter[key] = value; } }); return this; }, enter: function() { return Object.values(this.__data.enter); }, update: function() { return Object.values(this.__data.update); }, all: function() { return Object.values(Object.assign({}, this.__data.enter, this.__data.update)); }, exit: function() { return Object.values(this.__data.exit); } }; var dthree = { selections: {}, selectAll: function(namespace ) { if (typeof namespace === 'undefined') { throw new Error('dthree.selectAll: namespace is not provided'); } if (typeof namespace !== 'string') { throw new Error('dthree.selectAll: namespace should be a string'); } if (!(namespace in this.selections)) { this.selections[namespace] = Object.create(selectionPrototype); this.selections[namespace].__data = { enter: {}, exit: {}, update: {} }; } return this.selections[namespace]; }, }; export default dthree;
'use strict'; //Setting up route angular.module('breakouts').config(['$stateProvider', function($stateProvider) { // Breakouts state routing $stateProvider. state('listBreakouts', { url: '/breakouts', templateUrl: 'modules/breakouts/views/list-breakouts.client.view.html' }). state('createBreakout', { url: '/breakouts/create', templateUrl: 'modules/breakouts/views/create-breakout.client.view.html' }). state('viewAdminGrid', { url: '/admin/grid', templateUrl: 'modules/breakouts/views/adminGrid-breakout.client.view.html' }). state('usersGrid', { url: '/admin/usersGrid', templateUrl: 'modules/breakouts/views/adminUsersGrid.client.view.html' }). state('viewAdminUserById', { url: '/admin/users/:uid', templateUrl: 'modules/breakouts/views/adminUserView-breakout.client.view.html' }). state('viewAdminBreakoutsByName', { url: '/admin/grid/breakouts/:breakoutname', templateUrl: 'modules/breakouts/views/adminBreakoutsWithOneName-breakout.client.view.html' }). state('thanksForSigningUp', { url: '/schedule/users/:uid', templateUrl: 'modules/breakouts/views/thanksForSigningUp-breakouts.client.view.html' }). state('viewBreakout', { url: '/breakouts/:breakoutId', templateUrl: 'modules/breakouts/views/view-breakout.client.view.html' }). state('editBreakout', { url: '/breakouts/:breakoutId/edit', templateUrl: 'modules/breakouts/views/edit-breakout.client.view.html' }); } ]);
import React from 'react'; import Router from 'react-router'; import App from './components/App'; import Page from './components/Page'; const {Route} = Router; const routes = <Route handler={App}> <Route name='page' path='/page/:id' handler={Page} /> </Route>; Router.run(routes, Router.HistoryLocation, Root => React.render(<Root />, document.getElementById('app')));
import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT, TOGGLE_AGREEMENT, SAVE_NEW_METADATA } from './actions'; import { getStoredAuthData } from '../helpers/utils'; export const initialState = { isLoggingIn: false, idToken: null, profile: null, error: null }; function initializeState() { const storedAuthData = getStoredAuthData(); return Object.assign({}, initialState, storedAuthData); } export default function auth(state = initializeState(), action) { switch (action.type) { case LOGIN_REQUEST: return { ...state, isLoggingIn: true }; case LOGIN_SUCCESS: return { ...state, isLoggingIn: false, idToken: action.idToken, profile: action.profile, error: null }; case LOGIN_FAILURE: return { ...state, isLoggingIn: false, idToken: null, profile: null, error: action.error }; case LOGOUT: return initialState; case TOGGLE_AGREEMENT: return { ...state, profile: { ...state.profile, user_metadata: { ...state.profile.user_metadata, agreedToTerms: !state.profile.user_metadata.agreedToTerms } } }; case SAVE_NEW_METADATA: return { ...state, profile: { ...state.profile, user_metadata: action.user_metadata } }; default: return state; } }
$(document).ready(function () { /*------------------------------------------- Sparkline ---------------------------------------------*/ function sparklineBar(id, values, height, barWidth, barColor, barSpacing) { $('.'+id).sparkline(values, { type: 'bar', height: height, barWidth: barWidth, barColor: barColor, barSpacing: barSpacing }) } function sparklineLine(id, values, width, height, lineColor, fillColor, lineWidth, maxSpotColor, minSpotColor, spotColor, spotRadius, hSpotColor, hLineColor) { $('.'+id).sparkline(values, { type: 'line', width: width, height: height, lineColor: lineColor, fillColor: fillColor, lineWidth: lineWidth, maxSpotColor: maxSpotColor, minSpotColor: minSpotColor, spotColor: spotColor, spotRadius: spotRadius, highlightSpotColor: hSpotColor, highlightLineColor: hLineColor }); } function sparklinePie(id, values, width, height, sliceColors) { $('.'+id).sparkline(values, { type: 'pie', width: width, height: height, sliceColors: sliceColors, offset: 0, borderWidth: 0 }); } /* Mini Chart - Bar Chart 1 */ if ($('.stats-bar')[0]) { sparklineBar('stats-bar', [6,4,8,6,5,6,7,8,3,5,9,5,8,4], '35px', 3, '#fff', 2); } /* Mini Chart - Bar Chart 2 */ if ($('.stats-bar-2')[0]) { sparklineBar('stats-bar-2', [4,7,6,2,5,3,8,6,6,4,8,6,5,8], '35px', 3, '#fff', 2); } /* Mini Chart - Line Chart 1 */ if ($('.stats-line')[0]) { sparklineLine('stats-line', [9,4,6,5,6,4,5,7,9,3,6,5], 68, 35, '#fff', 'rgba(0,0,0,0)', 1.25, 'rgba(255,255,255,0.4)', 'rgba(255,255,255,0.4)', 'rgba(255,255,255,0.4)', 3, '#fff', 'rgba(255,255,255,0.4)'); } /* Mini Chart - Line Chart 2 */ if ($('.stats-line-2')[0]) { sparklineLine('stats-line-2', [5,6,3,9,7,5,4,6,5,6,4,9], 68, 35, '#fff', 'rgba(0,0,0,0)', 1.25, 'rgba(255,255,255,0.4)', 'rgba(255,255,255,0.4)', 'rgba(255,255,255,0.4)', 3, '#fff', 'rgba(255,255,255,0.4)'); } /* Mini Chart - Pie Chart 1 */ if ($('.stats-pie')[0]) { sparklinePie('stats-pie', [20, 35, 30, 5], 45, 45, ['#fff', 'rgba(255,255,255,0.7)', 'rgba(255,255,255,0.4)', 'rgba(255,255,255,0.2)']); } /* Dash Widget Line Chart */ if ($('.dash-widget-visits')[0]) { sparklineLine('dash-widget-visits', [9,4,6,5,6,4,5,7,9,3,6,5], '100%', '70px', 'rgba(255,255,255,0.7)', 'rgba(0,0,0,0)', 2, '#fff', '#fff', '#fff', 5, 'rgba(255,255,255,0.4)', 'rgba(255,255,255,0.1)'); } /*------------------------------------------- Easy Pie Charts ---------------------------------------------*/ function easyPieChart(id, trackColor, scaleColor, barColor, lineWidth, lineCap, size) { $('.'+id).easyPieChart({ trackColor: trackColor, scaleColor: scaleColor, barColor: barColor, lineWidth: lineWidth, lineCap: lineCap, size: size }); } /* Main Pie Chart */ if ($('.main-pie')[0]) { easyPieChart('main-pie', 'rgba(255,255,255,0.2)', 'rgba(255,255,255,0)', 'rgba(255,255,255,0.7)', 2, 'butt', 148); } /* Others */ if ($('.sub-pie-1')[0]) { easyPieChart('sub-pie-1', 'rgba(255,255,255,0.2)', 'rgba(255,255,255,0)', 'rgba(255,255,255,0.7)', 2, 'butt', 90); } if ($('.sub-pie-2')[0]) { easyPieChart('sub-pie-2', 'rgba(255,255,255,0.2)', 'rgba(255,255,255,0)', 'rgba(255,255,255,0.7)', 2, 'butt', 90); } });
(function ($) { 'use strict'; $.fn.twittie = function () { var options = (arguments[0] instanceof Object) ? arguments[0] : {}, callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1]; // Default settings var settings = $.extend({ 'username': 'ohadnavon', 'list': null, 'count': 4, 'hideReplies': false, 'dateFormat': '%b/%d/%Y', 'template': '{{date}} - {{tweet}}', 'apiPath' : 'api/tweet.php' }, options); if (settings.list && !settings.username) { $.error('If you want to fetch tweets from a list, you must define the username of the list owner.'); } /** * Applies @reply, #hash and http links * @param {String} tweet A single tweet * @return {String} Fixed tweet * * Thanks to @Wachem enhanced linking. */ var linking = function (tweet) { var twit = tweet.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig,'<a href="$1" target="_blank" title="Visit this link">$1</a>') .replace(/#([a-zA-Z0-9_]+)/g,'<a href="http://twitter.com/search?q=%23$1&amp;src=hash" target="_blank" title="Search for #$1">#$1</a>') .replace(/@([a-zA-Z0-9_]+)/g,'<a href="http://twitter.com/$1" target="_blank" title="$1 on Twitter">@$1</a>'); return twit; }; /** * Formating a date * @param {String} twt_date Twitter date * @return {String} Formatted date */ var dating =function relative_time(time_value) { var values = time_value.split(" "); time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3]; var parsed_date = Date.parse(time_value); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - parsed_date) / 1000); delta = delta + (relative_to.getTimezoneOffset() * 60); if (delta < 60) { return 'less than a minute ago'; } else if(delta < 120) { return 'about a minute ago'; } else if(delta < (60*60)) { return (parseInt(delta / 60)).toString() + ' minutes ago'; } else if(delta < (120*60)) { return 'about an hour ago'; } else if(delta < (24*60*60)) { return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'; } else if(delta < (48*60*60)) { return '1 day ago'; } else { return (parseInt(delta / 86400)).toString() + ' days ago'; } }; /** * Templating a tweet using '{{ }}' braces * @param {Object} data Tweet details are passed * @return {String} Templated string */ var templating = function (data) { var temp = settings.template; var temp_variables = ['date', 'tweet', 'avatar', 'url', 'retweeted', 'screen_name']; for (var i = 0, len = temp_variables.length; i < len; i++) { temp = temp.replace(new RegExp('{{' + temp_variables[i] + '}}', 'gi'), data[temp_variables[i]]); } return temp; }; // Set loading this.html('<span class="tweets_loader">Loading...</span>'); var that = this; // Fetch tweets $.getJSON(settings.apiPath, { username: settings.username, list: settings.list, count: settings.count, exclude_replies: settings.hideReplies }, function (twt) { that.find('span').fadeOut('fast', function () { for (var i = 0; i < settings.count; i++) { if (twt[i]) { var temp_data = { date: dating(twt[i].created_at), tweet: (twt[i].retweeted) ? linking('RT @'+ twt[i].user.screen_name +': '+ twt[i].retweeted_status.text) : linking(twt[i].text), avatar: '<img src="'+ twt[i].user.profile_image_url +'" />', url: 'http://twitter.com/' + twt[i].user.screen_name + '/status/' + twt[i].id_str, retweeted: twt[i].retweeted, screen_name: linking('@'+ twt[i].user.screen_name), }; that.append('<div class="tweet">' + templating(temp_data) + '</div>'); } else { break; } } $(".tweets_feed").find(".tweets_loader").remove(); if (typeof callback === 'function') { callback(); } }); }); }; })(jQuery);
/*! Flocking 0.2.0-dev, Copyright 2015 Colin Clark | flockingjs.org */ (function (root, factory) { if (typeof exports === "object") { // We're in a CommonJS-style loader. root.flock = exports; // Always create the "flock" global. factory(exports, require("jquery")); } else if (typeof define === "function" && define.amd) { // We're in an AMD-style loader. define(["exports", "jquery"], function (exports, jQuery) { root.flock = exports; // Always create the "flock" global. return (root.flock, factory(exports, jQuery)); }); } else { // Plain old browser. root.flock = {}; factory(root.flock, jQuery); } }(this, function (exports, jQuery) { // To hell with isolationism. window.jQuery = jQuery; ;/*! * Fluid Infusion v2.0 * * Infusion is distributed under the Educational Community License 2.0 and new BSD licenses: * http://wiki.fluidproject.org/display/fluid/Fluid+Licensing * * For information on copyright, see the individual Infusion source code files: * https://github.com/fluid-project/infusion/ */ /* Copyright 2007-2010 University of Cambridge Copyright 2007-2009 University of Toronto Copyright 2007-2009 University of California, Berkeley Copyright 2010-2011 Lucendo Development Ltd. Copyright 2010 OCAD University Copyright 2011 Charly Molter Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ // Declare dependencies /* global console, opera, YAHOO*/ var fluid_2_0 = fluid_2_0 || {}; var fluid = fluid || fluid_2_0; (function ($, fluid) { "use strict"; fluid.version = "Infusion 2.0-SNAPSHOT"; // Export this for use in environments like node.js, where it is useful for // configuring stack trace behaviour fluid.Error = Error; fluid.environment = { fluid: fluid }; fluid.global = fluid.global || window || {}; // A standard utility to schedule the invocation of a function after the current // stack returns. On browsers this defaults to setTimeout(func, 1) but in // other environments can be customised - e.g. to process.nextTick in node.js // In future, this could be optimised in the browser to not dispatch into the event queue fluid.invokeLater = function (func) { return setTimeout(func, 1); }; // The following flag defeats all logging/tracing activities in the most performance-critical parts of the framework. // This should really be performed by a build-time step which eliminates calls to pushActivity/popActivity and fluid.log. fluid.defeatLogging = true; // This flag enables the accumulating of all "activity" records generated by pushActivity into a running trace, rather // than removing them from the stack record permanently when receiving popActivity. This trace will be consumed by // visual debugging tools. fluid.activityTracing = false; fluid.activityTrace = []; var activityParser = /(%\w+)/g; // Renders a single activity element in a form suitable to be sent to a modern browser's console // unsupported, non-API function fluid.renderOneActivity = function (activity, nowhile) { var togo = nowhile === true ? [] : [" while "]; var message = activity.message; var index = activityParser.lastIndex = 0; while (true) { var match = activityParser.exec(message); if (match) { var key = match[1].substring(1); togo.push(message.substring(index, match.index)); togo.push(activity.args[key]); index = activityParser.lastIndex; } else { break; } } if (index < message.length) { togo.push(message.substring(index)); } return togo; }; // Renders an activity stack in a form suitable to be sent to a modern browser's console // unsupported, non-API function fluid.renderActivity = function (activityStack, renderer) { renderer = renderer || fluid.renderOneActivity; return fluid.transform(activityStack, renderer); }; // Return an array of objects describing the current activity // unsupported, non-API function fluid.getActivityStack = function () { var root = fluid.globalThreadLocal(); if (!root.activityStack) { root.activityStack = []; } return root.activityStack; }; // Return an array of objects describing the current activity // unsupported, non-API function fluid.describeActivity = fluid.getActivityStack; // Renders either the current activity or the supplied activity to the console fluid.logActivity = function (activity) { activity = activity || fluid.describeActivity(); var rendered = fluid.renderActivity(activity).reverse(); fluid.log("Current activity: "); fluid.each(rendered, function (args) { fluid.doLog(args); }); }; // Execute the supplied function with the specified activity description pushed onto the stack // unsupported, non-API function fluid.pushActivity = function (type, message, args) { var record = {type: type, message: message, args: args, time: new Date().getTime()}; if (fluid.activityTracing) { fluid.activityTrace.push(record); } if (fluid.passLogLevel(fluid.logLevel.TRACE)) { fluid.doLog(fluid.renderOneActivity(record, true)); } var activityStack = fluid.getActivityStack(); activityStack.push(record); }; // Undo the effect of the most recent pushActivity, or multiple frames if an argument is supplied fluid.popActivity = function (popframes) { popframes = popframes || 1; if (fluid.activityTracing) { fluid.activityTrace.push({pop: popframes}); } var activityStack = fluid.getActivityStack(); var popped = activityStack.length - popframes; activityStack.length = popped < 0 ? 0 : popped; }; // "this-ist" style Error so that we can distinguish framework errors whilst still retaining access to platform Error features // unsupported, non-API function fluid.FluidError = function (message) { this.message = message; this.stack = new Error().stack; }; fluid.FluidError.prototype = new Error(); // The framework's built-in "fail" policy, in case a user-defined handler would like to // defer to it fluid.builtinFail = function (soft, args, activity) { fluid.log.apply(null, [fluid.logLevel.FAIL, "ASSERTION FAILED: "].concat(args)); fluid.logActivity(activity); var message = args.join(""); if (soft) { throw new fluid.FluidError(message); } else { message["Assertion failure - check console for details"](); // Intentionally cause a browser error by invoking a nonexistent function. } }; var softFailure = [false]; /** * Signals an error to the framework. The default behaviour is to log a structured error message and throw a variety of * exception (hard or soft) - see fluid.pushSoftFailure for configuration * * @param {String} message the error message to log * @param ... Additional arguments, suitable for being sent to native console.log function */ fluid.fail = function (/* message, ... */) { var args = fluid.makeArray(arguments); var activity = fluid.makeArray(fluid.describeActivity()); // Take copy since we will destructively modify fluid.popActivity(activity.length); var topFailure = softFailure[0]; if (typeof(topFailure) === "boolean") { fluid.builtinFail(topFailure, args, activity); } else if (typeof(topFailure) === "function") { topFailure(args, activity); } }; /** * Configure the behaviour of fluid.fail by pushing or popping a disposition record onto a stack. * @param {Boolean|Number|Function} condition & Supply either a boolean flag choosing between built-in framework strategies to be used in fluid.fail * - <code>false</code>, the default causes a "hard failure" by using a nonexistent property on a String, which * will in all known environments trigger an unhandleable exception which aids debugging. The boolean value * <code>true</code> downgrades this behaviour to throw a conventional exception, which is more appropriate in * test cases which need to demonstrate failure, as well as in some production environments. * The argument may also be a function, which will be called with two arguments, args (the complete arguments to * fluid.fail) and activity, an array of strings describing the current framework invocation state. * Finally, the argument may be the number <code>-1</code> indicating that the previously supplied disposition should * be popped off the stack */ fluid.pushSoftFailure = function (condition) { if (typeof (condition) === "boolean" || typeof (condition) === "function") { softFailure.unshift(condition); } else if (condition === -1) { softFailure.shift(); } }; fluid.notrycatch = true; // A wrapper for the try/catch/finally language feature, to aid debugging on environments // such as IE, where any try will destroy stack information for errors // TODO: The only non-deprecated call to this annoying utility is left in DataBinding.js to deal with // cleanup in source tracking. We should really review whether we mean to abolish all exception handling // code throughout the framework - on several considerations this is desirable. fluid.tryCatch = function (tryfun, catchfun, finallyfun) { finallyfun = finallyfun || fluid.identity; if (fluid.notrycatch) { var togo = tryfun(); finallyfun(); return togo; } else { try { return tryfun(); } catch (e) { if (catchfun) { catchfun(e); } else { throw (e); } } finally { finallyfun(); } } }; // TODO: rescued from kettleCouchDB.js - clean up in time fluid.expect = function (name, members, target) { fluid.transform(fluid.makeArray(members), function (key) { if (typeof target[key] === "undefined") { fluid.fail(name + " missing required parameter " + key); } }); }; // Logging /** Returns whether logging is enabled **/ fluid.isLogging = function () { return logLevelStack[0].priority > fluid.logLevel.IMPORTANT.priority; }; /** Determines whether the supplied argument is a valid logLevel marker **/ fluid.isLogLevel = function (arg) { return fluid.isMarker(arg) && arg.priority !== undefined; }; /** Accepts one of the members of the <code>fluid.logLevel</code> structure. Returns <code>true</code> if * a message supplied at that log priority would be accepted at the current logging level. Clients who * issue particularly expensive log payload arguments are recommended to guard their logging statements with this * function */ fluid.passLogLevel = function (testLogLevel) { return testLogLevel.priority <= logLevelStack[0].priority; }; /** Method to allow user to control the logging level. Accepts either a boolean, for which <code>true</code> * represents <code>fluid.logLevel.INFO</code> and <code>false</code> represents <code>fluid.logLevel.IMPORTANT</code> (the default), * or else any other member of the structure <code>fluid.logLevel</code> * Messages whose priority is strictly less than the current logging level will not be shown*/ fluid.setLogging = function (enabled) { var logLevel; if (typeof enabled === "boolean") { logLevel = fluid.logLevel[enabled? "INFO" : "IMPORTANT"]; } else if (fluid.isLogLevel(enabled)) { logLevel = enabled; } else { fluid.fail("Unrecognised fluid logging level ", enabled); } logLevelStack.unshift(logLevel); }; fluid.setLogLevel = fluid.setLogging; /** Undo the effect of the most recent "setLogging", returning the logging system to its previous state **/ fluid.popLogging = function () { return logLevelStack.length === 1? logLevelStack[0] : logLevelStack.shift(); }; /** Actually do the work of logging <code>args</code> to the environment's console. If the standard "console" * stream is available, the message will be sent there - otherwise either the * YAHOO logger or the Opera "postError" stream will be used. On capable environments (those other than * IE8 or IE9) the entire argument set will be dispatched to the logger - otherwise they will be flattened into * a string first, destroying any information held in non-primitive values. */ fluid.doLog = function (args) { var str = args.join(""); if (typeof (console) !== "undefined") { if (console.debug) { console.debug.apply(console, args); } else if (typeof (console.log) === "function") { console.log.apply(console, args); } else { console.log(str); // this branch executes on old IE, fully synthetic console.log } } else if (typeof (YAHOO) !== "undefined") { YAHOO.log(str); } else if (typeof (opera) !== "undefined") { opera.postError(str); } }; /** Log a message to a suitable environmental console. If the first argument to fluid.log is * one of the members of the <code>fluid.logLevel</code> structure, this will be taken as the priority * of the logged message - else if will default to <code>fluid.logLevel.INFO</code>. If the logged message * priority does not exceed that set by the most recent call to the <code>fluid.setLogging</code> function, * the message will not appear. */ fluid.log = function (/* message /*, ... */) { var directArgs = fluid.makeArray(arguments); var userLogLevel = fluid.logLevel.INFO; if (fluid.isLogLevel(directArgs[0])) { userLogLevel = directArgs.shift(); } if (fluid.passLogLevel(userLogLevel)) { var arg0 = fluid.renderTimestamp(new Date()) + ": "; var args = [arg0].concat(directArgs); fluid.doLog(args); } }; // Functional programming utilities. /** A basic utility that returns its argument unchanged */ fluid.identity = function (arg) { return arg; }; // Framework and instantiation functions. /** Returns true if the argument is a value other than null or undefined **/ fluid.isValue = function (value) { return value !== undefined && value !== null; }; /** Returns true if the argument is a primitive type **/ fluid.isPrimitive = function (value) { var valueType = typeof (value); return !value || valueType === "string" || valueType === "boolean" || valueType === "number" || valueType === "function"; }; /** Determines whether the supplied object is an array. The strategy used is an optimised * approach taken from an earlier version of jQuery - detecting whether the toString() version * of the object agrees with the textual form [object Array], or else whether the object is a * jQuery object (the most common source of "fake arrays"). */ fluid.isArrayable = function (totest) { return totest && (totest.jquery || Object.prototype.toString.call(totest) === "[object Array]"); }; /** Determines whether the supplied object is a plain JSON-forming container - that is, it is either a plain Object * or a plain Array */ fluid.isPlainObject = function (totest) { if (!totest) { return false; // FLUID-5172 - on IE8 the line below produces [object Object] rather than [object Null] or [object Undefined] } var string = Object.prototype.toString.call(totest); return string === "[object Array]" || string === "[object Object]"; }; fluid.isDOMNode = function (obj) { // This could be more sound, but messy: // http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object // The real problem is browsers like IE6, 7 and 8 which still do not feature a "constructor" property on DOM nodes return obj && typeof (obj.nodeType) === "number"; }; fluid.isDOMish = function (obj) { return fluid.isDOMNode(obj) || obj.jquery; }; fluid.isComponent = function (obj) { // TODO: improve this strategy in time - we may want to actually use a constructor-based test when we can drop IE8 return obj && obj.typeName && obj.id; }; /** Return an empty container as the same type as the argument (either an * array or hash */ fluid.freshContainer = function (tocopy) { return fluid.isArrayable(tocopy) ? [] : {}; }; /** Performs a deep copy (clone) of its argument **/ fluid.copy = function (tocopy) { if (fluid.isPrimitive(tocopy)) { return tocopy; } return $.extend(true, fluid.freshContainer(tocopy), tocopy); }; /** Corrected version of jQuery makeArray that returns an empty array on undefined rather than crashing. * We don't deal with as many pathological cases as jQuery **/ fluid.makeArray = function (arg) { var togo = []; if (arg !== null && arg !== undefined) { if (fluid.isPrimitive(arg) || typeof(arg.length) !== "number") { togo.push(arg); } else { for (var i = 0; i < arg.length; ++ i) { togo[i] = arg[i]; } } } return togo; }; function transformInternal(source, togo, key, args) { var transit = source[key]; for (var j = 0; j < args.length - 1; ++j) { transit = args[j + 1](transit, key); } togo[key] = transit; } /** Return a list or hash of objects, transformed by one or more functions. Similar to * jQuery.map, only will accept an arbitrary list of transformation functions and also * works on non-arrays. * @param source {Array or Object} The initial container of objects to be transformed. * @param fn1, fn2, etc. {Function} An arbitrary number of optional further arguments, * all of type Function, accepting the signature (object, index), where object is the * list member to be transformed, and index is its list index. Each function will be * applied in turn to each list member, which will be replaced by the return value * from the function. * @return The finally transformed list, where each member has been replaced by the * original member acted on by the function or functions. */ fluid.transform = function (source) { var togo = fluid.freshContainer(source); if (fluid.isArrayable(source)) { for (var i = 0; i < source.length; ++i) { transformInternal(source, togo, i, arguments); } } else { for (var key in source) { transformInternal(source, togo, key, arguments); } } return togo; }; /** Better jQuery.each which works on hashes as well as having the arguments * the right way round. * @param source {Arrayable or Object} The container to be iterated over * @param func {Function} A function accepting (value, key) for each iterated * object. */ fluid.each = function (source, func) { if (fluid.isArrayable(source)) { for (var i = 0; i < source.length; ++i) { func(source[i], i); } } else { for (var key in source) { func(source[key], key); } } }; fluid.make_find = function (find_if) { var target = find_if ? false : undefined; return function (source, func, deffolt) { var disp; if (fluid.isArrayable(source)) { for (var i = 0; i < source.length; ++i) { disp = func(source[i], i); if (disp !== target) { return find_if ? source[i] : disp; } } } else { for (var key in source) { disp = func(source[key], key); if (disp !== target) { return find_if ? source[key] : disp; } } } return deffolt; }; }; /** Scan through a list or hash of objects, terminating on the first member which * matches a predicate function. * @param source {Arrayable or Object} The list or hash of objects to be searched. * @param func {Function} A predicate function, acting on a member. A predicate which * returns any value which is not <code>undefined</code> will terminate * the search. The function accepts (object, index). * @param deflt {Object} A value to be returned in the case no predicate function matches * a list member. The default will be the natural value of <code>undefined</code> * @return The first return value from the predicate function which is not <code>undefined</code> */ fluid.find = fluid.make_find(false); /** The same signature as fluid.find, only the return value is the actual element for which the * predicate returns a value different from <code>false</code> */ fluid.find_if = fluid.make_find(true); /** Scan through a list of objects, "accumulating" a value over them * (may be a straightforward "sum" or some other chained computation). "accumulate" is the name derived * from the C++ STL, other names for this algorithm are "reduce" or "fold". * @param list {Array} The list of objects to be accumulated over. * @param fn {Function} An "accumulation function" accepting the signature (object, total, index) where * object is the list member, total is the "running total" object (which is the return value from the previous function), * and index is the index number. * @param arg {Object} The initial value for the "running total" object. * @return {Object} the final running total object as returned from the final invocation of the function on the last list member. */ fluid.accumulate = function (list, fn, arg) { for (var i = 0; i < list.length; ++i) { arg = fn(list[i], arg, i); } return arg; }; /** Scan through a list or hash of objects, removing those which match a predicate. Similar to * jQuery.grep, only acts on the list in-place by removal, rather than by creating * a new list by inclusion. * @param source {Array|Object} The list or hash of objects to be scanned over. * @param fn {Function} A predicate function determining whether an element should be * removed. This accepts the standard signature (object, index) and returns a "truthy" * result in order to determine that the supplied object should be removed from the list. * @param target {Array|Object} (optional) A target object of the same type as <code>source</code>, which will * receive any objects removed from it. * @return <code>target</code>, containing the removed elements, if it was supplied, or else <code>source</code> * modified by the operation of removing the matched elements. */ fluid.remove_if = function (source, fn, target) { if (fluid.isArrayable(source)) { for (var i = source.length - 1; i >= 0; --i) { if (fn(source[i], i)) { if (target) { target.unshift(source[i]); } source.splice(i, 1); } } } else { for (var key in source) { if (fn(source[key], key)) { if (target) { target[key] = source[key]; } delete source[key]; } } } return target || source; }; /** Fills an array of given size with copies of a value or result of a function invocation * @param n {Number} The size of the array to be filled * @param generator {Object|Function} Either a value to be replicated or function to be called * @param applyFunc {Boolean} If true, treat the generator value as a function to be invoked with * argument equal to the index position */ fluid.generate = function (n, generator, applyFunc) { var togo = []; for (var i = 0; i < n; ++ i) { togo[i] = applyFunc? generator(i) : generator; } return togo; }; /** Returns an array of size count, filled with increasing integers, starting at 0 or at the index specified by first. * @param count {Number} Size of the filled array to be returned * @param first {Number} (optional, defaults to 0) First element to appear in the array */ fluid.iota = function (count, first) { first = first || 0; var togo = []; for (var i = 0; i < count; ++i) { togo[togo.length] = first++; } return togo; }; /** Extracts a particular member from each top-level member of a container, returning a new container of the same type * @param holder {Array|Object} The container to be filtered * @param name {String|Array of String} An EL path to be fetched from each top-level member */ fluid.getMembers = function (holder, name) { return fluid.transform(holder, function(member) { return fluid.get(member, name); }); }; /** Accepts an object to be filtered, and a list of keys. Either all keys not present in * the list are removed, or only keys present in the list are returned. * @param toFilter {Array|Object} The object to be filtered - this will be NOT modified by the operation (current implementation * passes through $.extend shallow algorithm) * @param keys {Array of String} The list of keys to operate with * @param exclude {boolean} If <code>true</code>, the keys listed are removed rather than included * @return the filtered object (the same object that was supplied as <code>toFilter</code> */ fluid.filterKeys = function (toFilter, keys, exclude) { return fluid.remove_if($.extend({}, toFilter), function (value, key) { return exclude ^ ($.inArray(key, keys) === -1); }); }; /** A convenience wrapper for <code>fluid.filterKeys</code> with the parameter <code>exclude</code> set to <code>true</code> * Returns the supplied object with listed keys removed */ fluid.censorKeys = function (toCensor, keys) { return fluid.filterKeys(toCensor, keys, true); }; // TODO: This is not as clever an idea as we think it is - this typically inner-loop function will optimise badly due to closure fluid.makeFlatten = function (index) { return function (obj) { var togo = []; fluid.each(obj, function (/* value, key */) { togo.push(arguments[index]); }); return togo; }; }; /** Return the keys in the supplied object as an array **/ fluid.keys = fluid.makeFlatten(1); /** Return the values in the supplied object as an array **/ fluid.values = fluid.makeFlatten(0); /** * Searches through the supplied object, and returns <code>true</code> if the supplied value * can be found */ fluid.contains = function (obj, value) { return obj ? (fluid.isArrayable(obj) ? $.inArray(value, obj) !== -1 : fluid.find(obj, function (thisValue) { if (value === thisValue) { return true; } })) : undefined; }; /** * Searches through the supplied object for the first value which matches the one supplied. * @param obj {Object} the Object to be searched through * @param value {Object} the value to be found. This will be compared against the object's * member using === equality. * @return {String} The first key whose value matches the one supplied, or <code>null</code> if no * such key is found. */ fluid.keyForValue = function (obj, value) { return fluid.find(obj, function (thisValue, key) { if (value === thisValue) { return key; } }); }; /** * This method is now deprecated and will be removed in a future release of Infusion. * See fluid.keyForValue instead. */ fluid.findKeyInObject = fluid.keyForValue; /** Converts an array into an object whose keys are the elements of the array, each with the value "true" */ fluid.arrayToHash = function (array) { var togo = {}; fluid.each(array, function (el) { togo[el] = true; }); return togo; }; /** * Clears an object or array of its contents. For objects, each property is deleted. * * @param {Object|Array} target the target to be cleared */ fluid.clear = function (target) { if (fluid.isArrayable(target)) { target.length = 0; } else { for (var i in target) { delete target[i]; } } }; /** * @param boolean ascending <code>true</code> if a comparator is to be returned which * sorts strings in descending order of length */ fluid.compareStringLength = function (ascending) { return ascending ? function (a, b) { return a.length - b.length; } : function (a, b) { return b.length - a.length; }; }; fluid.logLevelsSpec = { "FATAL": 0, "FAIL": 5, "WARN": 10, "IMPORTANT": 12, // The default logging "off" level - corresponds to the old "false" "INFO": 15, // The default logging "on" level - corresponds to the old "true" "TRACE": 20 }; /** A structure holding all supported log levels as supplied as a possible first argument to fluid.log * Members with a higher value of the "priority" field represent lower priority logging levels */ // Moved down here since it uses fluid.transform on startup fluid.logLevel = fluid.transform(fluid.logLevelsSpec, function (value, key) { return {type: "fluid.marker", value: key, priority: value}; }); var logLevelStack = [fluid.logLevel.IMPORTANT]; // The stack of active logging levels, with the current level at index 0 /** A set of special "marker values" used in signalling in function arguments and return values, * to partially compensate for JavaScript's lack of distinguished types. These should never appear * in JSON structures or other kinds of static configuration. An API specifically documents if it * accepts or returns any of these values, and if so, what its semantic is - most are of private * use internal to the framework **/ /** A special "marker object" representing that a distinguished * (probably context-dependent) value should be substituted. */ fluid.VALUE = {type: "fluid.marker", value: "VALUE"}; /** A special "marker object" representing that no value is present (where * signalling using the value "undefined" is not possible - e.g. the return value from a "strategy") */ fluid.NO_VALUE = {type: "fluid.marker", value: "NO_VALUE"}; /** A marker indicating that a value requires to be expanded after component construction begins **/ fluid.EXPAND = {type: "fluid.marker", value: "EXPAND"}; /** A marker indicating that a value requires to be expanded immediately **/ fluid.EXPAND_NOW = {type: "fluid.marker", value: "EXPAND_NOW"}; /** Determine whether an object is any marker, or a particular marker - omit the * 2nd argument to detect any marker */ fluid.isMarker = function (totest, type) { if (!totest || typeof (totest) !== "object" || totest.type !== "fluid.marker") { return false; } if (!type) { return true; } return totest.value === type.value; }; // Model functions fluid.model = {}; // cannot call registerNamespace yet since it depends on fluid.model /** Copy a source "model" onto a target **/ fluid.model.copyModel = function (target, source) { fluid.clear(target); $.extend(true, target, source); }; /** Parse an EL expression separated by periods (.) into its component segments. * @param {String} EL The EL expression to be split * @return {Array of String} the component path expressions. * TODO: This needs to be upgraded to handle (the same) escaping rules (as RSF), so that * path segments containing periods and backslashes etc. can be processed, and be harmonised * with the more complex implementations in fluid.pathUtil(data binding). */ fluid.model.parseEL = function (EL) { return EL === "" ? [] : String(EL).split("."); }; /** Compose an EL expression from two separate EL expressions. The returned * expression will be the one that will navigate the first expression, and then * the second, from the value reached by the first. Either prefix or suffix may be * the empty string **/ fluid.model.composePath = function (prefix, suffix) { return prefix === "" ? suffix : (suffix === "" ? prefix : prefix + "." + suffix); }; /** Compose any number of path segments, none of which may be empty **/ fluid.model.composeSegments = function () { return fluid.makeArray(arguments).join("."); }; /** Helpful alias for old-style API **/ fluid.path = fluid.model.composeSegments; fluid.composePath = fluid.model.composePath; // unsupported, NON-API function fluid.requireDataBinding = function () { fluid.fail("Please include DataBinding.js in order to operate complex model accessor configuration"); }; fluid.model.setWithStrategy = fluid.model.getWithStrategy = fluid.requireDataBinding; // unsupported, NON-API function fluid.model.resolvePathSegment = function (root, segment, create, origEnv) { if (!origEnv && root.resolvePathSegment) { return root.resolvePathSegment(segment); } if (create && root[segment] === undefined) { // This optimisation in this heavily used function has a fair effect return root[segment] = {}; // jshint ignore:line } return root[segment]; }; // unsupported, NON-API function fluid.model.pathToSegments = function (EL, config) { var parser = config && config.parser ? config.parser.parse : fluid.model.parseEL; var segs = typeof(EL) === "number" || typeof(EL) === "string" ? parser(EL) : EL; return segs; }; // Overall strategy skeleton for all implementations of fluid.get/set fluid.model.accessImpl = function (root, EL, newValue, config, initSegs, returnSegs, traverser) { var segs = fluid.model.pathToSegments(EL, config); var initPos = 0; if (initSegs) { initPos = initSegs.length; segs = initSegs.concat(segs); } var uncess = newValue === fluid.NO_VALUE ? 0 : 1; root = traverser(root, segs, initPos, config, uncess); if (newValue === fluid.NO_VALUE || newValue === fluid.VALUE) { // get or custom return returnSegs ? {root: root, segs: segs} : root; } else { // set root[segs[segs.length - 1]] = newValue; } }; // unsupported, NON-API function fluid.model.accessSimple = function (root, EL, newValue, environment, initSegs, returnSegs) { return fluid.model.accessImpl(root, EL, newValue, environment, initSegs, returnSegs, fluid.model.traverseSimple); }; // unsupported, NON-API function fluid.model.traverseSimple = function (root, segs, initPos, environment, uncess) { var origEnv = environment; var limit = segs.length - uncess; for (var i = 0; i < limit; ++i) { if (!root) { return root; } var segment = segs[i]; if (environment && environment[segment]) { root = environment[segment]; } else { root = fluid.model.resolvePathSegment(root, segment, uncess === 1, origEnv); } environment = null; } return root; }; fluid.model.setSimple = function (root, EL, newValue, environment, initSegs) { fluid.model.accessSimple(root, EL, newValue, environment, initSegs, false); }; /** Optimised version of fluid.get for uncustomised configurations **/ fluid.model.getSimple = function (root, EL, environment, initSegs) { if (EL === null || EL === undefined || EL.length === 0) { return root; } return fluid.model.accessSimple(root, EL, fluid.NO_VALUE, environment, initSegs, false); }; // unsupported, NON-API function // Returns undefined to signal complex configuration which needs to be farmed out to DataBinding.js // any other return represents an environment value AND a simple configuration we can handle here fluid.decodeAccessorArg = function (arg3) { return (!arg3 || arg3 === fluid.model.defaultGetConfig || arg3 === fluid.model.defaultSetConfig) ? null : (arg3.type === "environment" ? arg3.value : undefined); }; fluid.set = function (root, EL, newValue, config, initSegs) { var env = fluid.decodeAccessorArg(config); if (env === undefined) { fluid.model.setWithStrategy(root, EL, newValue, config, initSegs); } else { fluid.model.setSimple(root, EL, newValue, env, initSegs); } }; /** Evaluates an EL expression by fetching a dot-separated list of members * recursively from a provided root. * @param root The root data structure in which the EL expression is to be evaluated * @param {string/array} EL The EL expression to be evaluated, or an array of path segments * @param config An optional configuration or environment structure which can customise the fetch operation * @return The fetched data value. */ fluid.get = function (root, EL, config, initSegs) { var env = fluid.decodeAccessorArg(config); return env === undefined ? fluid.model.getWithStrategy(root, EL, config, initSegs) : fluid.model.accessImpl(root, EL, fluid.NO_VALUE, env, null, false, fluid.model.traverseSimple); }; // This backward compatibility will be maintained for a number of releases, probably until Fluid 2.0 fluid.model.setBeanValue = fluid.set; fluid.model.getBeanValue = fluid.get; fluid.getGlobalValue = function (path, env) { if (path) { env = env || fluid.environment; return fluid.get(fluid.global, path, {type: "environment", value: env}); } }; /** * Allows for the binding to a "this-ist" function * @param {Object} obj, "this-ist" object to bind to * @param {Object} fnName, the name of the function to call * @param {Object} args, arguments to call the function with */ fluid.bind = function (obj, fnName, args) { return obj[fnName].apply(obj, fluid.makeArray(args)); }; /** * Allows for the calling of a function from an EL expression "functionPath", with the arguments "args", scoped to an framework version "environment". * @param {Object} functionPath - An EL expression * @param {Object} args - An array of arguments to be applied to the function, specified in functionPath * @param {Object} environment - (optional) The object to scope the functionPath to (typically the framework root for version control) */ fluid.invokeGlobalFunction = function (functionPath, args, environment) { var func = fluid.getGlobalValue(functionPath, environment); if (!func) { fluid.fail("Error invoking global function: " + functionPath + " could not be located"); } else { // FLUID-4915: Fixes an issue for IE8 by defaulting to an empty array when args are falsey. return func.apply(null, args || []); } }; /** Registers a new global function at a given path */ fluid.registerGlobalFunction = function (functionPath, func, env) { env = env || fluid.environment; fluid.set(fluid.global, functionPath, func, {type: "environment", value: env}); }; fluid.setGlobalValue = fluid.registerGlobalFunction; /** Ensures that an entry in the global namespace exists. If it does not, a new entry is created as {} and returned. If an existing * value is found, it is returned instead **/ fluid.registerNamespace = function (naimspace, env) { env = env || fluid.environment; var existing = fluid.getGlobalValue(naimspace, env); if (!existing) { existing = {}; fluid.setGlobalValue(naimspace, existing, env); } return existing; }; // stubs for two functions in FluidDebugging.js fluid.dumpEl = fluid.identity; fluid.renderTimestamp = fluid.identity; /*** The Model Events system. ***/ fluid.registerNamespace("fluid.event"); fluid.generateUniquePrefix = function () { return (Math.floor(Math.random() * 1e12)).toString(36) + "-"; }; var fluid_prefix = fluid.generateUniquePrefix(); fluid.fluidInstance = fluid_prefix; var fluid_guid = 1; /** Allocate an string value that will be very likely unique within this Fluid scope (frame or process) **/ fluid.allocateGuid = function () { return fluid_prefix + (fluid_guid++); }; fluid.event.identifyListener = function (listener, soft) { if (typeof(listener) !== "string" && !listener.$$fluid_guid && !soft) { listener.$$fluid_guid = fluid.allocateGuid(); } return listener.$$fluid_guid; }; // unsupported, NON-API function fluid.event.impersonateListener = function (origListener, newListener) { fluid.event.identifyListener(origListener); newListener.$$fluid_guid = origListener.$$fluid_guid; }; // unsupported, NON-API function fluid.event.mapPriority = function (priority, count) { // TODO: This should respect both priority and count by a bit-partitioning scheme return (priority === null || priority === undefined ? count : (priority === "last" ? Number.MAX_VALUE : (priority === "first" ? -Number.MAX_VALUE : -priority))); }; // unsupported, NON-API function fluid.priorityComparator = function (recA, recB) { return recA.priority - recB.priority; }; // unsupported, NON-API function fluid.event.sortListeners = function (listeners) { var togo = []; fluid.each(listeners, function (oneNamespace) { var headHard; // notify only the first listener with hard namespace - or else all if all are soft for (var i = 0; i < oneNamespace.length; ++ i) { var thisListener = oneNamespace[i]; if (!thisListener.softNamespace && !headHard) { headHard = thisListener; } } if (headHard) { togo.push(headHard); } else { togo = togo.concat(oneNamespace); } }); return togo.sort(fluid.priorityComparator); }; // unsupported, non-API function fluid.event.invokeListener = function (listener, args) { if (typeof(listener) === "string") { listener = fluid.event.resolveListener({globalName: listener}); // just resolves globals } return listener.apply(null, args); }; // unsupported, NON-API function fluid.event.resolveListener = function (listener) { if (listener.globalName) { var listenerFunc = fluid.getGlobalValue(listener.globalName); if (!listenerFunc) { fluid.fail("Unable to look up name " + listener.globalName + " as a global function"); } else { listener = listenerFunc; } } return listener; }; /** Generate a name for a component for debugging purposes */ fluid.nameComponent = function (that) { return that ? "component with typename " + that.typeName + " and id " + that.id : "[unknown component]"; }; fluid.event.nameEvent = function (that, eventName) { return eventName + " of " + fluid.nameComponent(that); }; /** Construct an "event firer" object which can be used to register and deregister * listeners, to which "events" can be fired. These events consist of an arbitrary * function signature. General documentation on the Fluid events system is at * http://wiki.fluidproject.org/display/fluid/The+Fluid+Event+System . * @param {Object} options - A structure to configure this event firer. Supported fields: * {String} name - a name for this firer * {Boolean} preventable - If <code>true</code> the return value of each handler will * be checked for <code>false</code> in which case further listeners will be shortcircuited, and this * will be the return value of fire() */ fluid.makeEventFirer = function (options) { options = options || {}; var name = options.name || "<anonymous>"; var that; function fireToListeners(listeners, args, wrapper) { if (!listeners || that.destroyed) { return; } fluid.log(fluid.logLevel.TRACE, "Firing event " + name + " to list of " + listeners.length + " listeners"); for (var i = 0; i < listeners.length; ++i) { var lisrec = listeners[i]; lisrec.listener = fluid.event.resolveListener(lisrec.listener); var listener = lisrec.listener; if (lisrec.predicate && !lisrec.predicate(listener, args)) { continue; } var value; var ret = (wrapper ? wrapper(listener) : listener).apply(null, args); if (options.preventable && ret === false || that.destroyed) { value = false; } if (value !== undefined) { return value; } } } var identify = fluid.event.identifyListener; var lazyInit = function () { // Lazy init function to economise on object references for events which are never listened to that.listeners = {}; that.byId = {}; that.sortedListeners = []; that.addListener = function (listener, namespace, predicate, priority, softNamespace) { if (that.destroyed) { fluid.fail("Cannot add listener to destroyed event firer " + that.name); } if (!listener) { return; } if (typeof(listener) === "string") { listener = {globalName: listener}; } var id = identify(listener); namespace = namespace || id; var record = {listener: listener, predicate: predicate, namespace: namespace, softNamespace: softNamespace, priority: fluid.event.mapPriority(priority, that.sortedListeners.length)}; that.byId[id] = record; var thisListeners = (that.listeners[namespace] = fluid.makeArray(that.listeners[namespace])); thisListeners[softNamespace ? "push" : "unshift"] (record); that.sortedListeners = fluid.event.sortListeners(that.listeners); }; that.addListener.apply(null, arguments); }; that = { eventId: fluid.allocateGuid(), name: name, ownerId: options.ownerId, typeName: "fluid.event.firer", destroy: function () { that.destroyed = true; }, addListener: function () { lazyInit.apply(null, arguments); }, removeListener: function (listener) { if (!that.listeners) { return; } var namespace, id, record; if (typeof (listener) === "string") { namespace = listener; record = that.listeners[namespace]; if (!record) { return; } } else if (typeof(listener) === "function") { id = identify(listener, true); if (!id) { fluid.fail("Cannot remove unregistered listener function ", listener, " from event " + that.name); } } var rec = that.byId[id]; var softNamespace = rec && rec.softNamespace; namespace = namespace || (rec && rec.namespace) || id; delete that.byId[id]; record = that.listeners[namespace]; if (!record) { return; } if (softNamespace) { fluid.remove_if(record, function (thisLis) { return thisLis.listener.$$fluid_guid === id; }); } else { record.shift(); } if (record.length === 0) { delete that.listeners[namespace]; } that.sortedListeners = fluid.event.sortListeners(that.listeners); }, // NB - this method exists only to support the old ChangeApplier. It will be removed along with it. fireToListeners: function (listeners, args, wrapper) { return fireToListeners(listeners, args, wrapper); }, fire: function () { return fireToListeners(that.sortedListeners, arguments); } }; return that; }; /** Fire the specified event with supplied arguments. This call is an optimisation utility * which handles the case where the firer has not been instantiated (presumably as a result * of having no listeners registered) */ fluid.fireEvent = function (component, path, args) { var firer = fluid.get(component, path); if (firer) { firer.fire.apply(null, fluid.makeArray(args)); } }; // unsupported, NON-API function fluid.event.addListenerToFirer = function (firer, value, namespace, wrapper) { wrapper = wrapper || fluid.identity; if (fluid.isArrayable(value)) { for (var i = 0; i < value.length; ++i) { fluid.event.addListenerToFirer(firer, value[i], namespace, wrapper); } } else if (typeof (value) === "function" || typeof (value) === "string") { wrapper(firer).addListener(value, namespace); } else if (value && typeof (value) === "object") { wrapper(firer).addListener(value.listener, namespace || value.namespace, value.predicate, value.priority, value.softNamespace); } }; // unsupported, NON-API function - non-IOC passthrough fluid.event.resolveListenerRecord = function (records) { return { records: records }; }; fluid.expandOptions = function (material) { fluid.fail("fluid.expandOptions could not be loaded - please include FluidIoC.js in order to operate IoC-driven event with descriptor " + material); }; // unsupported, NON-API function fluid.mergeListeners = function (that, events, listeners) { fluid.each(listeners, function (value, key) { var firer, namespace; if (key.charAt(0) === "{") { firer = fluid.expandOptions(key, that); if (!firer) { fluid.fail("Error in listener record: key " + key + " could not be looked up to an event firer - did you miss out \"events.\" when referring to an event firer?"); } } else { var keydot = key.indexOf("."); if (keydot !== -1) { namespace = key.substring(keydot + 1); key = key.substring(0, keydot); } if (!events[key]) { fluid.fail("Listener registered for event " + key + " which is not defined for this component"); } firer = events[key]; } var record = fluid.event.resolveListenerRecord(value, that, key, namespace, true); fluid.event.addListenerToFirer(firer, record.records, namespace, record.adderWrapper); }); }; // unsupported, NON-API function fluid.eventFromRecord = function (eventSpec, eventKey, that) { var isIoCEvent = eventSpec && (typeof (eventSpec) !== "string" || eventSpec.charAt(0) === "{"); var event; if (isIoCEvent) { if (!fluid.event.resolveEvent) { fluid.fail("fluid.event.resolveEvent could not be loaded - please include FluidIoC.js in order to operate IoC-driven event with descriptor ", eventSpec); } else { event = fluid.event.resolveEvent(that, eventKey, eventSpec); } } else { event = fluid.makeEventFirer({ name: fluid.event.nameEvent(that, eventKey), preventable: eventSpec === "preventable", ownerId: that.id }); } return event; }; // unsupported, NON-API function - this is patched from FluidIoC.js fluid.instantiateFirers = function (that, options) { fluid.each(options.events, function (eventSpec, eventKey) { that.events[eventKey] = fluid.eventFromRecord(eventSpec, eventKey, that); }); }; // unsupported, NON-API function fluid.mergeListenerPolicy = function (target, source, key) { if (typeof (key) !== "string") { fluid.fail("Error in listeners declaration - the keys in this structure must resolve to event names - got " + key + " from ", source); } // cf. triage in mergeListeners var hasNamespace = key.charAt(0) !== "{" && key.indexOf(".") !== -1; return hasNamespace ? (source || target) : fluid.arrayConcatPolicy(target, source); }; // unsupported, NON-API function fluid.makeMergeListenersPolicy = function (merger) { return function (target, source) { target = target || {}; fluid.each(source, function (listeners, key) { target[key] = merger(target[key], listeners, key); }); return target; }; }; /** Removes duplicated and empty elements from an already sorted array **/ fluid.unique = function (array) { return fluid.remove_if(array, function (element, i) { return !element || i > 0 && element === array[i - 1]; }); }; fluid.arrayConcatPolicy = function (target, source) { return fluid.makeArray(target).concat(fluid.makeArray(source)); }; /*** DEFAULTS AND OPTIONS MERGING SYSTEM ***/ /** Create a "type tag" component with no state but simply a type name and id. The most * minimal form of Fluid component */ fluid.typeTag = function (name) { return name ? { typeName: name, id: fluid.allocateGuid() } : null; }; // Definitions for ThreadLocals, the static and dynamic environment - lifted here from // FluidIoC.js so that we can issue calls to fluid.describeActivity for debugging purposes // in the core framework fluid.staticEnvironment = fluid.typeTag("fluid.staticEnvironment"); // unsupported, non-API function fluid.singleThreadLocal = function (initFunc) { var value = initFunc(); return function (newValue) { return newValue === undefined ? value : value = newValue; }; }; // Currently we only support single-threaded environments - ensure that this function // is not used on startup so it can be successfully monkey-patched // unsupported, non-API function fluid.threadLocal = fluid.singleThreadLocal; // unsupported, non-API function fluid.globalThreadLocal = fluid.threadLocal(function () { return fluid.typeTag("fluid.dynamicEnvironment"); }); var gradeTick = 1; // tick counter for managing grade cache invalidation var gradeTickStore = {}; var defaultsStore = {}; var resolveGradesImpl = function (gs, gradeNames, base) { var raw = true; if (base) { raw = gradeNames.length === 1; // We are just resolving a single grade and populating the cache } else { gradeNames = fluid.makeArray(gradeNames); } fluid.each(gradeNames, function (gradeName) { if (gradeName && !gs.gradeHash[gradeName]) { var isDynamic = gradeName.charAt(0) === "{"; var options = (isDynamic ? null : (raw ? fluid.rawDefaults(gradeName) : fluid.getGradedDefaults(gradeName))) || {}; var thisTick = gradeTickStore[gradeName] || (gradeTick - 1); // a nonexistent grade is recorded as previous to current gs.lastTick = Math.max(gs.lastTick, thisTick); gs.gradeHash[gradeName] = true; gs.gradeChain.push(gradeName); gs.optionsChain.push(options); var oGradeNames = fluid.makeArray(options.gradeNames); for (var i = 0; i < oGradeNames.length; ++ i) { var oGradeName = oGradeNames[i]; var isAuto = oGradeName === "autoInit"; if (!raw) { if (!gs.gradeHash[oGradeName] && !isAuto) { gs.gradeHash[oGradeName] = true; // these have already been resolved gs.gradeChain.push(oGradeName); } } else if (!isAuto) { resolveGradesImpl(gs, oGradeName); } } } }); return gs; }; // unsupported, NON-API function fluid.resolveGradeStructure = function (defaultName, gradeNames) { var gradeStruct = { lastTick: 0, gradeChain: [], gradeHash: {}, optionsChain: [] }; // stronger grades appear to the left in defaults - dynamic grades are stronger still - FLUID-5085 return resolveGradesImpl(gradeStruct, (fluid.makeArray(gradeNames).reverse() || []).concat([defaultName]), true); }; var mergedDefaultsCache = {}; // unsupported, NON-API function fluid.gradeNamesToKey = function (defaultName, gradeNames) { return defaultName + "|" + gradeNames.join("|"); }; fluid.hasGrade = function (options, gradeName) { return !options || !options.gradeNames ? false : fluid.contains(options.gradeNames, gradeName); }; // unsupported, NON-API function fluid.resolveGrade = function (defaults, defaultName, gradeNames) { var gradeStruct = fluid.resolveGradeStructure(defaultName, gradeNames); var mergeArgs = gradeStruct.optionsChain.reverse(); var mergePolicy = {}; for (var i = 0; i < mergeArgs.length; ++ i) { if (mergeArgs[i] && mergeArgs[i].mergePolicy) { mergePolicy = $.extend(true, mergePolicy, mergeArgs[i].mergePolicy); } } mergeArgs = [mergePolicy, {}].concat(mergeArgs); var mergedDefaults = fluid.merge.apply(null, mergeArgs); mergedDefaults.gradeNames = gradeStruct.gradeChain; if (fluid.hasGrade(defaults, "autoInit")) { mergedDefaults.gradeNames.push("autoInit"); } return {defaults: mergedDefaults, lastTick: gradeStruct && gradeStruct.lastTick}; }; // unsupported, NON-API function fluid.getGradedDefaults = function (defaultName, gradeNames) { gradeNames = fluid.makeArray(gradeNames); var key = fluid.gradeNamesToKey(defaultName, gradeNames); var mergedDefaults = mergedDefaultsCache[key]; if (mergedDefaults) { var lastTick = 0; // check if cache should be invalidated through real latest tick being later than the one stored var searchGrades = mergedDefaults.defaults.gradeNames || []; for (var i = 0; i < searchGrades.length; ++ i) { lastTick = Math.max(lastTick, gradeTickStore[searchGrades[i]] || 0); } if (lastTick > mergedDefaults.lastTick) { fluid.log("Clearing cache for component " + defaultName + " with gradeNames ", searchGrades); mergedDefaults = null; } } if (!mergedDefaults) { var defaults = fluid.rawDefaults(defaultName); if (!defaults) { return defaults; } mergedDefaults = mergedDefaultsCache[key] = fluid.resolveGrade(defaults, defaultName, gradeNames); } return mergedDefaults.defaults; }; // unsupported, NON-API function // Modify supplied options record to include "componentSource" annotation required by FLUID-5082 // TODO: This function really needs to act recursively in order to catch listeners registered for subcomponents fluid.annotateListeners = function (componentName, options) { if (options.listeners) { options.listeners = fluid.transform(options.listeners, function (record) { var togo = fluid.makeArray(record); return fluid.transform(togo, function (onerec) { if (!fluid.isPrimitive(onerec)) { onerec.componentSource = componentName; } return onerec; }); }); } }; // unsupported, NON-API function fluid.rawDefaults = function (componentName, options) { if (options === undefined) { return defaultsStore[componentName]; } else { fluid.pushActivity("registerDefaults", "registering defaults for grade %componentName with options %options", {componentName: componentName, options: options}); var optionsCopy = fluid.expandCompact ? fluid.expandCompact(options) : fluid.copy(options); fluid.annotateListeners(componentName, optionsCopy); defaultsStore[componentName] = optionsCopy; gradeTickStore[componentName] = gradeTick++; fluid.popActivity(); } }; // unsupported, NON-API function fluid.doIndexDefaults = function (defaultName, defaults, index, indexSpec) { var requiredGrades = fluid.makeArray(indexSpec.gradeNames); for (var i = 0; i < requiredGrades.length; ++ i) { if (!fluid.hasGrade(defaults, requiredGrades[i])) { return; } } var indexFunc = typeof(indexSpec.indexFunc) === "function" ? indexSpec.indexFunc : fluid.getGlobalValue(indexSpec.indexFunc); var keys = indexFunc(defaults) || []; for (var j = 0; j < keys.length; ++ j) { (index[keys[j]] = index[keys[j]] || []).push(defaultName); } }; /** Evaluates an index specification over all the defaults records registered into the system. * @param indexName {String} The name of this index record (currently ignored) * @param indexSpec {Object} Specification of the index to be performed - fields: * gradeNames: {String/Array of String} List of grades that must be matched by this indexer * indexFunc: {String/Function} An index function which accepts a defaults record and returns a list of keys * @return A structure indexing keys to lists of matched gradenames */ // The expectation is that this function is extremely rarely used with respect to registration of defaults // in the system, so currently we do not make any attempts to cache the results. The field "indexName" is // supplied in case a future implementation chooses to implement caching fluid.indexDefaults = function (indexName, indexSpec) { var index = {}; for (var defaultName in defaultsStore) { var defaults = fluid.getGradedDefaults(defaultName); fluid.doIndexDefaults(defaultName, defaults, index, indexSpec); } return index; }; /** * Retrieves and stores a component's default settings centrally. * @param {String} componentName the name of the component * @param {Object} (optional) an container of key/value pairs to set */ fluid.defaults = function (componentName, options) { if (options === undefined) { return fluid.getGradedDefaults(componentName); } else { if (options && options.options) { fluid.fail("Probable error in options structure for " + componentName + " with option named \"options\" - perhaps you meant to write these options at top level in fluid.defaults? - ", options); } fluid.rawDefaults(componentName, options); if (fluid.hasGrade(options, "autoInit")) { fluid.makeComponent(componentName, fluid.getGradedDefaults(componentName)); } } }; fluid.makeComponent = function (componentName, options) { if (!options.gradeNames || options.gradeNames.length === 0) { fluid.fail("Cannot autoInit component " + componentName + " which does not have any gradeNames defined"); } else if (!options.initFunction) { var blankGrades = []; for (var i = 0; i < options.gradeNames.length; ++ i) { var gradeName = options.gradeNames[i]; var defaults = fluid.rawDefaults(gradeName); if (!defaults && gradeName !== "autoInit") { blankGrades.push(gradeName); } } if (blankGrades.length === 0) { fluid.fail("Cannot autoInit component " + componentName + " which does not have an initFunction defined"); } else { fluid.fail("The grade hierarchy of component with typeName " + componentName + " is incomplete - it inherits from the following grade(s): " + blankGrades.join(", ") + " for which the grade definitions are corrupt or missing. Please check the files which might include these " + "grades and ensure they are readable and have been loaded by this instance of Infusion"); } } var creator = function () { return fluid.initComponent(componentName, arguments); }; var existing = fluid.getGlobalValue(componentName); if (existing) { $.extend(creator, existing); } fluid.setGlobalValue(componentName, creator); }; fluid.makeComponents = function (components) { fluid.each(components, function (value, key) { var options = { gradeNames: fluid.makeArray(value).concat(["autoInit"]) }; fluid.defaults(key, options); }); }; // Cheapskate implementation which avoids dependency on DataBinding.js fluid.model.mergeModel = function (target, source) { if (!fluid.isPrimitive(target)) { var copySource = fluid.copy(source); $.extend(true, source, target); $.extend(true, source, copySource); } return source; }; var emptyPolicy = {}; // unsupported, NON-API function fluid.derefMergePolicy = function (policy) { return (policy? policy["*"]: emptyPolicy) || emptyPolicy; }; // unsupported, NON-API function fluid.compileMergePolicy = function (mergePolicy) { var builtins = {}, defaultValues = {}; var togo = {builtins: builtins, defaultValues: defaultValues}; if (!mergePolicy) { return togo; } fluid.each(mergePolicy, function (value, key) { var parsed = {}, builtin = true; if (typeof(value) === "function") { parsed.func = value; } else if (typeof(value) === "object") { parsed = value; } else if (!fluid.isDefaultValueMergePolicy(value)) { var split = value.split(/\s*,\s*/); for (var i = 0; i < split.length; ++ i) { parsed[split[i]] = true; } } else { // Convert to ginger self-reference - NB, this can only be parsed by IoC fluid.set(defaultValues, key, "{that}.options." + value); togo.hasDefaults = true; builtin = false; } if (builtin) { fluid.set(builtins, fluid.composePath(key, "*"), parsed); } }); return togo; }; // TODO: deprecate this method of detecting default value merge policies before 1.6 in favour of // explicit typed records a la ModelTransformations // unsupported, NON-API function fluid.isDefaultValueMergePolicy = function (policy) { return typeof(policy) === "string" && (policy.indexOf(",") === -1 && !/replace|preserve|nomerge|noexpand/.test(policy)); }; // unsupported, NON-API function fluid.mergeOneImpl = function (thisTarget, thisSource, j, sources, newPolicy, i, segs) { var togo = thisTarget; var primitiveTarget = fluid.isPrimitive(thisTarget); if (thisSource !== undefined) { if (!newPolicy.func && thisSource !== null && fluid.isPlainObject(thisSource) && !fluid.isDOMish(thisSource) && thisSource !== fluid.VALUE && !newPolicy.preserve && !newPolicy.nomerge) { if (primitiveTarget) { togo = thisTarget = fluid.freshContainer(thisSource); } // recursion is now external? We can't do it from here since sources are not all known // options.recurse(thisTarget, i + 1, segs, sources, newPolicyHolder, options); } else { sources[j] = undefined; if (newPolicy.func) { togo = newPolicy.func.call(null, thisTarget, thisSource, segs[i - 1], segs, i); // NB - change in this mostly unused argument } else { togo = fluid.isValue(thisTarget) && newPolicy.preserve ? fluid.model.mergeModel(thisTarget, thisSource) : thisSource; } } } return togo; }; // NB - same quadratic worry about these as in FluidIoC in the case the RHS trundler is live - // since at each regeneration step driving the RHS we are discarding the "cursor arguments" these // would have to be regenerated at each step - although in practice this can only happen once for // each object for all time, since after first resolution it will be concrete. function regenerateCursor (source, segs, limit, sourceStrategy) { for (var i = 0; i < limit; ++ i) { source = sourceStrategy(source, segs[i], i, fluid.makeArray(segs)); // copy for FLUID-5243 } return source; } function regenerateSources (sources, segs, limit, sourceStrategies) { var togo = []; for (var i = 0; i < sources.length; ++ i) { var thisSource = regenerateCursor(sources[i], segs, limit, sourceStrategies[i]); if (thisSource !== undefined) { togo.push(thisSource); } } return togo; } // unsupported, NON-API function fluid.fetchMergeChildren = function (target, i, segs, sources, mergePolicy, options) { /* unused parameter left for documentation purposes */ // jshint ignore:line var thisPolicy = fluid.derefMergePolicy(mergePolicy); for (var j = sources.length - 1; j >= 0; -- j) { // this direction now irrelevant - control is in the strategy var source = sources[j]; // NB - this detection relies on strategy return being complete objects - which they are // although we need to set up the roots separately. We need to START the process of evaluating each // object root (sources) COMPLETELY, before we even begin! Even if the effect of this is to cause a // dispatch into ourselves almost immediately. We can do this because we can take control over our // TARGET objects and construct them early. Even if there is a self-dispatch, it will be fine since it is // DIRECTED and so will not trouble our "slow" detection of properties. After all self-dispatches end, control // will THEN return to "evaluation of arguments" (expander blocks) and only then FINALLY to this "slow" // traversal of concrete properties to do the final merge. if (source !== undefined) { // This use of function creation within a loop is acceptable since // the function does not attempt to close directly over the loop counter fluid.each(source, function (newSource, name) { if (!target.hasOwnProperty(name)) { // only request each new target key once -- all sources will be queried per strategy segs[i] = name; options.strategy(target, name, i + 1, segs, sources, mergePolicy); } }); /* function in loop */ //jshint ignore:line if (thisPolicy.replace) { // this branch primarily deals with a policy of replace at the root break; } } } return target; }; // A special marker object which will be placed at a current evaluation point in the tree in order // to protect against circular evaluation fluid.inEvaluationMarker = {"__CURRENTLY_IN_EVALUATION__": true}; fluid.destroyedMarker = {"__COMPONENT_DESTROYED__": true}; // A path depth above which the core "process strategies" will bail out, assuming that the // structure has become circularly linked. Helpful in environments such as Firebug which will // kill the browser process if they happen to be open when a stack overflow occurs. Also provides // a more helpful diagnostic. fluid.strategyRecursionBailout = 50; // unsupported, NON-API function fluid.makeMergeStrategy = function (options) { var strategy = function (target, name, i, segs, sources, policy) { if (i > fluid.strategyRecursionBailout) { fluid.fail("Overflow/circularity in options merging, current path is ", segs, " at depth " , i, " - please protect components from merging using the \"nomerge\" merge policy"); } if (fluid.isPrimitive(target)) { // For "use strict" return undefined; // Review this after FLUID-4925 since the only trigger is in slow component lookahead } if (fluid.isTracing) { fluid.tracing.pathCount.push(fluid.path(segs.slice(0, i))); } var oldTarget; if (target.hasOwnProperty(name)) { // bail out if our work has already been done oldTarget = target[name]; if (!options.evaluateFully) { // see notes on this hack in "initter" - early attempt to deal with FLUID-4930 return oldTarget; } } else { // This is hardwired here for performance reasons - no need to protect deeper strategies target[name] = fluid.inEvaluationMarker; } if (sources === undefined) { // recover our state in case this is an external entry point segs = fluid.makeArray(segs); // avoid trashing caller's segs sources = regenerateSources(options.sources, segs, i - 1, options.sourceStrategies); policy = regenerateCursor(options.mergePolicy, segs, i - 1, fluid.concreteTrundler); } // var thisPolicy = fluid.derefMergePolicy(policy); var newPolicyHolder = fluid.concreteTrundler(policy, name); var newPolicy = fluid.derefMergePolicy(newPolicyHolder); var start, limit, mul; if (newPolicy.replace) { start = 1 - sources.length; limit = 0; mul = -1; /* on one line for easier visual comparison of the two algorithms */ // jshint ignore:line } else { start = 0; limit = sources.length - 1; mul = +1; /* on one line for easier visual comparison of the two algorithms */ // jshint ignore:line } var newSources = []; var thisTarget; for (var j = start; j <= limit; ++j) { // TODO: try to economise on this array and on gaps var k = mul * j; var thisSource = options.sourceStrategies[k](sources[k], name, i, segs); // Run the RH algorithm in "driving" mode if (thisSource !== undefined) { newSources[k] = thisSource; if (oldTarget === undefined) { if (mul === -1) { // if we are going backwards, it is "replace" thisTarget = target[name] = thisSource; break; } else { // write this in early, since early expansions may generate a trunk object which is written in to by later ones thisTarget = target[name] = fluid.mergeOneImpl(thisTarget, thisSource, j, newSources, newPolicy, i, segs, options); } } } } if (oldTarget !== undefined) { thisTarget = oldTarget; } if (newSources.length > 0) { if (!fluid.isPrimitive(thisTarget)) { fluid.fetchMergeChildren(thisTarget, i, segs, newSources, newPolicyHolder, options); } } if (oldTarget === undefined && newSources.length === 0) { delete target[name]; // remove the evaluation marker - nothing to evaluate } return thisTarget; }; options.strategy = strategy; return strategy; }; // A simple stand-in for "fluid.get" where the material is covered by a single strategy fluid.driveStrategy = function (root, pathSegs, strategy) { pathSegs = fluid.makeArray(pathSegs); for (var i = 0; i < pathSegs.length; ++ i) { if (!root) { return undefined; } root = strategy(root, pathSegs[i], i + 1, pathSegs); } return root; }; // A very simple "new inner trundler" that just performs concrete property access // Note that every "strategy" is also a "trundler" of this type, considering just the first two arguments fluid.concreteTrundler = function (source, seg) { return !source? undefined : source[seg]; }; /** Merge a collection of options structures onto a target, following an optional policy. * This method is now used only for the purpose of merging "dead" option documents in order to * cache graded component defaults. Component option merging is now performed by the * fluid.makeMergeOptions pathway which sets up a deferred merging process. This function * will not be removed in the Fluid 2.0 release but it is recommended that users not call it * directly. * The behaviour of this function is explained more fully on * the page http://wiki.fluidproject.org/display/fluid/Options+Merging+for+Fluid+Components . * @param policy {Object/String} A "policy object" specifiying the type of merge to be performed. * If policy is of type {String} it should take on the value "replace" representing * a static policy. If it is an * Object, it should contain a mapping of EL paths onto these String values, representing a * fine-grained policy. If it is an Object, the values may also themselves be EL paths * representing that a default value is to be taken from that path. * @param options1, options2, .... {Object} an arbitrary list of options structure which are to * be merged together. These will not be modified. */ fluid.merge = function (policy /*, ... sources */) { var sources = Array.prototype.slice.call(arguments, 1); var compiled = fluid.compileMergePolicy(policy).builtins; var options = fluid.makeMergeOptions(compiled, sources, {}); options.initter(); return options.target; }; // unsupported, NON-API function fluid.simpleGingerBlock = function (source, recordType) { var block = { target: source, simple: true, strategy: fluid.concreteTrundler, initter: fluid.identity, recordType: recordType, priority: fluid.mergeRecordTypes[recordType] }; return block; }; // unsupported, NON-API function fluid.makeMergeOptions = function (policy, sources, userOptions) { var options = { mergePolicy: policy, sources: sources }; options = $.extend(options, userOptions); options.target = options.target || fluid.freshContainer(options.sources[0]); options.sourceStrategies = options.sourceStrategies || fluid.generate(options.sources.length, fluid.concreteTrundler); options.initter = function () { // This hack is necessary to ensure that the FINAL evaluation doesn't balk when discovering a trunk path which was already // visited during self-driving via the expander. This bi-modality is sort of rubbish, but we currently don't have "room" // in the strategy API to express when full evaluation is required - and the "flooding API" is not standardised. See FLUID-4930 options.evaluateFully = true; fluid.fetchMergeChildren(options.target, 0, [], options.sources, options.mergePolicy, options); }; fluid.makeMergeStrategy(options); return options; }; // unsupported, NON-API function fluid.transformOptions = function (options, transRec) { fluid.expect("Options transformation record", ["transformer", "config"], transRec); var transFunc = fluid.getGlobalValue(transRec.transformer); return transFunc.call(null, options, transRec.config); }; // unsupported, NON-API function fluid.findMergeBlocks = function (mergeBlocks, recordType) { return fluid.remove_if(fluid.makeArray(mergeBlocks), function (block) { return block.recordType !== recordType; }); }; // unsupported, NON-API function fluid.transformOptionsBlocks = function (mergeBlocks, transformOptions, recordTypes) { fluid.each(recordTypes, function (recordType) { var blocks = fluid.findMergeBlocks(mergeBlocks, recordType); fluid.each(blocks, function (block) { block[block.simple? "target": "source"] = fluid.transformOptions(block.source, transformOptions); }); }); }; // unsupported, NON-API function fluid.deliverOptionsStrategy = fluid.identity; fluid.computeComponentAccessor = fluid.identity; fluid.computeDynamicComponents = fluid.identity; // The (extensible) types of merge record the system supports, with the weakest records first fluid.mergeRecordTypes = { defaults: 0, localOptions: 50, // provisional defaultValueMerge: 100, subcomponentRecord: 200, distribution: 300, // rendererDecorator: 400, // TODO, these are probably honoured already as "user" user: 500, demands: 600 // and above }; /** Delete the value in the supplied object held at the specified path * @param target {Object} The object holding the value to be deleted (possibly empty) * @param path {String/Array of String} the path of the value to be deleted */ fluid.destroyValue = function (target, path) { if (target) { fluid.model.applyChangeRequest(target, {type: "DELETE", path: path}); } }; /** * Merges the component's declared defaults, as obtained from fluid.defaults(), * with the user's specified overrides. * * @param {Object} that the instance to attach the options to * @param {String} componentName the unique "name" of the component, which will be used * to fetch the default options from store. By recommendation, this should be the global * name of the component's creator function. * @param {Object} userOptions the user-specified configuration options for this component */ // unsupported, NON-API function fluid.mergeComponentOptions = function (that, componentName, userOptions, localOptions) { var rawDefaults = fluid.rawDefaults(componentName); var defaults = fluid.getGradedDefaults(componentName, rawDefaults && rawDefaults.gradeNames ? null : localOptions.gradeNames); var sharedMergePolicy = {}; var mergeBlocks = []; if (fluid.expandComponentOptions) { mergeBlocks = mergeBlocks.concat(fluid.expandComponentOptions(sharedMergePolicy, defaults, userOptions, that)); } else { mergeBlocks = mergeBlocks.concat([fluid.simpleGingerBlock(defaults, "defaults"), fluid.simpleGingerBlock(userOptions, "user")]); } var options = {}; // ultimate target var sourceStrategies = [], sources = []; var baseMergeOptions = { target: options, sourceStrategies: sourceStrategies }; // Called both from here and from IoC whenever there is a change of block content or arguments which // requires them to be resorted and rebound var updateBlocks = function () { mergeBlocks.sort(fluid.priorityComparator); sourceStrategies.length = 0; sources.length = 0; fluid.each(mergeBlocks, function (block) { sourceStrategies.push(block.strategy); sources.push(block.target); }); }; updateBlocks(); var mergeOptions = fluid.makeMergeOptions(sharedMergePolicy, sources, baseMergeOptions); mergeOptions.mergeBlocks = mergeBlocks; mergeOptions.updateBlocks = updateBlocks; mergeOptions.destroyValue = function (path) { // This method is a temporary hack to assist FLUID-5091 for (var i = 0; i < mergeBlocks.length; ++ i) { fluid.destroyValue(mergeBlocks[i].target, path); } fluid.destroyValue(baseMergeOptions.target, path); }; var compiledPolicy; var mergePolicy; function computeMergePolicy() { // Decode the now available mergePolicy mergePolicy = fluid.driveStrategy(options, "mergePolicy", mergeOptions.strategy); mergePolicy = $.extend({}, fluid.rootMergePolicy, mergePolicy); compiledPolicy = fluid.compileMergePolicy(mergePolicy); // TODO: expandComponentOptions has already put some builtins here - performance implications of the now huge // default mergePolicy material need to be investigated as well as this deep merge $.extend(true, sharedMergePolicy, compiledPolicy.builtins); // ensure it gets broadcast to all sharers } computeMergePolicy(); if (compiledPolicy.hasDefaults) { if (fluid.generateExpandBlock) { mergeBlocks.push(fluid.generateExpandBlock({ options: compiledPolicy.defaultValues, recordType: "defaultValueMerge", priority: fluid.mergeRecordTypes.defaultValueMerge }, that, {})); updateBlocks(); } else { fluid.fail("Cannot operate mergePolicy ", mergePolicy, " for component ", that, " without including FluidIoC.js"); } } that.options = options; var optionsNickName = fluid.driveStrategy(options, "nickName", mergeOptions.strategy); that.nickName = optionsNickName || fluid.computeNickName(that.typeName); fluid.driveStrategy(options, "gradeNames", mergeOptions.strategy); fluid.deliverOptionsStrategy(that, options, mergeOptions); // do this early to broadcast and receive "distributeOptions" var transformOptions = fluid.driveStrategy(options, "transformOptions", mergeOptions.strategy); if (transformOptions) { fluid.transformOptionsBlocks(mergeBlocks, transformOptions, ["user", "subcomponentRecord"]); updateBlocks(); // because the possibly simple blocks may have changed target } fluid.computeComponentAccessor(that); if (!baseMergeOptions.target.mergePolicy) { computeMergePolicy(); } return mergeOptions; }; // The Fluid Component System proper // The base system grade definitions fluid.defaults("fluid.function", {}); /** Invoke a global function by name and named arguments. A courtesy to allow declaratively encoded function calls * to use named arguments rather than bare arrays. * @param name {String} A global name which can be resolved to a Function. The defaults for this name must * resolve onto a grade including "fluid.function". The defaults record should also contain an entry * <code>argumentMap</code>, a hash of argument names onto indexes. * @param spec {Object} A named hash holding the argument values to be sent to the function. These will be looked * up in the <code>argumentMap</code> and resolved into a flat list of arguments. * @return {Any} The return value from the function */ fluid.invokeGradedFunction = function (name, spec) { var defaults = fluid.defaults(name); if (!defaults || !defaults.argumentMap || !fluid.hasGrade(defaults, "fluid.function")) { fluid.fail("Cannot look up name " + name + " to a function with registered argumentMap - got defaults ", defaults); } var args = []; fluid.each(defaults.argumentMap, function (value, key) { args[value] = spec[key]; }); return fluid.invokeGlobalFunction(name, args); }; fluid.lifecycleFunctions = { preInitFunction: true, postInitFunction: true, finalInitFunction: true }; fluid.rootMergePolicy = $.extend({ gradeNames: fluid.arrayConcatPolicy, distributeOptions: fluid.arrayConcatPolicy, transformOptions: "replace" }, fluid.transform(fluid.lifecycleFunctions, function () { return fluid.mergeListenerPolicy; })); fluid.defaults("fluid.littleComponent", { gradeNames: ["autoInit"], initFunction: "fluid.initLittleComponent", mergePolicy: fluid.rootMergePolicy, argumentMap: { options: 0 } }); fluid.defaults("fluid.eventedComponent", { gradeNames: ["fluid.littleComponent", "autoInit"], events: { // Five standard lifecycle points common to all components onCreate: null, onAttach: null, // onAttach, onClear are only fired for IoC-configured components onClear: null, onDestroy: null, afterDestroy: null }, mergePolicy: { listeners: fluid.makeMergeListenersPolicy(fluid.mergeListenerPolicy) } }); /** A special "marker object" which is recognised as one of the arguments to * fluid.initSubcomponents. This object is recognised by reference equality - * where it is found, it is replaced in the actual argument position supplied * to the specific subcomponent instance, with the particular options block * for that instance attached to the overall "that" object. * NOTE: The use of this marker has been deprecated as of the Fluid 1.4 release in * favour of the contextual EL path "{options}" - it will be removed in a future * release of the framework. */ fluid.COMPONENT_OPTIONS = {type: "fluid.marker", value: "COMPONENT_OPTIONS"}; /** Construct a dummy or "placeholder" subcomponent, that optionally provides empty * implementations for a set of methods. */ // TODO: this method is inefficient and inappropriate, should simply discard options entirely pending review fluid.emptySubcomponent = function (options) { var that = fluid.typeTag("fluid.emptySubcomponent"); that.options = options || {}; that.options.gradeNames = [that.typeName]; options = fluid.makeArray(options); for (var i = 0; i < options.length; ++i) { that[options[i]] = fluid.identity; } return that; }; /** Compute a "nickname" given a fully qualified typename, by returning the last path * segment. */ fluid.computeNickName = function (typeName) { var segs = fluid.model.parseEL(typeName); return segs[segs.length - 1]; }; /** A combined "component and grade name" which allows type tags to be declaratively constructed * from options material. Any component found bearing this grade will be instantiated first amongst * its set of siblings, since it is likely to bear a context-forming type name */ fluid.typeFount = function (options) { var that = fluid.initLittleComponent("fluid.typeFount", options); return fluid.typeTag(that.options.targetTypeName); }; /** * Creates a new "little component": a that-ist object with options merged into it by the framework. * This method is a convenience for creating small objects that have options but don't require full * View-like features such as the DOM Binder or events * * @param {Object} name the name of the little component to create * @param {Object} options user-supplied options to merge with the defaults */ // NOTE: the 3rd argument localOptions is NOT to be advertised as part of the stable API, it is present // just to allow backward compatibility whilst grade specifications are not mandatory - similarly for 4th arg "receiver" fluid.initLittleComponent = function (name, userOptions, localOptions, receiver) { var that = fluid.typeTag(name); localOptions = localOptions || {gradeNames: "fluid.littleComponent"}; that.destroy = fluid.makeRootDestroy(that); // overwritten by FluidIoC for constructed subcomponents var mergeOptions = fluid.mergeComponentOptions(that, name, userOptions, localOptions); var options = that.options; var evented = fluid.hasGrade(options, "fluid.eventedComponent"); if (evented) { that.events = {}; } // deliver to a non-IoC side early receiver of the component (currently only initView) (receiver || fluid.identity)(that, options, mergeOptions.strategy); fluid.computeDynamicComponents(that, mergeOptions); // TODO: ****THIS**** is the point we must deliver and suspend!! Construct the "component skeleton" first, and then continue // for as long as we can continue to find components. for (var i = 0; i < mergeOptions.mergeBlocks.length; ++ i) { mergeOptions.mergeBlocks[i].initter(); } mergeOptions.initter(); delete options.mergePolicy; fluid.initLifecycleFunctions(that); fluid.fireEvent(options, "preInitFunction", that); if (evented) { fluid.instantiateFirers(that, options); fluid.mergeListeners(that, that.events, options.listeners); } if (!fluid.hasGrade(options, "autoInit")) { fluid.clearLifecycleFunctions(options); } return that; }; // unsupported, NON-API function fluid.updateWithDefaultLifecycle = function (key, value, typeName) { var funcName = typeName + "." + key.substring(0, key.length - "function".length); var funcVal = fluid.getGlobalValue(funcName); if (typeof (funcVal) === "function") { value = fluid.makeArray(value); var existing = fluid.find(value, function (el) { var listener = el.listener || el; if (listener === funcVal || listener === funcName) { return true; } }); if (!existing) { value.push(funcVal); } } return value; }; // unsupported, NON-API function fluid.initLifecycleFunctions = function (that) { var gradeNames = that.options.gradeNames || []; fluid.each(fluid.lifecycleFunctions, function (func, key) { var value = that.options[key]; for (var i = gradeNames.length - 1; i >= 0; -- i) { // most specific grades are at front if (gradeNames[i] !== "autoInit") { value = fluid.updateWithDefaultLifecycle(key, value, gradeNames[i]); } } if (value) { that.options[key] = fluid.makeEventFirer({name: key, ownerId: that.id}); fluid.event.addListenerToFirer(that.options[key], value); } }); }; // unsupported, NON-API function fluid.clearLifecycleFunctions = function (options) { fluid.each(fluid.lifecycleFunctions, function (value, key) { delete options[key]; }); delete options.initFunction; }; fluid.diagnoseFailedView = fluid.identity; // unsupported, NON-API function fluid.makeRootDestroy = function (that) { return function () { fluid.fireEvent(that, "events.onClear", [that, "", null]); fluid.doDestroy(that); fluid.fireEvent(that, "events.afterDestroy", [that, "", null]); }; }; /** Returns <code>true</code> if the supplied reference holds a component which has been destroyed **/ fluid.isDestroyed = function (that) { return that.destroy === fluid.destroyedMarker; }; // unsupported, NON-API function fluid.doDestroy = function (that, name, parent) { fluid.fireEvent(that, "events.onDestroy", [that, name || "", parent]); that.destroy = fluid.destroyedMarker; for (var key in that.events) { if (key !== "afterDestroy" && typeof(that.events[key].destroy) === "function") { that.events[key].destroy(); } } if (that.applier) { // TODO: Break this out into the grade's destroyer that.applier.destroy(); } }; fluid.resolveReturnedPath = fluid.identity; // unsupported, NON-API function fluid.initComponent = function (componentName, initArgs) { var options = fluid.defaults(componentName); if (!options.gradeNames) { fluid.fail("Cannot initialise component " + componentName + " which has no gradeName registered"); } var args = [componentName].concat(fluid.makeArray(initArgs)); // TODO: support different initFunction variants var that; fluid.pushActivity("initComponent", "constructing component of type %componentName with arguments %initArgs", {componentName: componentName, initArgs: initArgs}); that = fluid.invokeGlobalFunction(options.initFunction, args); fluid.diagnoseFailedView(componentName, that, options, args); fluid.fireEvent(that.options, "postInitFunction", that); if (fluid.initDependents) { fluid.initDependents(that); } fluid.fireEvent(that.options, "finalInitFunction", that); fluid.clearLifecycleFunctions(that.options); fluid.fireEvent(that, "events.onCreate", that); fluid.popActivity(); return fluid.resolveReturnedPath(that.options.returnedPath, that) ? fluid.get(that, that.options.returnedPath) : that; }; // unsupported, NON-API function fluid.initSubcomponentImpl = function (that, entry, args) { var togo; if (typeof (entry) !== "function") { var entryType = typeof (entry) === "string" ? entry : entry.type; togo = entryType === "fluid.emptySubcomponent" ? fluid.emptySubcomponent(entry.options) : fluid.invokeGlobalFunction(entryType, args); } else { togo = entry.apply(null, args); } return togo; }; /** Initialise all the "subcomponents" which are configured to be attached to * the supplied top-level component, which share a particular "class name". This method * of instantiating components is deprecated and will be removed in favour of the automated * IoC system in the Fluid 2.0 release. * @param {Component} that The top-level component for which sub-components are * to be instantiated. It contains specifications for these subcomponents in its * <code>options</code> structure. * @param {String} className The "class name" or "category" for the subcomponents to * be instantiated. A class name specifies an overall "function" for a class of * subcomponents and represents a category which accept the same signature of * instantiation arguments. * @param {Array of Object} args The instantiation arguments to be passed to each * constructed subcomponent. These will typically be members derived from the * top-level <code>that</code> or perhaps globally discovered from elsewhere. One * of these arguments may be <code>fluid.COMPONENT_OPTIONS</code> in which case this * placeholder argument will be replaced by instance-specific options configured * into the member of the top-level <code>options</code> structure named for the * <code>className</code> * @return {Array of Object} The instantiated subcomponents, one for each member * of <code>that.options[className]</code>. */ fluid.initSubcomponents = function (that, className, args) { var entry = that.options[className]; if (!entry) { return; } var entries = fluid.makeArray(entry); var optindex = -1; var togo = []; args = fluid.makeArray(args); for (var i = 0; i < args.length; ++i) { if (args[i] === fluid.COMPONENT_OPTIONS) { optindex = i; } } for (i = 0; i < entries.length; ++i) { entry = entries[i]; if (optindex !== -1) { args[optindex] = entry.options; } togo[i] = fluid.initSubcomponentImpl(that, entry, args); } return togo; }; fluid.initSubcomponent = function (that, className, args) { return fluid.initSubcomponents(that, className, args)[0]; }; // ******* SELECTOR ENGINE ********* // selector regexps copied from jQuery - recent versions correct the range to start C0 // The initial portion of the main character selector "just add water" to add on extra // accepted characters, as well as the "\\\\." -> "\." portion necessary for matching // period characters escaped in selectors var charStart = "(?:[\\w\\u00c0-\\uFFFF*_-"; fluid.simpleCSSMatcher = { regexp: new RegExp("([#.]?)(" + charStart + "]|\\\\.)+)", "g"), charToTag: { "": "tag", "#": "id", ".": "clazz" } }; fluid.IoCSSMatcher = { regexp: new RegExp("([&#]?)(" + charStart + "]|\\.)+)", "g"), charToTag: { "": "context", "&": "context", "#": "id" } }; var childSeg = new RegExp("\\s*(>)?\\s*", "g"); // var whiteSpace = new RegExp("^\\w*$"); // Parses a selector expression into a data structure holding a list of predicates // 2nd argument is a "strategy" structure, e.g. fluid.simpleCSSMatcher or fluid.IoCSSMatcher // unsupported, non-API function fluid.parseSelector = function (selstring, strategy) { var togo = []; selstring = $.trim(selstring); //ws-(ss*)[ws/>] var regexp = strategy.regexp; regexp.lastIndex = 0; var lastIndex = 0; while (true) { var atNode = []; // a list of predicates at a particular node var first = true; while (true) { var segMatch = regexp.exec(selstring); if (!segMatch) { break; } if (segMatch.index !== lastIndex) { if (first) { fluid.fail("Error in selector string - cannot match child selector expression starting at " + selstring.substring(lastIndex)); } else { break; } } var thisNode = {}; var text = segMatch[2]; var targetTag = strategy.charToTag[segMatch[1]]; if (targetTag) { thisNode[targetTag] = text; } atNode[atNode.length] = thisNode; lastIndex = regexp.lastIndex; first = false; } childSeg.lastIndex = lastIndex; var fullAtNode = {predList: atNode}; var childMatch = childSeg.exec(selstring); if (!childMatch || childMatch.index !== lastIndex) { fluid.fail("Error in selector string - can not match child selector expression at " + selstring.substring(lastIndex)); } if (childMatch[1] === ">") { fullAtNode.child = true; } togo[togo.length] = fullAtNode; // >= test here to compensate for IE bug http://blog.stevenlevithan.com/archives/exec-bugs if (childSeg.lastIndex >= selstring.length) { break; } lastIndex = childSeg.lastIndex; regexp.lastIndex = childSeg.lastIndex; } return togo; }; // Message resolution and templating /** * Converts a string to a regexp with the specified flags given in parameters * @param {String} a string that has to be turned into a regular expression * @param {String} the flags to provide to the reg exp */ fluid.stringToRegExp = function (str, flags) { return new RegExp(str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"), flags); }; /** * Simple string template system. * Takes a template string containing tokens in the form of "%value". * Returns a new string with the tokens replaced by the specified values. * Keys and values can be of any data type that can be coerced into a string. Arrays will work here as well. * * @param {String} template a string (can be HTML) that contains tokens embedded into it * @param {object} values a collection of token keys and values */ fluid.stringTemplate = function (template, values) { var keys = fluid.keys(values); keys = keys.sort(fluid.compareStringLength()); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var re = fluid.stringToRegExp("%" + key, "g"); template = template.replace(re, values[key]); } return template; }; fluid.defaults("fluid.messageResolver", { gradeNames: ["fluid.littleComponent", "autoInit"], mergePolicy: { messageBase: "nomerge", parents: "nomerge" }, resolveFunc: fluid.stringTemplate, parseFunc: fluid.identity, messageBase: {}, parents: [] }); fluid.messageResolver.preInit = function (that) { that.messageBase = that.options.parseFunc(that.options.messageBase); that.lookup = function (messagecodes) { var resolved = fluid.messageResolver.resolveOne(that.messageBase, messagecodes); if (resolved === undefined) { return fluid.find(that.options.parents, function (parent) { return parent ? parent.lookup(messagecodes) : undefined; }); } else { return {template: resolved, resolveFunc: that.options.resolveFunc}; } }; that.resolve = function (messagecodes, args) { if (!messagecodes) { return "[No messagecodes provided]"; } messagecodes = fluid.makeArray(messagecodes); var looked = that.lookup(messagecodes); return looked ? looked.resolveFunc(looked.template, args) : "[Message string for key " + messagecodes[0] + " not found]"; }; }; // unsupported, NON-API function fluid.messageResolver.resolveOne = function (messageBase, messagecodes) { for (var i = 0; i < messagecodes.length; ++i) { var code = messagecodes[i]; var message = messageBase[code]; if (message !== undefined) { return message; } } }; /** Converts a data structure consisting of a mapping of keys to message strings, * into a "messageLocator" function which maps an array of message codes, to be * tried in sequence until a key is found, and an array of substitution arguments, * into a substituted message string. */ fluid.messageLocator = function (messageBase, resolveFunc) { var resolver = fluid.messageResolver({messageBase: messageBase, resolveFunc: resolveFunc}); return function (messagecodes, args) { return resolver.resolve(messagecodes, args); }; }; })(jQuery, fluid_2_0); ;/* Copyright 2007-2010 University of Cambridge Copyright 2007-2009 University of Toronto Copyright 2007-2009 University of California, Berkeley Copyright 2010 OCAD University Copyright 2010-2011 Lucendo Development Ltd. Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ var fluid_2_0 = fluid_2_0 || {}; var fluid = fluid || fluid_2_0; (function ($, fluid) { "use strict"; /** Render a timestamp from a Date object into a helpful fixed format for debug logs to millisecond accuracy * @param date {Date} The date to be rendered * @return {String} A string format consisting of hours:minutes:seconds.millis for the datestamp padded to fixed with */ fluid.renderTimestamp = function (date) { var zeropad = function (num, width) { if (!width) { width = 2; } var numstr = (num === undefined ? "" : num.toString()); return "00000".substring(5 - width + numstr.length) + numstr; }; return zeropad(date.getHours()) + ":" + zeropad(date.getMinutes()) + ":" + zeropad(date.getSeconds()) + "." + zeropad(date.getMilliseconds(), 3); }; fluid.isTracing = false; fluid.registerNamespace("fluid.tracing"); fluid.tracing.pathCount = []; fluid.tracing.summarisePathCount = function (pathCount) { pathCount = pathCount || fluid.tracing.pathCount; var togo = {}; for (var i = 0; i < pathCount.length; ++ i) { var path = pathCount[i]; if (!togo[path]) { togo[path] = 1; } else { ++togo[path]; } } var toReallyGo = []; fluid.each(togo, function (el, path) { toReallyGo.push({path: path, count: el}); }); toReallyGo.sort(function (a, b) {return b.count - a.count;}); return toReallyGo; }; fluid.tracing.condensePathCount = function (prefixes, pathCount) { prefixes = fluid.makeArray(prefixes); var prefixCount = {}; fluid.each(prefixes, function(prefix) { prefixCount[prefix] = 0; }); var togo = []; fluid.each(pathCount, function (el) { var path = el.path; if (!fluid.find(prefixes, function(prefix) { if (path.indexOf(prefix) === 0) { prefixCount[prefix] += el.count; return true; } })) { togo.push(el); } }); fluid.each(prefixCount, function(count, path) { togo.unshift({path: path, count: count}); }); return togo; }; // Exception stripping code taken from https://github.com/emwendelin/javascript-stacktrace/blob/master/stacktrace.js // BSD licence, see header fluid.detectStackStyle = function (e) { var style = "other"; var stackStyle = { offset: 0 }; if (e["arguments"]) { style = "chrome"; } else if (typeof window !== "undefined" && window.opera && e.stacktrace) { style = "opera10"; } else if (e.stack) { style = "firefox"; // Detect FireFox 4-style stacks which are 1 level less deep stackStyle.offset = e.stack.indexOf("Trace exception") === -1? 1 : 0; } else if (typeof window !== "undefined" && window.opera && !("stacktrace" in e)) { //Opera 9- style = "opera"; } stackStyle.style = style; return stackStyle; }; fluid.obtainException = function () { try { throw new Error("Trace exception"); } catch (e) { return e; } }; var stackStyle = fluid.detectStackStyle(fluid.obtainException()); fluid.registerNamespace("fluid.exceptionDecoders"); fluid.decodeStack = function () { if (stackStyle.style !== "firefox") { return null; } var e = fluid.obtainException(); return fluid.exceptionDecoders[stackStyle.style](e); }; fluid.exceptionDecoders.firefox = function (e) { var lines = e.stack.replace(/(?:\n@:0)?\s+$/m, "").replace(/^\(/gm, "{anonymous}(").split("\n"); return fluid.transform(lines, function (line) { var atind = line.indexOf("@"); return atind === -1? [line] : [line.substring(atind + 1), line.substring(0, atind)]; }); }; // Main entry point for callers. // TODO: This infrastructure is several years old and probably still only works on Firefox if there fluid.getCallerInfo = function (atDepth) { atDepth = (atDepth || 3) - stackStyle.offset; var stack = fluid.decodeStack(); return stack? stack[atDepth][0] : null; }; /** Generates a string for padding purposes by replicating a character a given number of times * @param c {Character} A character to be used for padding * @param count {Integer} The number of times to repeat the character * @return A string of length <code>count</code> consisting of repetitions of the supplied character */ // UNOPTIMISED fluid.generatePadding = function (c, count) { var togo = ""; for (var i = 0; i < count; ++ i) { togo += c; } return togo; }; // Marker so that we can render a custom string for properties which are not direct and concrete fluid.SYNTHETIC_PROPERTY = {}; // utility to avoid triggering custom getter code which could throw an exception - e.g. express 3.x's request object fluid.getSafeProperty = function (obj, key) { var desc = Object.getOwnPropertyDescriptor(obj, key); // supported on all of our environments - is broken on IE8 return desc && !desc.get ? obj[key] : fluid.SYNTHETIC_PROPERTY; }; function printImpl (obj, small, options) { var big = small + options.indentChars, togo, isFunction = typeof(obj) === "function"; if (obj === null) { togo = "null"; } else if (obj === undefined) { togo = "undefined"; // NB - object invalid for JSON interchange } else if (obj === fluid.SYNTHETIC_PROPERTY) { togo = "[Synthetic property]"; } else if (fluid.isPrimitive(obj) && !isFunction) { togo = JSON.stringify(obj); } else { if ($.inArray(obj, options.stack) !== -1) { return "(CIRCULAR)"; // NB - object invalid for JSON interchange } options.stack.push(obj); var j = []; var i; if (fluid.isArrayable(obj)) { if (obj.length === 0) { togo = "[]"; } else { for (i = 0; i < obj.length; ++ i) { j[i] = printImpl(obj[i], big, options); } togo = "[\n" + big + j.join(",\n" + big) + "\n" + small + "]"; } } else { i = 0; togo = "{" + (isFunction ? " Function" : "") + "\n"; // NB - Function object invalid for JSON interchange for (var key in obj) { var value = fluid.getSafeProperty(obj, key); j[i++] = JSON.stringify(key) + ": " + printImpl(value, big, options); } togo += big + j.join(",\n" + big) + "\n" + small + "}"; } options.stack.pop(); } return togo; } /** Render a complex JSON object into a nicely indented format suitable for human readability. * @param obj {Object} The object to be rendered * @param options {Object} An options structure governing the rendering process. The only option which * is currently supported is <code>indent</code> holding the number of space characters to be used to * indent each level of containment. */ fluid.prettyPrintJSON = function (obj, options) { options = $.extend({indent: 4, stack: []}, options); options.indentChars = fluid.generatePadding(" ", options.indent); return printImpl(obj, "", options); }; /** * Dumps a DOM element into a readily recognisable form for debugging - produces a * "semi-selector" summarising its tag name, class and id, whichever are set. * * @param {jQueryable} element The element to be dumped * @return A string representing the element. */ fluid.dumpEl = function (element) { var togo; if (!element) { return "null"; } if (element.nodeType === 3 || element.nodeType === 8) { return "[data: " + element.data + "]"; } if (element.nodeType === 9) { return "[document: location " + element.location + "]"; } if (!element.nodeType && fluid.isArrayable(element)) { togo = "["; for (var i = 0; i < element.length; ++ i) { togo += fluid.dumpEl(element[i]); if (i < element.length - 1) { togo += ", "; } } return togo + "]"; } element = $(element); togo = element.get(0).tagName; if (element.id) { togo += "#" + element.id; } if (element.attr("class")) { togo += "." + element.attr("class"); } return togo; }; })(jQuery, fluid_2_0); ;/* Copyright 2011-2013 OCAD University Copyright 2010-2011 Lucendo Development Ltd. Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ var fluid_2_0 = fluid_2_0 || {}; (function ($, fluid) { "use strict"; /** The Fluid "IoC System proper" - resolution of references and * completely automated instantiation of declaratively defined * component trees */ // unsupported, non-API function // Currently still uses manual traversal - once we ban manually instantiated components, // it will use the instantiator's records instead. fluid.visitComponentChildren = function (that, visitor, options, path, i) { var instantiator = fluid.getInstantiator(that); for (var name in that) { var newPath = instantiator.composePath(path, name); var component = that[name]; // This entire algorithm is primitive and expensive and will be removed once we can abolish manual init components if (!fluid.isComponent(component) || (options.visited && options.visited[component.id])) {continue; } if (options.visited) { options.visited[component.id] = true; } if (visitor(component, name, newPath, path, i)) { return true; } if (!options.flat) { fluid.visitComponentChildren(component, visitor, options, newPath); } } }; // unsupported, non-API function fluid.getMemberNames = function (instantiator, thatStack) { var path = instantiator.idToPath(thatStack[thatStack.length - 1].id); var segs = fluid.model.parseEL(path); segs.unshift.apply(segs, fluid.generate(thatStack.length - segs.length, "")); return segs; }; // thatStack contains an increasing list of MORE SPECIFIC thats. // this visits all components starting from the current location (end of stack) // in visibility order up the tree. var visitComponents = function (instantiator, thatStack, visitor, options) { options = options || { visited: {}, flat: true, instantiator: instantiator }; var memberNames = fluid.getMemberNames(instantiator, thatStack); for (var i = thatStack.length - 1; i >= 0; --i) { var that = thatStack[i], path; if (that.typeName) { options.visited[that.id] = true; path = instantiator.idToPath[that.id]; if (visitor(that, memberNames[i], path, path, i)) { return; } } if (fluid.visitComponentChildren(that, visitor, options, path, i)) { return; } } }; fluid.mountStrategy = function (prefix, root, toMount) { var offset = prefix.length; return function (target, name, i, segs) { if (i <= prefix.length) { // Avoid OOB to not trigger deoptimisation! return; } for (var j = 0; j < prefix.length; ++ j) { if (segs[j] !== prefix[j]) { return; } } return toMount(target, name, i - prefix.length, segs.slice(offset)); }; }; // unsupported, NON-API function fluid.invokerFromRecord = function (invokerec, name, that) { fluid.pushActivity("makeInvoker", "beginning instantiation of invoker with name %name and record %record as child of %that", {name: name, record: invokerec, that: that}); var invoker = fluid.makeInvoker(that, invokerec, name); fluid.popActivity(); return invoker; }; // unsupported, NON-API function fluid.memberFromRecord = function (memberrec, name, that) { var value = fluid.expandOptions(memberrec, that, null, null, {freeRoot: true}); return value; }; // unsupported, NON-API function fluid.recordStrategy = function (that, options, optionsStrategy, recordPath, recordMaker, prefix) { prefix = prefix || []; return { strategy: function (target, name, i) { if (i !== 1) { return; } var record = fluid.driveStrategy(options, [recordPath, name], optionsStrategy); if (record === undefined) { return; } fluid.set(target, [name], fluid.inEvaluationMarker); var member = recordMaker(record, name, that); fluid.set(target, [name], member); return member; }, initter: function () { var records = fluid.driveStrategy(options, recordPath, optionsStrategy) || {}; for (var name in records) { fluid.getForComponent(that, prefix.concat([name])); } } }; }; // patch Fluid.js version for timing // unsupported, NON-API function fluid.instantiateFirers = function (that) { var shadow = fluid.shadowForComponent(that); var initter = fluid.get(shadow, ["eventStrategyBlock", "initter"]) || fluid.identity; initter(); }; // unsupported, NON-API function fluid.makeDistributionRecord = function (contextThat, sourceRecord, sourcePath, targetSegs, exclusions, offset, sourceType) { offset = offset || 0; sourceType = sourceType || "distribution"; var source = fluid.copy(fluid.get(sourceRecord, sourcePath)); fluid.each(exclusions, function (exclusion) { fluid.model.applyChangeRequest(source, {path: exclusion, type: "DELETE"}); }); var record = {options: {}}; var primitiveSource = fluid.isPrimitive(source); fluid.model.applyChangeRequest(record, {path: targetSegs, type: primitiveSource? "ADD": "MERGE", value: source}); return $.extend(record, {contextThat: contextThat, recordType: sourceType, priority: fluid.mergeRecordTypes.distribution + offset}); }; // unsupported, NON-API function // Part of the early "distributeOptions" workflow. Given the description of the blocks to be distributed, assembles "canned" records // suitable to be either registered into the shadow record for later or directly pushed to an existing component, as well as honouring // any "removeSource" annotations by removing these options from the source block. fluid.filterBlocks = function (contextThat, sourceBlocks, sourcePath, targetSegs, exclusions, removeSource) { var togo = [], offset = 0; fluid.each(sourceBlocks, function (block) { var source = fluid.get(block.source, sourcePath); if (source) { togo.push(fluid.makeDistributionRecord(contextThat, block.source, sourcePath, targetSegs, exclusions, offset++, block.recordType)); var rescued = $.extend({}, source); if (removeSource) { fluid.model.applyChangeRequest(block.source, {path: sourcePath, type: "DELETE"}); } fluid.each(exclusions, function (exclusion) { var orig = fluid.get(rescued, exclusion); fluid.set(block.source, sourcePath.concat(exclusion), orig); }); } }); return togo; }; // unsupported, NON-API function // TODO: This implementation is obviously poor and has numerous flaws fluid.matchIoCSelector = function (selector, thatStack, contextHashes, memberNames, i) { var thatpos = thatStack.length - 1; var selpos = selector.length - 1; while (true) { var mustMatchHere = thatpos === thatStack.length - 1 || selector[selpos].child; var that = thatStack[thatpos]; var selel = selector[selpos]; var match = true; for (var j = 0; j < selel.predList.length; ++j) { var pred = selel.predList[j]; if (pred.context && !(contextHashes[thatpos][pred.context] || memberNames[thatpos] === pred.context)) { match = false; break; } if (pred.id && that.id !== pred.id) { match = false; break; } } if (selpos === 0 && thatpos > i && mustMatchHere) { match = false; // child selector must exhaust stack completely - FLUID-5029 } if (match) { if (selpos === 0) { return true; } --thatpos; --selpos; } else { if (mustMatchHere) { return false; } else { --thatpos; } } if (thatpos < i) { return false; } } }; // Use this peculiar signature since the actual component and shadow itself may not exist yet. Perhaps clean up with FLUID-4925 fluid.noteCollectedDistribution = function (parentShadow, memberName, distribution) { fluid.model.setSimple(parentShadow, ["collectedDistributions", memberName, distribution.id], true); }; fluid.isCollectedDistribution = function (parentShadow, memberName, distribution) { return fluid.model.getSimple(parentShadow, ["collectedDistributions", memberName, distribution.id]); }; fluid.clearCollectedDistributions = function (parentShadow, memberName) { fluid.model.applyChangeRequest(parentShadow, {path: ["collectedDistributions", memberName], type: "DELETE"}); }; // unsupported, NON-API function fluid.collectDistributions = function (distributedBlocks, parentShadow, distribution, thatStack, contextHashes, memberNames, i) { var lastMember = memberNames[memberNames.length - 1]; if (!fluid.isCollectedDistribution(parentShadow, lastMember, distribution) && fluid.matchIoCSelector(distribution.selector, thatStack, contextHashes, memberNames, i)) { distributedBlocks.push.apply(distributedBlocks, distribution.blocks); fluid.noteCollectedDistribution(parentShadow, lastMember, distribution); } }; // Slightly silly function to clean up the "appliedDistributions" records. In general we need to be much more aggressive both // about clearing instantiation garbage (e.g. onCreate and most of the shadow) // as well as caching frequently-used records such as the "thatStack" which // would mean this function could be written in a sensible way fluid.registerCollectedClearer = function (shadow, parentShadow, memberName) { if (!shadow.collectedClearer && parentShadow) { shadow.collectedClearer = function () { fluid.clearCollectedDistributions(parentShadow, memberName); }; } }; // unsupported, NON-API function fluid.receiveDistributions = function (parentThat, gradeNames, memberName, that) { var instantiator = fluid.getInstantiator(parentThat || that); var thatStack = instantiator.getThatStack(parentThat || that); // most specific is at end var memberNames = fluid.getMemberNames(instantiator, thatStack); var distributedBlocks = []; var shadows = fluid.transform(thatStack, function (thisThat) { return instantiator.idToShadow[thisThat.id]; }); var parentShadow = shadows[shadows.length - (parentThat ? 1 : 2)]; var contextHashes = fluid.getMembers(shadows, "contextHash"); if (parentThat) { // if called before construction of component from embodyDemands - NB this path will be abolished/amalgamated memberNames.push(memberName); contextHashes.push(fluid.gradeNamesToHash(gradeNames)); thatStack.push(that); } else { fluid.registerCollectedClearer(shadows[shadows.length - 1], parentShadow, memberNames[memberNames.length - 1]); } // This use of function creation within a loop is acceptable since // the function does not attempt to close directly over the loop counter for (var i = 0; i < thatStack.length - 1; ++ i) { fluid.each(shadows[i].distributions, function (distribution) { fluid.collectDistributions(distributedBlocks, parentShadow, distribution, thatStack, contextHashes, memberNames, i); }); /* function in loop */ /* jshint ignore:line */ } return distributedBlocks; }; // unsupported, NON-API function // convert "preBlocks" as produced from fluid.filterBlocks into "real blocks" suitable to be used by the expansion machinery. fluid.applyDistributions = function (that, preBlocks, targetShadow) { var distributedBlocks = fluid.transform(preBlocks, function (preBlock) { return fluid.generateExpandBlock(preBlock, that, targetShadow.mergePolicy); }); var mergeOptions = targetShadow.mergeOptions; mergeOptions.mergeBlocks.push.apply(mergeOptions.mergeBlocks, distributedBlocks); mergeOptions.updateBlocks(); return distributedBlocks; }; // unsupported, NON-API function fluid.parseExpectedOptionsPath = function (path, role) { var segs = fluid.model.parseEL(path); if (segs.length > 1 && segs[0] !== "options") { fluid.fail("Error in options distribution path ", path, " - only " + role + " paths beginning with \"options\" are supported"); } return segs.slice(1); }; // unsupported, NON-API function fluid.isIoCSSSelector = function (context) { return context.indexOf(" ") !== -1; // simple-minded check for an IoCSS reference }; // unsupported, NON-API function fluid.pushDistributions = function (targetHead, selector, blocks) { var targetShadow = fluid.shadowForComponent(targetHead); var id = fluid.allocateGuid(); var distributions = (targetShadow.distributions = targetShadow.distributions || []); distributions.push({ id: id, // This id is used in clearDistributions - which itself currently only seems to appear in IoCTestUtils selector: selector, blocks: blocks }); return id; }; // unsupported, NON-API function fluid.clearDistributions = function (targetHead, id) { var targetShadow = fluid.shadowForComponent(targetHead); fluid.remove_if(targetShadow.distributions, function (distribution) { return distribution.id === id; }); }; // unsupported, NON-API function // Modifies a parsed selector to extra its head context which will be matched upwards fluid.extractSelectorHead = function (parsedSelector) { var predList = parsedSelector[0].predList; var context = predList[0].context; predList.length = 0; return context; }; fluid.undistributableOptions = ["gradeNames", "distributeOptions", "returnedPath", "argumentMap", "initFunction", "mergePolicy", "progressiveCheckerOptions"]; // automatically added to "exclusions" of every distribution // unsupported, NON-API function fluid.distributeOptions = function (that, optionsStrategy) { var records = fluid.makeArray(fluid.driveStrategy(that.options, "distributeOptions", optionsStrategy)); fluid.each(records, function (record) { var targetRef = fluid.parseContextReference(record.target); var targetComp, selector; if (fluid.isIoCSSSelector(targetRef.context)) { selector = fluid.parseSelector(targetRef.context, fluid.IoCSSMatcher); var headContext = fluid.extractSelectorHead(selector); if (headContext !== "that") { fluid.fail("Downwards options distribution not supported from component other than \"that\""); } targetComp = that; } else { targetComp = fluid.resolveContext(targetRef.context, that); if (!targetComp) { fluid.fail("Error in options distribution record ", record, " - could not resolve context selector {"+targetRef.context+"} to a root component"); } } var targetSegs = fluid.model.parseEL(targetRef.path); var preBlocks; if (record.record !== undefined) { preBlocks = [(fluid.makeDistributionRecord(that, record.record, [], targetSegs, [], 0))]; } else { var thatShadow = fluid.shadowForComponent(that); var source = fluid.parseContextReference(record.source || "{that}.options"); // TODO: This is probably not a sensible default if (source.context !== "that") { fluid.fail("Error in options distribution record ", record, " only a context of {that} is supported"); } var sourcePath = fluid.parseExpectedOptionsPath(source.path, "source"); var fullExclusions = fluid.makeArray(record.exclusions).concat(sourcePath.length === 0 ? fluid.undistributableOptions : []); var exclusions = fluid.transform(fullExclusions, function (exclusion) { return fluid.model.parseEL(exclusion); }); preBlocks = fluid.filterBlocks(that, thatShadow.mergeOptions.mergeBlocks, sourcePath, targetSegs, exclusions, record.removeSource); thatShadow.mergeOptions.updateBlocks(); // perhaps unnecessary } // TODO: inline material has to be expanded in its original context! if (selector) { fluid.pushDistributions(targetComp, selector, preBlocks); } else { // The component exists now, we must rebalance it var targetShadow = fluid.shadowForComponent(targetComp); fluid.applyDistributions(that, preBlocks, targetShadow); } }); }; // unsupported, NON-API function fluid.gradeNamesToHash = function (gradeNames) { var contextHash = {}; fluid.each(gradeNames, function (gradeName) { contextHash[gradeName] = true; contextHash[fluid.computeNickName(gradeName)] = true; }); return contextHash; }; // unsupported, NON-API function fluid.cacheShadowGrades = function (that, shadow) { var contextHash = fluid.gradeNamesToHash(that.options.gradeNames); contextHash[that.nickName] = true; shadow.contextHash = contextHash; }; // First sequence point where the mergeOptions strategy is delivered from Fluid.js - here we take care // of both receiving and transmitting options distributions // unsupported, NON-API function fluid.deliverOptionsStrategy = function (that, target, mergeOptions) { var shadow = fluid.shadowForComponent(that, shadow); fluid.cacheShadowGrades(that, shadow); shadow.mergeOptions = mergeOptions; }; // unsupported, NON-API function fluid.resolveReturnedPath = function (returnedPath, that) { var shadow = fluid.shadowForComponent(that); // This prevents corruption of instantiator records by defeating effect of "returnedPath" for non-roots return shadow && shadow.path !== "" ? null : returnedPath; }; fluid.defaults("fluid.gradeLinkageRecord", { gradeNames: ["fluid.littleComponent"] }); /** A "tag component" to opt in to the grade linkage system (FLUID-5212) which is currently very expensive - * this will become the default once we have a better implementation and have stabilised requirements */ fluid.defaults("fluid.applyGradeLinkage", { }); fluid.gradeLinkageIndexer = function (defaults) { if (defaults.contextGrades && defaults.resultGrades) { return ["*"]; } }; fluid.getLinkedGrades = function (gradeNames) { var togo = []; var gradeLinkages = fluid.indexDefaults("gradeLinkages", { gradeNames: "fluid.gradeLinkageRecord", indexFunc: fluid.gradeLinkageIndexer }); fluid.each(gradeLinkages["*"], function (defaultsName) { var defaults = fluid.defaults(defaultsName); var exclude = fluid.find(fluid.makeArray(defaults.contextGrades), function (grade) { if (!fluid.contains(gradeNames, grade)) { return true; } } ); if (!exclude) { togo.push.apply(togo, fluid.makeArray(defaults.resultGrades)); } }); return togo; }; fluid.expandDynamicGrades = function (that, shadow, gradeNames, dynamicGrades) { var resolved = []; fluid.each(dynamicGrades, function (dynamicGrade) { var expanded = fluid.expandOptions(dynamicGrade, that); if (typeof(expanded) === "function") { expanded = expanded(); } if (expanded) { resolved = resolved.concat(expanded); } }); var allGrades = fluid.makeArray(gradeNames).concat(resolved); if (fluid.contains(allGrades, "fluid.applyGradeLinkage")) { var linkedGrades = fluid.getLinkedGrades(allGrades); fluid.remove_if(linkedGrades, function (gradeName) { return fluid.contains(allGrades, gradeName); }); resolved = resolved.concat(linkedGrades); } var distributedBlocks = fluid.receiveDistributions(null, null, null, that); if (distributedBlocks.length > 0) { var readyBlocks = fluid.applyDistributions(that, distributedBlocks, shadow); // rely on the fact that "dirty tricks are not permitted" wrt. resolving gradeNames - each element must be a literal entry or array // holding primitive or EL values - otherwise we would have to go all round the houses and reenter the top of fluid.computeDynamicGrades var gradeNamesList = fluid.transform(fluid.getMembers(readyBlocks, ["source", "gradeNames"]), fluid.makeArray); resolved = resolved.concat.apply(resolved, gradeNamesList); } return resolved; }; // Discover further grades that are entailed by the given base typeName and the current total "dynamic grades list" held in the argument "resolved". // These are looked up conjointly in the grade registry, and then any further i) dynamic grades references {} ii) grade linkage records // are expanded and added into the list and concatenated into "resolved". Additional grades discovered during this function are returned as // "furtherResolved". fluid.collectDynamicGrades = function (that, shadow, defaultsBlock, gradeNames, dynamicGrades, resolved) { var newDefaults = fluid.copy(fluid.getGradedDefaults(that.typeName, resolved)); gradeNames.length = 0; // acquire derivatives of dynamic grades (FLUID-5054) gradeNames.push.apply(gradeNames, newDefaults.gradeNames); fluid.cacheShadowGrades(that, shadow); // This cheap strategy patches FLUID-5091 for now - some more sophisticated activity will take place // at this site when we have a full fix for FLUID-5028 shadow.mergeOptions.destroyValue("mergePolicy"); shadow.mergeOptions.destroyValue("components"); shadow.mergeOptions.destroyValue("invokers"); defaultsBlock.source = newDefaults; shadow.mergeOptions.updateBlocks(); var furtherResolved = fluid.remove_if(gradeNames, function (gradeName) { return gradeName.charAt(0) === "{" && !fluid.contains(dynamicGrades, gradeName); }, []); dynamicGrades.push.apply(dynamicGrades, furtherResolved); furtherResolved = fluid.expandDynamicGrades(that, shadow, gradeNames, furtherResolved); resolved.push.apply(resolved, furtherResolved); return furtherResolved; }; // unsupported, NON-API function fluid.computeDynamicGrades = function (that, shadow, strategy) { delete that.options.gradeNames; // Recompute gradeNames for FLUID-5012 and others var gradeNames = fluid.driveStrategy(that.options, "gradeNames", strategy); // TODO: In complex distribution cases, a component might end up with multiple default blocks var defaultsBlock = fluid.findMergeBlocks(shadow.mergeOptions.mergeBlocks, "defaults")[0]; var dynamicGrades = fluid.remove_if(gradeNames, function (gradeName) { return gradeName.charAt(0) === "{" || !fluid.hasGrade(defaultsBlock.target, gradeName); }, []); var resolved = fluid.expandDynamicGrades(that, shadow, gradeNames, dynamicGrades); if (resolved.length !== 0) { var furtherResolved; do { // repeatedly collect dynamic grades whilst they arrive (FLUID-5155) furtherResolved = fluid.collectDynamicGrades(that, shadow, defaultsBlock, gradeNames, dynamicGrades, resolved); } while (furtherResolved.length !== 0); } if (shadow.collectedClearer) { shadow.collectedClearer(); delete shadow.collectedClearer; } }; fluid.computeDynamicComponentKey = function (recordKey, sourceKey) { return recordKey + (sourceKey === 0 ? "" : "-" + sourceKey); // TODO: configurable name strategies }; // unsupported, NON-API function fluid.registerDynamicRecord = function (that, recordKey, sourceKey, record, toCensor) { var key = fluid.computeDynamicComponentKey(recordKey, sourceKey); var cRecord = fluid.copy(record); delete cRecord[toCensor]; fluid.set(that.options, ["components", key], cRecord); return key; }; // unsupported, NON-API function fluid.computeDynamicComponents = function (that, mergeOptions) { var shadow = fluid.shadowForComponent(that); var localSub = shadow.subcomponentLocal = {}; var records = fluid.driveStrategy(that.options, "dynamicComponents", mergeOptions.strategy); fluid.each(records, function (record, recordKey) { if (!record.sources && !record.createOnEvent) { fluid.fail("Cannot process dynamicComponents record ", record, " without a \"sources\" or \"createOnEvent\" entry"); } if (record.sources) { var sources = fluid.expandOptions(record.sources, that); fluid.each(sources, function (source, sourceKey) { var key = fluid.registerDynamicRecord(that, recordKey, sourceKey, record, "sources"); localSub[key] = {"source": source, "sourcePath": sourceKey}; }); } else if (record.createOnEvent) { var event = fluid.event.expandOneEvent(that, record.createOnEvent); fluid.set(shadow, ["dynamicComponentCount", recordKey], 0); var listener = function () { var key = fluid.registerDynamicRecord(that, recordKey, shadow.dynamicComponentCount[recordKey]++, record, "createOnEvent"); localSub[key] = {"arguments": fluid.makeArray(arguments)}; fluid.initDependent(that, key); }; event.addListener(listener); fluid.recordListener(event, listener, shadow); } }); }; // Second sequence point for mergeOptions from Fluid.js - here we construct all further // strategies required on the IoC side and mount them into the shadow's getConfig for universal use // unsupported, NON-API function fluid.computeComponentAccessor = function (that) { var shadow = fluid.shadowForComponent(that); var options = that.options; var strategy = shadow.mergeOptions.strategy; var optionsStrategy = fluid.mountStrategy(["options"], options, strategy); shadow.invokerStrategy = fluid.recordStrategy(that, options, strategy, "invokers", fluid.invokerFromRecord); shadow.eventStrategyBlock = fluid.recordStrategy(that, options, strategy, "events", fluid.eventFromRecord, ["events"]); var eventStrategy = fluid.mountStrategy(["events"], that, shadow.eventStrategyBlock.strategy, ["events"]); shadow.memberStrategy = fluid.recordStrategy(that, options, strategy, "members", fluid.memberFromRecord); // NB - ginger strategy handles concrete, rationalise shadow.getConfig = {strategies: [fluid.model.funcResolverStrategy, fluid.makeGingerStrategy(that), optionsStrategy, shadow.invokerStrategy.strategy, shadow.memberStrategy.strategy, eventStrategy]}; fluid.computeDynamicGrades(that, shadow, strategy, shadow.mergeOptions.mergeBlocks); fluid.distributeOptions(that, strategy); return shadow.getConfig; }; fluid.shadowForComponent = function (component) { var instantiator = fluid.getInstantiator(component); return instantiator && component ? instantiator.idToShadow[component.id] : null; }; fluid.getForComponent = function (component, path) { var shadow = fluid.shadowForComponent(component); var getConfig = shadow ? shadow.getConfig : undefined; return fluid.get(component, path, getConfig); }; // An EL segment resolver strategy that will attempt to trigger creation of // components that it discovers along the EL path, if they have been defined but not yet // constructed. // unsupported, NON-API function fluid.makeGingerStrategy = function (that) { var instantiator = fluid.getInstantiator(that); return function (component, thisSeg, index, segs) { var atval = component[thisSeg]; if (atval === fluid.inEvaluationMarker && index === segs.length) { fluid.fail("Error in component configuration - a circular reference was found during evaluation of path segment \"" + thisSeg + "\": for more details, see the activity records following this message in the console, or issue fluid.setLogging(fluid.logLevel.TRACE) when running your application"); } if (index > 1) { return atval; } if (atval === undefined && component.hasOwnProperty(thisSeg)) { // avoid recomputing properties that have been explicitly evaluated to undefined return fluid.NO_VALUE; } if (atval === undefined) { // pick up components in instantiation here - we can cut this branch by attaching early var parentPath = instantiator.idToShadow[component.id].path; var childPath = fluid.composePath(parentPath, thisSeg); atval = instantiator.pathToComponent[childPath]; } if (atval === undefined) { // TODO: This check is very expensive - once gingerness is stable, we ought to be able to // eagerly compute and cache the value of options.components - check is also incorrect and will miss injections var subRecord = fluid.getForComponent(component, ["options", "components", thisSeg]); if (subRecord) { if (subRecord.createOnEvent) { fluid.fail("Error resolving path segment \"" + thisSeg + "\" of path " + segs.join(".") + " since component with record ", subRecord, " has annotation \"createOnEvent\" - this very likely represents an implementation error. Either alter the reference so it does not " + " match this component, or alter your workflow to ensure that the component is instantiated by the time this reference resolves"); } fluid.initDependent(component, thisSeg); atval = component[thisSeg]; } } return atval; }; }; fluid.filterBuiltinGrades = function (gradeNames) { return fluid.remove_if(fluid.makeArray(gradeNames), function (gradeName) { return (/^(autoInit|fluid.littleComponent|fluid.modelComponent|fluid.eventedComponent|fluid.viewComponent|fluid.typeFount)$/).test(gradeName); }); }; fluid.dumpGradeNames = function (that) { return that.options && that.options.gradeNames ? " gradeNames: " + JSON.stringify(fluid.filterBuiltinGrades(that.options.gradeNames)) : ""; }; // unsupported, non-API function fluid.dumpThat = function (that) { return "{ typeName: \"" + that.typeName + "\"" + fluid.dumpGradeNames(that) + " id: " + that.id + "}"; }; // unsupported, non-API function fluid.dumpThatStack = function (thatStack, instantiator) { var togo = fluid.transform(thatStack, function(that) { var path = instantiator.idToPath(that.id); return fluid.dumpThat(that) + (path? (" - path: " + path) : ""); }); return togo.join("\n"); }; // unsupported, NON-API function fluid.resolveContext = function (context, that) { var instantiator = fluid.getInstantiator(that); if (context === "instantiator") { return instantiator; } else if (context === "that") { return that; } var foundComponent; var thatStack = instantiator.getFullStack(that); visitComponents(instantiator, thatStack, function (component, name) { var shadow = fluid.shadowForComponent(component); // TODO: Some components, e.g. the static environment and typeTags do not have a shadow, which slows us down here if (context === name || shadow && shadow.contextHash && shadow.contextHash[context] || context === component.typeName || context === component.nickName) { foundComponent = component; return true; // YOUR VISIT IS AT AN END!! } if (fluid.getForComponent(component, ["options", "components", context, "type"]) && !component[context]) { // This is an expensive guess since we make it for every component up the stack - must apply the WAVE OF EXPLOSIONS (FLUID-4925) to discover all components first // This line attempts a hopeful construction of components that could be guessed by nickname through finding them unconstructed // in options. In the near future we should eagerly BEGIN the process of constructing components, discovering their // types and then attaching them to the tree VERY EARLY so that we get consistent results from different strategies. foundComponent = fluid.getForComponent(component, context); return true; } }); return foundComponent; }; var localRecordExpected = /^(arguments|options|container|source|sourcePath|change)$/; // unsupported, NON-API function fluid.makeStackFetcher = function (parentThat, localRecord) { var fetcher = function (parsed) { if (parentThat && parentThat.destroy === fluid.destroyedMarker) { fluid.fail("Cannot resolve reference " + fluid.renderContextReference(parsed) + " from component " + fluid.dumpThat(parentThat) + " which has been destroyed"); } var context = parsed.context; if (localRecord && localRecordExpected.test(context)) { var fetched = fluid.get(localRecord[context], parsed.path); return context === "arguments" || context === "source" || context === "sourcePath" || context === "change" ? fetched : { marker: context === "options" ? fluid.EXPAND : fluid.EXPAND_NOW, value: fetched }; } var foundComponent = fluid.resolveContext(context, parentThat); if (!foundComponent && parsed.path !== "") { var ref = fluid.renderContextReference(parsed); fluid.fail("Failed to resolve reference " + ref + " - could not match context with name " + context + " from component " + fluid.dumpThat(parentThat), parentThat); } return fluid.getForComponent(foundComponent, parsed.path); }; return fetcher; }; // unsupported, NON-API function fluid.makeStackResolverOptions = function (parentThat, localRecord) { return $.extend(fluid.copy(fluid.rawDefaults("fluid.makeExpandOptions")), { fetcher: fluid.makeStackFetcher(parentThat, localRecord), contextThat: parentThat }); }; // unsupported, non-API function fluid.clearListeners = function (shadow) { // TODO: bug here - "afterDestroy" listeners will be unregistered already unless they come from this component fluid.each(shadow.listeners, function (rec) { rec.event.removeListener(rec.listener); }); delete shadow.listeners; }; // unsupported, non-API function fluid.recordListener = function (event, listener, shadow) { if (event.ownerId !== shadow.that.id) { // don't bother recording listeners registered from this component itself var listeners = shadow.listeners; if (!listeners) { listeners = shadow.listeners = []; } listeners.push({event: event, listener: listener}); } }; var idToInstantiator = {}; // unsupported, non-API function - however, this structure is of considerable interest to those debugging // into IoC issues. The structures idToShadow and pathToComponent contain a complete map of the component tree // forming the surrounding scope fluid.instantiator = function (freeInstantiator) { var that = { id: fluid.allocateGuid(), free: freeInstantiator, nickName: "instantiator", pathToComponent: {}, idToShadow: {}, modelTransactions: {init: {}}, // a map of transaction id to map of component id to records of components enlisted in a current model initialisation transaction composePath: fluid.composePath // For speed, we declare that no component's name may contain a period }; // We frequently get requests for components not in this instantiator - e.g. from the dynamicEnvironment or manually created ones that.idToPath = function (id) { var shadow = that.idToShadow[id]; return shadow ? shadow.path : ""; }; that.getThatStack = function (component) { var shadow = that.idToShadow[component.id]; if (shadow) { var path = shadow.path; var parsed = fluid.model.parseEL(path); var togo = fluid.transform(parsed, function (value, i) { var parentPath = fluid.model.composeSegments.apply(null, parsed.slice(0, i + 1)); return that.pathToComponent[parentPath]; }); var root = that.pathToComponent[""]; if (root) { togo.unshift(root); } return togo; } else { return [component];} }; that.getEnvironmentalStack = function () { var togo = [fluid.staticEnvironment]; if (!freeInstantiator) { togo.push(fluid.globalThreadLocal()); } return togo; }; that.getFullStack = function (component) { var thatStack = component? that.getThatStack(component) : []; return that.getEnvironmentalStack().concat(thatStack); }; function recordComponent(component, path, created) { if (created) { idToInstantiator[component.id] = that; var shadow = that.idToShadow[component.id] = {}; shadow.that = component; shadow.path = path; } if (that.pathToComponent[path]) { fluid.fail("Error during instantiation - path " + path + " which has just created component " + fluid.dumpThat(component) + " has already been used for component " + fluid.dumpThat(that.pathToComponent[path]) + " - this is a circular instantiation or other oversight." + " Please clear the component using instantiator.clearComponent() before reusing the path."); } that.pathToComponent[path] = component; } that.recordRoot = function (component) { if (component && component.id && !that.pathToComponent[""]) { recordComponent(component, "", true); } }; that.recordKnownComponent = function (parent, component, name, created) { var parentPath = that.idToShadow[parent.id].path; var path = that.composePath(parentPath, name); recordComponent(component, path, created); }; that.clearComponent = function (component, name, child, options, noModTree, path) { var record = that.idToShadow[component.id].path; // use flat recursion since we want to use our own recursion rather than rely on "visited" records options = options || {flat: true, instantiator: that}; child = child || component[name]; path = path || record; if (path === undefined) { fluid.fail("Cannot clear component " + name + " from component ", component, " which was not created by this instantiator"); } fluid.fireEvent(child, "events.onClear", [child, name, component]); var childPath = that.composePath(path, name); var childRecord = that.idToShadow[child.id]; // only recurse on components which were created in place - if the id record disagrees with the // recurse path, it must have been injected if (childRecord && childRecord.path === childPath) { fluid.doDestroy(child, name, component); // TODO: There needs to be a call to fluid.clearDistributions here fluid.clearListeners(childRecord); fluid.visitComponentChildren(child, function(gchild, gchildname, newPath, parentPath) { that.clearComponent(child, gchildname, null, options, true, parentPath); }, options, childPath); fluid.fireEvent(child, "events.afterDestroy", [child, name, component]); delete that.idToShadow[child.id]; delete idToInstantiator[child.id]; } delete that.pathToComponent[childPath]; // there may be no entry - if created informally if (!noModTree) { delete component[name]; // there may be no entry - if creation is not concluded } }; return that; }; // An instantiator to be used in the "free environment", unattached to any component tree fluid.freeInstantiator = fluid.instantiator(true); // Look up the globally registered instantiator for a particular component fluid.getInstantiator = function (component) { return component && idToInstantiator[component.id] || fluid.freeInstantiator; }; /** Expand a set of component options either immediately, or with deferred effect. * The current policy is to expand immediately function arguments within fluid.embodyDemands which are not the main options of a * component. The component's own options take <code>{defer: true}</code> as part of * <code>outerExpandOptions</code> which produces an "expandOptions" structure holding the "strategy" and "initter" pattern * common to ginger participants. * Probably not to be advertised as part of a public API, but is considerably more stable than most of the rest * of the IoC API structure especially with respect to the first arguments. */ fluid.expandOptions = function (args, that, mergePolicy, localRecord, outerExpandOptions) { if (!args) { return args; } fluid.pushActivity("expandOptions", "expanding options %args for component %that ", {that: that, args: args}); var expandOptions = fluid.makeStackResolverOptions(that, localRecord); expandOptions.mergePolicy = mergePolicy; expandOptions.freeRoot = outerExpandOptions && outerExpandOptions.freeRoot; var expanded = outerExpandOptions && outerExpandOptions.defer ? fluid.makeExpandOptions(args, expandOptions) : fluid.expand(args, expandOptions); fluid.popActivity(); return expanded; }; // unsupported, non-API function fluid.localRecordExpected = ["type", "options", "args", "mergeOptions", "createOnEvent", "priority", "recordType"]; // last element unavoidably polluting // unsupported, non-API function fluid.checkComponentRecord = function (defaults, localRecord) { var expected = fluid.arrayToHash(fluid.localRecordExpected); fluid.each(defaults && defaults.argumentMap, function(value, key) { expected[key] = true; }); fluid.each(localRecord, function (value, key) { if (!expected[key]) { fluid.fail("Probable error in subcomponent record - key \"" + key + "\" found, where the only legal options are " + fluid.keys(expected).join(", ")); } }); }; // unsupported, non-API function fluid.pushDemands = function (list, demands) { demands = fluid.makeArray(demands); var thisp = fluid.mergeRecordTypes.demands; function push(rec) { rec.recordType = "demands"; rec.priority = thisp++; list.push(rec); } function buildAndPush(rec) { push({options: rec}); } // Assume these are sorted at source by intersect count (can't pre-merge if we want "mergeOptions") for (var i = 0; i < demands.length; ++ i) { var thisd = demands[i]; if (thisd.options) { push(thisd); } else if (thisd.mergeOptions) { var mergeOptions = fluid.makeArray(thisd.mergeOptions); fluid.each(mergeOptions, buildAndPush); } else { fluid.fail("Uninterpretable demands record without options or mergeOptions ", thisd); } } }; // unsupported, non-API function fluid.mergeRecordsToList = function (mergeRecords) { var list = []; fluid.each(mergeRecords, function (value, key) { value.recordType = key; if (key === "distributions") { list.push.apply(list, value); } else if (key !== "demands") { if (!value.options) { return; } value.priority = fluid.mergeRecordTypes[key]; if (value.priority === undefined) { fluid.fail("Merge record with unrecognised type " + key + ": ", value); } list.push(value); } else { fluid.pushDemands(list, value); } }); return list; }; // TODO: overall efficiency could huge be improved by resorting to the hated PROTOTYPALISM as an optimisation // for this mergePolicy which occurs in every component. Although it is a deep structure, the root keys are all we need var addPolicyBuiltins = function (policy) { fluid.each(["gradeNames", "mergePolicy", "argumentMap", "components", "dynamicComponents", "members", "invokers", "events", "listeners", "modelListeners", "distributeOptions", "transformOptions"], function (key) { fluid.set(policy, [key, "*", "noexpand"], true); }); return policy; }; // unsupported, NON-API function - used from Fluid.js fluid.generateExpandBlock = function (record, that, mergePolicy, localRecord) { var expanded = fluid.expandOptions(record.options, record.contextThat || that, mergePolicy, localRecord, {defer: true}); expanded.priority = record.priority; expanded.recordType = record.recordType; return expanded; }; var expandComponentOptionsImpl = function (mergePolicy, defaults, userOptions, that) { var defaultCopy = fluid.copy(defaults); addPolicyBuiltins(mergePolicy); var shadow = fluid.shadowForComponent(that); shadow.mergePolicy = mergePolicy; var mergeRecords = { defaults: {options: defaultCopy} }; if (userOptions) { if (userOptions.marker === fluid.EXPAND) { $.extend(mergeRecords, userOptions.mergeRecords); // Do this here for gradeless components that were corrected by "localOptions" if (mergeRecords.subcomponentRecord) { fluid.checkComponentRecord(defaults, mergeRecords.subcomponentRecord); } } else { mergeRecords.user = {options: fluid.expandCompact(userOptions, true)}; } } var expandList = fluid.mergeRecordsToList(mergeRecords); var togo = fluid.transform(expandList, function (value) { return fluid.generateExpandBlock(value, that, mergePolicy, userOptions && userOptions.localRecord); }); return togo; }; // unsupported, non-API function fluid.makeIoCRootDestroy = function (instantiator, that) { return function () { instantiator.clearComponent(that, "", that, null, true); }; }; // NON-API function fluid.fabricateDestroyMethod = function (that, name, instantiator, child) { return function () { instantiator.clearComponent(that, name, child); }; }; // unsupported, non-API function fluid.expandComponentOptions = function (mergePolicy, defaults, userOptions, that) { var instantiator = userOptions && userOptions.marker === fluid.EXPAND && userOptions.memberName !== undefined ? userOptions.instantiator : null; var fresh; if (!instantiator) { instantiator = fluid.instantiator(); fresh = true; fluid.log("Created new instantiator with id " + instantiator.id + " in order to operate on component " + (that? that.typeName : "[none]")); that.destroy = fluid.makeIoCRootDestroy(instantiator, that); } fluid.pushActivity("expandComponentOptions", "expanding component options %options with record %record for component %that", {options: userOptions && userOptions.mergeRecords, record: userOptions, that: that}); if (fresh) { instantiator.recordRoot(that); } else { instantiator.recordKnownComponent(userOptions.parentThat, that, userOptions.memberName, true); } var togo = expandComponentOptionsImpl(mergePolicy, defaults, userOptions, that); fluid.popActivity(); return togo; }; // unsupported, non-API function fluid.argMapToDemands = function (argMap) { var togo = []; fluid.each(argMap, function (value, key) { togo[value] = "{" + key + "}"; }); return togo; }; // unsupported, non-API function fluid.makePassArgsSpec = function (initArgs) { return fluid.transform(initArgs, function(arg, index) { return "{arguments}." + index; }); }; // unsupported, NON-API function fluid.pushDemandSpec = function (record, options, mergeOptions) { if (options && options !== "{options}") { record.push({options: options}); } if (mergeOptions) { record.push({mergeOptions: mergeOptions}); } }; /** Given a concrete argument list and/or options, determine the final concrete * "invocation specification" which is coded by the supplied demandspec in the * environment "thatStack" - the return is a package of concrete global function name * and argument list which is suitable to be executed directly by fluid.invokeGlobalFunction. */ // unsupported, non-API function // options is just a disposition record containing memberName, componentRecord + passArgs // various built-in effects of this method // i) note that it makes no effort to actually propagate direct // options from "initArgs", assuming that they will be seen again in expandComponentOptions fluid.embodyDemands = function (parentThat, demandspec, initArgs, options) { options = options || {}; if (demandspec.mergeOptions && demandspec.options) { fluid.fail("demandspec ", demandspec, " is invalid - cannot specify literal options together with mergeOptions"); } if (demandspec.transformOptions) { // Support for "transformOptions" at top level in a demands record demandspec.options = $.extend(true, {}, demandspec.options, { transformOptions: demandspec.transformOptions }); } var demands = fluid.makeArray(demandspec.args); var upDefaults = fluid.defaults(demandspec.funcName); var fakeThat = {}; // fake "that" for receiveDistributions since we try to match selectors before creation for FLUID-5013 var distributions = upDefaults && parentThat ? fluid.receiveDistributions(parentThat, upDefaults.gradeNames, options.memberName, fakeThat) : []; var argMap = upDefaults? upDefaults.argumentMap : null; var inferMap = false; if (upDefaults) { options.passArgs = false; // Don't attempt to construct a component using "passArgs" spec } if (!argMap && (upDefaults || (options && options.componentRecord))) { inferMap = true; // infer that it must be a little component if we have any reason to believe it is a component if (demands.length < 2) { argMap = fluid.rawDefaults("fluid.littleComponent").argumentMap; } else { var optionpos = $.inArray("{options}", demands); if (optionpos === -1) { optionpos = demands.length - 1; // wild guess in the old style } argMap = {options: optionpos}; } } options = options || {}; if (demands.length === 0) { if (argMap) { demands = fluid.argMapToDemands(argMap); } else if (options.passArgs) { demands = fluid.makePassArgsSpec(initArgs); } } var shadow = fluid.shadowForComponent(parentThat); var localDynamic = shadow && options.memberName ? shadow.subcomponentLocal[options.memberName] : null; // confusion remains with "localRecord" - it is a random mishmash of user arguments and the component record // this should itself be absorbed into "mergeRecords" and let stackFetcher sort it out var localRecord = $.extend({"arguments": initArgs}, fluid.censorKeys(options.componentRecord, ["type"]), localDynamic); fluid.each(argMap, function (index, name) { // this is incorrect anyway! What if the supplied arguments were not in the same order as the target argmap, // which was obtained from the target defaults if (initArgs.length > 0) { localRecord[name] = localRecord["arguments"][index]; } if (demandspec[name] !== undefined && localRecord[name] === undefined) { localRecord[name] = demandspec[name]; } if (name !== "options") { for (var i = 0; i < distributions.length; ++ i) { // Apply non-options material from distributions (FLUID-5013) if (distributions[i][name] !== undefined) { localRecord[name] = distributions[i][name]; } } } }); var i; for (i = 0; i < distributions.length; ++ i) { if (distributions[i].type !== undefined) { demandspec.funcName = distributions[i].type; } } var mergeRecords = {distributions: distributions}; if (options.componentRecord !== undefined) { // Deliberately put too many things here so they can be checked in expandComponentOptions (FLUID-4285) mergeRecords.subcomponentRecord = $.extend({}, options.componentRecord); } var expandOptions = fluid.makeStackResolverOptions(parentThat, localRecord); var pushBackSpec = function (backSpec) { fluid.pushDemandSpec(mergeRecords.demands, backSpec.options, backSpec.mergeOptions); }; var args = []; if (demands) { for (i = 0; i < demands.length; ++i) { var arg = demands[i]; // Weak detection since we cannot guarantee this material has not been copied if (fluid.isMarker(arg) && arg.value === fluid.COMPONENT_OPTIONS.value) { arg = "{options}"; // Backwards compatibility for non-users of GRADES - last-ditch chance to correct the inference if (inferMap) { argMap = {options: i}; } } if (typeof(arg) === "string") { if (arg.charAt(0) === "@") { var argpos = arg.substring(1); arg = "{arguments}." + argpos; } } demands[i] = arg; if (!argMap || argMap.options !== i) { // expand immediately if there can be no options or this is not the options args[i] = fluid.expand(arg, expandOptions); } else { // It is the component options if (options.passArgs) { fluid.fail("Error invoking function " + demandspec.funcName + ": found component creator rather than free function"); } if (typeof(arg) === "object" && !arg.targetTypeName) { arg.targetTypeName = demandspec.funcName; } mergeRecords.demands = []; fluid.each((demandspec.backSpecs).reverse(), pushBackSpec); fluid.pushDemandSpec(mergeRecords.demands, demandspec.options || arg, demandspec.mergeOptions); if (initArgs.length > 0) { mergeRecords.user = {options: localRecord.options}; } args[i] = {marker: fluid.EXPAND, localRecord: localDynamic, mergeRecords: mergeRecords, instantiator: fluid.getInstantiator(parentThat), parentThat: parentThat, memberName: options.memberName}; } if (args[i] && fluid.isMarker(args[i].marker, fluid.EXPAND_NOW)) { args[i] = fluid.expand(args[i].value, expandOptions); } } } else { args = initArgs? initArgs : []; } var togo = { args: args, preExpand: demands, funcName: demandspec.funcName }; return togo; }; /** Instantiate the subcomponent with the supplied name of the supplied top-level component. Although this method * is published as part of the Fluid API, it should not be called by general users and may not remain stable. It is * currently the only mechanism provided for instantiating components whose definitions are dynamic, and will be * replaced in time by dedicated declarative framework described by FLUID-5022. * @param that {Component} the parent component for which the subcomponent is to be instantiated * @param name {String} the name of the component - the index of the options block which configures it as part of the * <code>components</code> section of its parent's options */ // NB "directArgs" is now disused by the framework fluid.initDependent = function (that, name, directArgs) { if (that[name]) { return; } // TODO: move this into strategy directArgs = directArgs || []; var component = that.options.components[name]; fluid.pushActivity("initDependent", "instantiating dependent component with name \"%name\" with record %record as child of %parent", {name: name, record: component, parent: that}); var instance; var instantiator = idToInstantiator[that.id]; if (typeof(component) === "string") { instance = fluid.expandOptions(component, that); instantiator.recordKnownComponent(that, instance, name, false); } else if (component.type) { var type = fluid.expandOptions(component.type, that); if (!type) { fluid.fail("Error in subcomponent record: ", component.type, " could not be resolved to a type for component ", name, " of parent ", that); } var invokeSpec = fluid.resolveDemands(that, [type, name], directArgs, {componentRecord: component, memberName: name}); instance = fluid.initSubcomponentImpl(that, {type: invokeSpec.funcName}, invokeSpec.args); // The existing instantiator record will be provisional, adjust it to take account of the true return // TODO: Instantiator contents are generally extremely incomplete var path = instantiator.composePath(instantiator.idToPath(that.id), name); var existing = instantiator.pathToComponent[path]; // This branch deals with the case where the component creator registered a component into "pathToComponent" // that does not agree with the component which was the return value. We need to clear out "pathToComponent" but // not shred the component since most of it is probably still valid if (existing && existing !== instance) { instantiator.clearComponent(that, name, existing); } if (instance && instance.typeName && instance.id && instance !== existing) { instantiator.recordKnownComponent(that, instance, name, true); } instance.destroy = fluid.fabricateDestroyMethod(that, name, instantiator, instance); } else { fluid.fail("Unrecognised material in place of subcomponent " + name + " - no \"type\" field found"); } that[name] = instance; fluid.fireEvent(instance, "events.onAttach", [instance, name, that]); fluid.popActivity(); return instance; }; // unsupported, non-API function fluid.bindDeferredComponent = function (that, componentName, component) { var events = fluid.makeArray(component.createOnEvent); fluid.each(events, function(eventName) { var event = eventName.charAt(0) === "{" ? fluid.expandOptions(eventName, that) : that.events[eventName]; if (!event || !event.addListener) { fluid.fail("Error instantiating createOnEvent component with name " + componentName + " of parent ", that, " since event specification " + eventName + " could not be expanded to an event - got ", event); } event.addListener(function () { fluid.pushActivity("initDeferred", "instantiating deferred component %componentName of parent %that due to event %eventName", {componentName: componentName, that: that, eventName: eventName}); if (that[componentName]) { var instantiator = idToInstantiator[that.id]; instantiator.clearComponent(that, componentName); } fluid.initDependent(that, componentName); fluid.popActivity(); }, null, null, component.priority); }); }; // unsupported, non-API function fluid.priorityForComponent = function (component) { return component.priority? component.priority : (component.type === "fluid.typeFount" || fluid.hasGrade(fluid.defaults(component.type), "fluid.typeFount"))? "first" : undefined; }; fluid.initDependents = function (that) { fluid.pushActivity("initDependents", "instantiating dependent components for component %that", {that: that}); var shadow = fluid.shadowForComponent(that); shadow.memberStrategy.initter(); var options = that.options; var components = options.components || {}; var componentSort = {}; fluid.each(components, function (component, name) { if (!component.createOnEvent) { var priority = fluid.priorityForComponent(component); componentSort[name] = [{key: name, priority: fluid.event.mapPriority(priority, 0)}]; } else { fluid.bindDeferredComponent(that, name, component); } }); var componentList = fluid.event.sortListeners(componentSort); fluid.each(componentList, function (entry) { fluid.initDependent(that, entry.key); }); shadow.invokerStrategy.initter(); fluid.popActivity(); }; var dependentStore = {}; function searchDemands (demandingName, contextNames) { var exist = dependentStore[demandingName] || []; outer: for (var i = 0; i < exist.length; ++i) { var rec = exist[i]; for (var j = 0; j < contextNames.length; ++j) { if (rec.contexts[j] !== contextNames[j]) { continue outer; } } return rec.spec; // jslint:ok } } var isDemandLogging = false; fluid.setDemandLogging = function (set) { isDemandLogging = set; }; // unsupported, non-API function fluid.isDemandLogging = function () { return isDemandLogging && fluid.isLogging(); }; fluid.demands = function (demandingName, contextName, spec) { var contextNames = fluid.makeArray(contextName).sort(); if (!spec) { return searchDemands(demandingName, contextNames); } else if (spec.length) { spec = {args: spec}; } if (fluid.getCallerInfo && fluid.isDemandLogging()) { var callerInfo = fluid.getCallerInfo(5); if (callerInfo) { spec.registeredFrom = callerInfo; } } spec.demandId = fluid.allocateGuid(); var exist = dependentStore[demandingName]; if (!exist) { exist = []; dependentStore[demandingName] = exist; } exist.push({contexts: contextNames, spec: spec}); }; // unsupported, non-API function fluid.compareDemands = function (speca, specb) { return specb.intersect - speca.intersect; }; // unsupported, non-API function fluid.locateAllDemands = function (parentThat, demandingNames) { var demandLogging = fluid.isDemandLogging(demandingNames); if (demandLogging) { fluid.log("Resolving demands for function names ", demandingNames, " in context of " + (parentThat? "component " + parentThat.typeName : "no component")); } var contextNames = {}; var visited = []; var instantiator = fluid.getInstantiator(parentThat); var thatStack = instantiator.getFullStack(parentThat); visitComponents(instantiator, thatStack, function (component, xname, path, xpath, depth) { // NB - don't use shadow's cache here because we allow fewer names for demand resolution than for value resolution contextNames[component.typeName] = depth; var gradeNames = fluid.makeArray(fluid.get(component, ["options", "gradeNames"])); fluid.each(gradeNames, function (gradeName) { contextNames[gradeName] = depth; }); visited.push(component); }); if (demandLogging) { fluid.log("Components in scope for resolution:\n" + fluid.dumpThatStack(visited, instantiator)); } var matches = []; for (var i = 0; i < demandingNames.length; ++i) { var rec = dependentStore[demandingNames[i]] || []; for (var j = 0; j < rec.length; ++j) { var spec = rec[j]; var horizonLevel = spec.spec.horizon ? contextNames[spec.spec.horizon] : -1; var record = {spec: spec, intersect: 0, uncess: 0}; for (var k = 0; k < spec.contexts.length; ++k) { var depth = contextNames[spec.contexts[k]]; record[depth !== undefined && depth >= horizonLevel ? "intersect" : "uncess"] += 2; } if (spec.contexts.length === 0) { // allow weak priority for contextless matches record.intersect++; } if (record.uncess === 0) { matches.push(record); } } } matches.sort(fluid.compareDemands); return matches; }; // unsupported, non-API function fluid.locateDemands = function (parentThat, demandingNames) { var matches = fluid.locateAllDemands(parentThat, demandingNames); var demandspec = fluid.getMembers(matches, ["spec", "spec"]); if (fluid.isDemandLogging(demandingNames)) { if (demandspec.length) { fluid.log("Located " + matches.length + " potential match" + (matches.length === 1? "" : "es") + ", selected best match with " + matches[0].intersect + " matched context names: ", demandspec); } else { fluid.log("No matches found for demands, using direct implementation"); } } return demandspec; }; /** Determine the appropriate demand specification held in the fluid.demands environment * relative the supplied component position for the function name(s) funcNames. */ // unsupported, non-API function fluid.determineDemands = function (parentThat, funcNames) { funcNames = fluid.makeArray(funcNames); var newFuncName = funcNames[0]; var demandspec = fluid.locateDemands(parentThat, funcNames); if (demandspec.length && demandspec[0].funcName) { newFuncName = demandspec[0].funcName; } return $.extend(true, {funcName: newFuncName, args: demandspec[0] ? fluid.makeArray(demandspec[0].args) : [] }, { backSpecs: demandspec.slice(1) }, // Fix for FLUID-5126 fluid.censorKeys(demandspec[0], ["funcName", "args"])); }; // "options" includes - passArgs, componentRecord, memberName (latter two from initDependent route) // unsupported, non-API function fluid.resolveDemands = function (parentThat, funcNames, initArgs, options) { var demandspec = fluid.determineDemands(parentThat, funcNames); return fluid.embodyDemands(parentThat, demandspec, initArgs, options); }; // unsupported, non-API function fluid.thisistToApplicable = function (record, recthis, that) { return { apply: function (noThis, args) { // Resolve this material late, to deal with cases where the target has only just been brought into existence // (e.g. a jQuery target for rendered material) - TODO: Possibly implement cached versions of these as we might do for invokers var resolvedThis = fluid.expandOptions(recthis, that); if (typeof(resolvedThis) === "string") { resolvedThis = fluid.getGlobalValue(resolvedThis); } if (!resolvedThis) { fluid.fail("Could not resolve reference " + recthis + " to a value"); } var resolvedFunc = resolvedThis[record.method]; if (typeof(resolvedFunc) !== "function") { fluid.fail("Object ", resolvedThis, " at reference " + recthis + " has no member named " + record.method + " which is a function "); } fluid.log("Applying arguments ", args, " to method " + record.method + " of instance ", resolvedThis); return resolvedFunc.apply(resolvedThis, args); } }; }; fluid.changeToApplicable = function (record, that) { return { apply: function (noThis, args) { var parsed = fluid.parseValidModelReference(that, "changePath listener record", record.changePath); var value = fluid.expandOptions(record.value, that, {}, {"arguments": args}); fluid.fireSourcedChange(parsed.applier, parsed.path, value, record.source); } }; }; // Convert "exotic records" into an applicable form ("this/method" for FLUID-4878 or "changePath" for FLUID-3674) // unsupported, non-API function fluid.recordToApplicable = function (record, that) { if (record.changePath) { return fluid.changeToApplicable(record, that); } var recthis = record["this"]; if (record.method ^ recthis) { fluid.fail("Record ", that, " must contain both entries \"method\" and \"this\" if it contains either"); } return record.method ? fluid.thisistToApplicable(record, recthis, that) : null; }; // TODO: make a *slightly* more performant version of fluid.invoke that perhaps caches the demands // after the first successful invocation fluid.invoke = function (functionName, args, that, environment) { fluid.pushActivity("invokeFunc", "invoking function with name \"%functionName\" from component %that", {functionName: functionName, that: that}); var invokeSpec = fluid.resolveDemands(that, functionName, fluid.makeArray(args), {passArgs: true}); var togo = fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); fluid.popActivity(); return togo; }; /** Make a function which performs only "static redispatch" of the supplied function name - * that is, taking only account of the contents of the "static environment". Since the static * environment is assumed to be constant, the dispatch of the call will be evaluated at the * time this call is made, as an optimisation. */ // unsupported, non-API function fluid.makeFreeInvoker = function (functionName, environment) { var demandSpec = fluid.determineDemands(null, functionName); return function () { var invokeSpec = fluid.embodyDemands(null, demandSpec, fluid.makeArray(arguments), {passArgs: true}); return fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); }; }; var argPrefix = "{arguments}."; fluid.parseInteger = function (string) { return isFinite(string) && ((string % 1) === 0) ? Number(string) : NaN; }; fluid.makeFastInvoker = function (invokeSpec, func) { var argMap; if (invokeSpec.preExpand) { argMap = {}; for (var i = 0; i < invokeSpec.preExpand.length; ++ i) { var value = invokeSpec.preExpand[i]; if (typeof(value) === "string") { if (value.indexOf("}.model") !== -1) { return {noFast: true}; } if (value === "{arguments}") { argMap[i] = "*"; } else if (value.indexOf(argPrefix) === 0) { var argIndex = fluid.parseInteger(value.substring(argPrefix.length)); if (isNaN(argIndex)) { return {noFast: true}; } else { argMap[i] = argIndex; // target arg pos = original arg pos } } } } } var outArgs = invokeSpec.args; var invoke = argMap ? function invoke(args) { for (var i in argMap) { outArgs[i] = argMap[i] === "*" ? args : args[argMap[i]]; } return func.apply(null, outArgs); } : function invoke (args) { return func.apply(null, args); }; return { invoke: invoke }; }; // unsupported, non-API function fluid.makeInvoker = function (that, invokerec, name, environment) { var functionName; if (typeof(invokerec) === "string") { if (invokerec.charAt(0) === "{") { // shorthand case for direct function invokers (FLUID-4926) invokerec = {func: invokerec}; } else { functionName = invokerec; } } var demandspec = functionName? fluid.determineDemands(that, functionName) : invokerec; var fastRec = {noFast: invokerec.dynamic}; return function invokeInvoker () { if (fluid.defeatLogging === false) { fluid.pushActivity("invokeInvoker", "invoking invoker with name %name and record %record from component %that", {name: name, record: invokerec, that: that}); } var togo; if (fastRec.invoke) { togo = fastRec.invoke(arguments); } else { var func = fluid.recordToApplicable(invokerec, that); var args = fluid.makeArray(arguments); var invokeSpec = fluid.embodyDemands(that, demandspec, args, {passArgs: true}); func = func || (invokeSpec.funcName? fluid.getGlobalValue(invokeSpec.funcName, environment) : fluid.expandOptions(demandspec.func, that)); if (!func || !func.apply) { fluid.fail("Error in invoker record: could not resolve members func, funcName or method to a function implementation - got " + func + " from ", demandspec); } if (fastRec.noFast !== true) { fastRec = fluid.makeFastInvoker(invokeSpec, func); } togo = func.apply(null, invokeSpec.args); } if (fluid.defeatLogging === false) { fluid.popActivity(); } return togo; }; }; // unsupported, non-API function // weird higher-order function so that we can staightforwardly dispatch original args back onto listener fluid.event.makeTrackedListenerAdder = function (source) { var shadow = fluid.shadowForComponent(source); return function (event) { return {addListener: function (listener) { fluid.recordListener(event, listener, shadow); event.addListener.apply(null, arguments); } }; }; }; // unsupported, non-API function fluid.event.listenerEngine = function (eventSpec, callback, adder) { var argstruc = {}; function checkFire() { var notall = fluid.find(eventSpec, function(value, key) { if (argstruc[key] === undefined) { return true; } }); if (!notall) { var oldstruc = argstruc; argstruc = {}; // guard against the case the callback perversely fires one of its prerequisites (FLUID-5112) callback(oldstruc); } } fluid.each(eventSpec, function (event, eventName) { adder(event).addListener(function () { argstruc[eventName] = fluid.makeArray(arguments); checkFire(); }); }); }; // unsupported, non-API function fluid.event.dispatchListener = function (that, listener, eventName, eventSpec, indirectArgs) { var togo = function () { fluid.pushActivity("dispatchListener", "firing to listener to event named %eventName of component %that", {eventName: eventName, that: that}); var args = indirectArgs? arguments[0] : fluid.makeArray(arguments); var demandspec = fluid.determineDemands(that, eventName); // TODO: This name may contain a namespace if (demandspec.args.length === 0 && eventSpec.args) { demandspec.args = eventSpec.args; } // TODO: create a "fast path" here as for invokers. Eliminate redundancy with invoker code var resolved = fluid.embodyDemands(that, demandspec, args, {passArgs: true}); var togo = fluid.event.invokeListener(listener, resolved.args); fluid.popActivity(); return togo; }; fluid.event.impersonateListener(listener, togo); return togo; }; // unsupported, non-API function fluid.event.resolveSoftNamespace = function (key) { if (typeof(key) !== "string") { return null; } else { var lastpos = Math.max(key.lastIndexOf("."), key.lastIndexOf("}")); return key.substring(lastpos + 1); } }; // unsupported, non-API function fluid.event.resolveListenerRecord = function (lisrec, that, eventName, namespace, standard) { var badRec = function (record, extra) { fluid.fail("Error in listener record - could not resolve reference ", record, " to a listener or firer. " + "Did you miss out \"events.\" when referring to an event firer?" + extra); }; fluid.pushActivity("resolveListenerRecord", "resolving listener record for event named %eventName for component %that", {eventName: eventName, that: that}); var records = fluid.makeArray(lisrec); var transRecs = fluid.transform(records, function (record) { // TODO: FLUID-5242 fix - we copy here since distributeOptions does not copy options blocks that it distributes and we can hence corrupt them. // need to clarify policy on options sharing - for slightly better efficiency, copy should happen during distribution and not here var expanded = fluid.isPrimitive(record) || record.expander ? {listener: record} : fluid.copy(record); var methodist = fluid.recordToApplicable(record, that); if (methodist) { expanded.listener = methodist; } else { expanded.listener = expanded.listener || expanded.func || expanded.funcName; } if (!expanded.listener) { badRec(record, " Listener record must contain a member named \"listener\", \"func\", \"funcName\" or \"method\""); } var softNamespace = record.method ? fluid.event.resolveSoftNamespace(record["this"]) + "." + record.method : fluid.event.resolveSoftNamespace(expanded.listener); if (!expanded.namespace && !namespace && softNamespace) { expanded.softNamespace = true; expanded.namespace = (record.componentSource ? record.componentSource : that.typeName) + "." + softNamespace; } var listener = expanded.listener = fluid.expandOptions(expanded.listener, that); if (!listener) { badRec(record, ""); } var firer = false; if (listener.typeName === "fluid.event.firer") { listener = listener.fire; firer = true; } expanded.listener = (standard && (expanded.args || firer)) ? fluid.event.dispatchListener(that, listener, eventName, expanded) : listener; return expanded; }); var togo = { records: transRecs, adderWrapper: standard ? fluid.event.makeTrackedListenerAdder(that) : null }; fluid.popActivity(); return togo; }; // unsupported, non-API function fluid.event.expandOneEvent = function (that, event) { var origin; if (typeof(event) === "string" && event.charAt(0) !== "{") { // Shorthand for resolving onto our own events, but with GINGER WORLD! origin = fluid.getForComponent(that, ["events", event]); } else { origin = fluid.expandOptions(event, that); } if (!origin || origin.typeName !== "fluid.event.firer") { fluid.fail("Error in event specification - could not resolve base event reference ", event, " to an event firer: got ", origin); } return origin; }; // unsupported, non-API function fluid.event.expandEvents = function (that, event) { return typeof(event) === "string" ? fluid.event.expandOneEvent(that, event) : fluid.transform(event, function (oneEvent) { return fluid.event.expandOneEvent(that, oneEvent); }); }; // unsupported, non-API function fluid.event.resolveEvent = function (that, eventName, eventSpec) { fluid.pushActivity("resolveEvent", "resolving event with name %eventName attached to component %that", {eventName: eventName, that: that}); var adder = fluid.event.makeTrackedListenerAdder(that); if (typeof(eventSpec) === "string") { eventSpec = {event: eventSpec}; } var event = eventSpec.event || eventSpec.events; if (!event) { fluid.fail("Event specification for event with name " + eventName + " does not include a base event specification: ", eventSpec); } var origin = fluid.event.expandEvents(that, event); var isMultiple = origin.typeName !== "fluid.event.firer"; var isComposite = eventSpec.args || isMultiple; // If "event" is not composite, we want to share the listener list and FIRE method with the original // If "event" is composite, we need to create a new firer. "composite" includes case where any boiling // occurred - this was implemented wrongly in 1.4. var firer; if (isComposite) { firer = fluid.makeEventFirer({name: " [composite] " + fluid.event.nameEvent(that, eventName)}); var dispatcher = fluid.event.dispatchListener(that, firer.fire, eventName, eventSpec, isMultiple); if (isMultiple) { fluid.event.listenerEngine(origin, dispatcher, adder); } else { adder(origin).addListener(dispatcher); } } else { firer = {typeName: "fluid.event.firer"}; // jslint:ok - already defined firer.fire = function () { var outerArgs = fluid.makeArray(arguments); fluid.pushActivity("fireSynthetic", "firing synthetic event %eventName ", {eventName: eventName}); var togo = origin.fire.apply(null, outerArgs); fluid.popActivity(); return togo; }; firer.addListener = function (listener, namespace, predicate, priority, softNamespace) { var dispatcher = fluid.event.dispatchListener(that, listener, eventName, eventSpec); adder(origin).addListener(dispatcher, namespace, predicate, priority, softNamespace); }; firer.removeListener = function (listener) { origin.removeListener(listener); }; } fluid.popActivity(); return firer; }; /** BEGIN unofficial IoC material **/ // Although the following three functions are unsupported and not part of the IoC // implementation proper, they are still used in the renderer // expander as well as in some old-style tests and various places in CSpace. // unsupported, non-API function fluid.withEnvironment = function (envAdd, func, root) { root = root || fluid.globalThreadLocal(); return fluid.tryCatch(function() { for (var key in envAdd) { root[key] = envAdd[key]; } $.extend(root, envAdd); return func(); }, null, function() { for (var key in envAdd) { // jslint:ok duplicate "value" delete root[key]; // TODO: users may want a recursive "scoping" model } }); }; // unsupported, NON-API function fluid.fetchContextReference = function (parsed, directModel, env, elResolver, externalFetcher) { // The "elResolver" is a hack to make certain common idioms in protoTrees work correctly, where a contextualised EL // path actually resolves onto a further EL reference rather than directly onto a value target if (elResolver) { parsed = elResolver(parsed, env); } var base = parsed.context? env[parsed.context] : directModel; if (!base) { var resolveExternal = externalFetcher && externalFetcher(parsed); return resolveExternal || base; } return parsed.noDereference? parsed.path : fluid.get(base, parsed.path); }; // unsupported, non-API function fluid.makeEnvironmentFetcher = function (directModel, elResolver, envGetter, externalFetcher) { envGetter = envGetter || fluid.globalThreadLocal; return function(parsed) { var env = envGetter(); return fluid.fetchContextReference(parsed, directModel, env, elResolver, externalFetcher); }; }; /** END of unofficial IoC material **/ // unsupported, non-API function fluid.coerceToPrimitive = function (string) { return string === "false" ? false : (string === "true" ? true : (isFinite(string) ? Number(string) : string)); }; // unsupported, non-API function fluid.compactStringToRec = function (string, type) { var openPos = string.indexOf("("); var closePos = string.indexOf(")"); if (openPos === -1 ^ closePos === -1 || openPos > closePos) { fluid.fail("Badly-formed compact " + type + " record without matching parentheses: ", string); } if (openPos !== -1 && closePos !== -1) { var prefix = string.substring(0, openPos); var body = string.substring(openPos + 1, closePos); var args = fluid.transform(body.split(","), $.trim, fluid.coerceToPrimitive); var togo = { args: args }; if (type === "invoker" && prefix.charAt(openPos - 1) === "!") { prefix = string.substring(0, openPos - 1); togo.dynamic = true; } togo[prefix.charAt(0) === "{" ? "func" : "funcName"] = prefix; return togo; } else if (type === "expander") { fluid.fail("Badly-formed compact expander record without parentheses: ", string); } return string; }; fluid.expandPrefix = "@expand:"; // unsupported, non-API function fluid.expandCompactString = function (string, active) { var rec = string; if (string.indexOf(fluid.expandPrefix) === 0) { var rem = string.substring(fluid.expandPrefix.length); rec = { expander: fluid.compactStringToRec(rem, "expander") }; } else if (active) { rec = fluid.compactStringToRec(string, active); } return rec; }; var singularPenRecord = { listeners: "listener", modelListeners: "modelListener" }; var singularRecord = $.extend({ invokers: "invoker" }, singularPenRecord); // unsupported, non-API function fluid.expandCompactRec = function (segs, target, source, userOptions) { var pen = segs.length > 0 ? segs[segs.length - 1] : ""; var active = singularRecord[pen]; if (!active && segs.length > 1) { active = singularPenRecord[segs[segs.length - 2]]; // support array of listeners and modelListeners } fluid.each(source, function (value, key) { // TODO: hack here to avoid corrupting old-style model references which were listed with "preserve" - eliminate this along with that mergePolicy if (fluid.isPlainObject(value) && !fluid.isDOMish(value) && !(userOptions && key === "model" && segs.length === 0)) { target[key] = fluid.freshContainer(value); segs.push(key); fluid.expandCompactRec(segs, target[key], value); segs.pop(); return; } else if (typeof(value) === "string") { value = fluid.expandCompactString(value, active); } target[key] = value; }); }; // unsupported, non-API function fluid.expandCompact = function (options, userOptions) { var togo = {}; fluid.expandCompactRec([], togo, options, userOptions); return togo; }; // unsupported, non-API function fluid.extractEL = function (string, options) { if (options.ELstyle === "ALL") { return string; } else if (options.ELstyle.length === 1) { if (string.charAt(0) === options.ELstyle) { return string.substring(1); } } else if (options.ELstyle === "${}") { var i1 = string.indexOf("${"); var i2 = string.lastIndexOf("}"); if (i1 === 0 && i2 !== -1) { return string.substring(2, i2); } } }; // unsupported, non-API function fluid.extractELWithContext = function (string, options) { var EL = fluid.extractEL(string, options); if (EL && EL.charAt(0) === "{" && EL.indexOf("}") > 0) { return fluid.parseContextReference(EL); } return EL? {path: EL} : EL; }; fluid.parseContextReference = function (reference, index, delimiter) { index = index || 0; var endcpos = reference.indexOf("}", index + 1); if (endcpos === -1) { fluid.fail("Cannot parse context reference \"" + reference + "\": Malformed context reference without }"); } var context = reference.substring(index + 1, endcpos); var endpos = delimiter? reference.indexOf(delimiter, endcpos + 1) : reference.length; var path = reference.substring(endcpos + 1, endpos); if (path.charAt(0) === ".") { path = path.substring(1); } return {context: context, path: path, endpos: endpos}; }; fluid.renderContextReference = function (parsed) { return "{" + parsed.context + "}" + (parsed.path ? "." + parsed.path : ""); }; // unsupported, non-API function fluid.resolveContextValue = function (string, options) { function fetch(parsed) { fluid.pushActivity("resolveContextValue", "resolving context value %string", {string: string}); var togo = options.fetcher(parsed); fluid.pushActivity("resolvedContextValue", "resolved value %string to value %value", {string: string, value: togo}); fluid.popActivity(2); return togo; } var parsed; if (options.bareContextRefs && string.charAt(0) === "{" && string.indexOf("}") > 0) { parsed = fluid.parseContextReference(string); return fetch(parsed); } else if (options.ELstyle && options.ELstyle !== "${}") { parsed = fluid.extractELWithContext(string, options); if (parsed) { return fetch(parsed); } } while (typeof(string) === "string") { var i1 = string.indexOf("${"); var i2 = string.indexOf("}", i1 + 2); if (i1 !== -1 && i2 !== -1) { if (string.charAt(i1 + 2) === "{") { parsed = fluid.parseContextReference(string, i1 + 2, "}"); i2 = parsed.endpos; } else { parsed = {path: string.substring(i1 + 2, i2)}; } var subs = fetch(parsed); var all = (i1 === 0 && i2 === string.length - 1); // TODO: test case for all undefined substitution if (subs === undefined || subs === null) { return subs; } string = all? subs : string.substring(0, i1) + subs + string.substring(i2 + 1); } else { break; } } return string; }; // unsupported, NON-API function fluid.expandExpander = function (target, source, options) { var expander = fluid.getGlobalValue(source.expander.type || "fluid.deferredInvokeCall"); if (expander) { return expander.call(null, target, source, options); } }; // This function appears somewhat reusable, but not entirely - it probably needs to be packaged // along with the particular "strategy". Very similar to the old "filter"... the "outer driver" needs // to execute it to get the first recursion going at top level. This was one of the most odd results // of the reorganisation, since the "old work" seemed much more naturally expressed in terms of values // and what happened to them. The "new work" is expressed in terms of paths and how to move amongst them. fluid.fetchExpandChildren = function (target, i, segs, source, mergePolicy, miniWorld, options) { if (source.expander /* && source.expander.type */) { // possible expander at top level var expanded = fluid.expandExpander(target, source, options); if (options.freeRoot || fluid.isPrimitive(expanded) || fluid.isDOMish(expanded) || !fluid.isPlainObject(expanded) || (fluid.isArrayable(expanded) ^ fluid.isArrayable(target))) { return expanded; } else { // make an attempt to preserve the root reference if possible $.extend(true, target, expanded); } } // NOTE! This expects that RHS is concrete! For material input to "expansion" this happens to be the case, but is not // true for other algorithms. Inconsistently, this algorithm uses "sourceStrategy" below. In fact, this "fetchChildren" // operation looks like it is a fundamental primitive of the system. We do call "deliverer" early which enables correct // reference to parent nodes up the tree - however, anyone processing a tree IN THE CHAIN requires that it is produced // concretely at the point STRATEGY returns. Which in fact it is............... fluid.each(source, function (newSource, key) { if (newSource === undefined) { target[key] = undefined; // avoid ever dispatching to ourselves with undefined source } else if (key !== "expander") { segs[i] = key; options.strategy(target, key, i + 1, segs, source, mergePolicy, miniWorld); } }); return target; }; // TODO: This method is unnecessary and will quadratic inefficiency if RHS block is not concrete. // The driver should detect "homogeneous uni-strategy trundling" and agree to preserve the extra // "cursor arguments" which should be advertised somehow (at least their number) function regenerateCursor (source, segs, limit, sourceStrategy) { for (var i = 0; i < limit; ++ i) { // copy segs to avoid aliasing with FLUID-5243 source = sourceStrategy(source, segs[i], i, fluid.makeArray(segs)); } return source; } // unsupported, NON-API function fluid.isUnexpandable = function (source) { return fluid.isPrimitive(source) || fluid.isComponent(source) || source.nodeType !== undefined || source.jquery || !fluid.isPlainObject(source); }; // unsupported, NON-API function fluid.expandSource = function (options, target, i, segs, deliverer, source, policy, miniWorld, recurse) { var expanded, isTrunk, isLate; var thisPolicy = fluid.derefMergePolicy(policy); if (typeof (source) === "string" && !thisPolicy.noexpand) { if (!options.defaultEL || source.charAt(0) === "{") { // hard-code this for performance fluid.pushActivity("expandContextValue", "expanding context value %source held at path %path", {source: source, path: fluid.path.apply(null, segs.slice(0, i))}); expanded = fluid.resolveContextValue(source, options); fluid.popActivity(1); } else { expanded = source; } } else if (thisPolicy.noexpand || fluid.isUnexpandable(source)) { expanded = source; } else if (source.expander) { expanded = fluid.expandExpander(deliverer, source, options); } else { if (thisPolicy.preserve) { expanded = source; isLate = true; } else { expanded = fluid.freshContainer(source); } isTrunk = true; } if (!isLate && expanded !== fluid.NO_VALUE) { deliverer(expanded); } if (isTrunk) { recurse(expanded, source, i, segs, policy, miniWorld || isLate); } if (isLate && expanded !== fluid.NO_VALUE) { deliverer(expanded); } return expanded; }; // unsupported, NON-API function fluid.makeExpandStrategy = function (options) { var recurse = function (target, source, i, segs, policy, miniWorld) { return fluid.fetchExpandChildren(target, i || 0, segs || [], source, policy, miniWorld, options); }; var strategy = function (target, name, i, segs, source, policy, miniWorld) { if (i > fluid.strategyRecursionBailout) { fluid.fail("Overflow/circularity in options expansion, current path is ", segs, " at depth " , i, " - please ensure options are not circularly connected, or protect from expansion using the \"noexpand\" policy or expander"); } if (!target) { return; } if (!miniWorld && target.hasOwnProperty(name)) { // bail out if our work has already been done return target[name]; } if (source === undefined) { // recover our state in case this is an external entry point source = regenerateCursor(options.source, segs, i - 1, options.sourceStrategy); policy = regenerateCursor(options.mergePolicy, segs, i - 1, fluid.concreteTrundler); } var thisSource = options.sourceStrategy(source, name, i, segs); var thisPolicy = fluid.concreteTrundler(policy, name); function deliverer(value) { target[name] = value; } return fluid.expandSource(options, target, i, segs, deliverer, thisSource, thisPolicy, miniWorld, recurse); }; options.recurse = recurse; options.strategy = strategy; return strategy; }; fluid.defaults("fluid.makeExpandOptions", { ELstyle: "${}", bareContextRefs: true, target: fluid.inCreationMarker }); // unsupported, NON-API function fluid.makeExpandOptions = function (source, options) { options = $.extend({}, fluid.rawDefaults("fluid.makeExpandOptions"), options); options.defaultEL = options.ELStyle === "${}" && options.bareContextRefs; // optimisation to help expander options.expandSource = function (source) { return fluid.expandSource(options, null, 0, [], fluid.identity, source, options.mergePolicy, false); }; if (!fluid.isUnexpandable(source)) { options.source = source; options.target = fluid.freshContainer(source); options.sourceStrategy = options.sourceStrategy || fluid.concreteTrundler; fluid.makeExpandStrategy(options); options.initter = function () { options.target = fluid.fetchExpandChildren(options.target, 0, [], options.source, options.mergePolicy, false, options); }; } else { // these init immediately since we must deliver a valid root target options.strategy = fluid.concreteTrundler; options.initter = fluid.identity; if (typeof(source) === "string") { options.target = options.expandSource(source); } else { options.target = source; } } return options; }; fluid.expand = function (source, options) { var expandOptions = fluid.makeExpandOptions(source, options); expandOptions.initter(); return expandOptions.target; }; fluid.registerNamespace("fluid.expander"); /** "light" expanders, starting with support functions for the so-called "deferredCall" expanders, which make an arbitrary function call (after expanding arguments) and are then replaced in the configuration with the call results. These will probably be abolished and replaced with equivalent model transformation machinery **/ fluid.expander.deferredCall = function (deliverer, source, options) { var expander = source.expander; var args = (!expander.args || fluid.isArrayable(expander.args))? expander.args : fluid.makeArray(expander.args); args = options.recurse([], args); return fluid.invokeGlobalFunction(expander.func, args); }; fluid.deferredCall = fluid.expander.deferredCall; // put in top namespace for convenience // This one is now positioned as the "universal expander" - default if no type supplied fluid.deferredInvokeCall = function (deliverer, source, options) { var expander = source.expander; var args = fluid.makeArray(expander.args); args = options.recurse([], args); // TODO: risk of double expansion here. embodyDemands will sometimes expand, sometimes not... var funcEntry = expander.func || expander.funcName; var func = options.expandSource(funcEntry) || fluid.recordToApplicable(expander, options.contextThat); if (!func) { fluid.fail("Error in expander record - " + funcEntry + " could not be resolved to a function for component ", options.contextThat); } return func.apply ? func.apply(null, args) : fluid.invoke(func, args, options.contextThat); }; // The "noexpand" expander which simply unwraps one level of expansion and ceases. fluid.expander.noexpand = function (deliverer, source) { return source.expander.value ? source.expander.value : source.expander.tree; }; fluid.noexpand = fluid.expander.noexpand; // TODO: check naming and namespacing })(jQuery, fluid_2_0); ;/* Copyright 2008-2010 University of Cambridge Copyright 2008-2009 University of Toronto Copyright 2010-2011 Lucendo Development Ltd. Copyright 2010-2014 OCAD University Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ var fluid_2_0 = fluid_2_0 || {}; (function ($, fluid) { "use strict"; /** NOTE: The contents of this file are by default NOT PART OF THE PUBLIC FLUID API unless explicitly annotated before the function **/ /** MODEL ACCESSOR ENGINE **/ /** Standard strategies for resolving path segments **/ fluid.model.makeEnvironmentStrategy = function (environment) { return function (root, segment, index) { return index === 0 && environment[segment] ? environment[segment] : undefined; }; }; fluid.model.defaultCreatorStrategy = function (root, segment) { if (root[segment] === undefined) { root[segment] = {}; return root[segment]; } }; fluid.model.defaultFetchStrategy = function (root, segment) { return root[segment]; }; fluid.model.funcResolverStrategy = function (root, segment) { if (root.resolvePathSegment) { return root.resolvePathSegment(segment); } }; fluid.model.traverseWithStrategy = function (root, segs, initPos, config, uncess) { var strategies = config.strategies; var limit = segs.length - uncess; for (var i = initPos; i < limit; ++i) { if (!root) { return root; } var accepted; for (var j = 0; j < strategies.length; ++ j) { accepted = strategies[j](root, segs[i], i + 1, segs); if (accepted !== undefined) { break; // May now short-circuit with stateless strategies } } if (accepted === fluid.NO_VALUE) { accepted = undefined; } root = accepted; } return root; }; /** Returns both the value and the path of the value held at the supplied EL path **/ fluid.model.getValueAndSegments = function (root, EL, config, initSegs) { return fluid.model.accessWithStrategy(root, EL, fluid.NO_VALUE, config, initSegs, true); }; // Very lightweight remnant of trundler, only used in resolvers fluid.model.makeTrundler = function (config) { return function (valueSeg, EL) { return fluid.model.getValueAndSegments(valueSeg.root, EL, config, valueSeg.segs); }; }; fluid.model.getWithStrategy = function (root, EL, config, initSegs) { return fluid.model.accessWithStrategy(root, EL, fluid.NO_VALUE, config, initSegs); }; fluid.model.setWithStrategy = function (root, EL, newValue, config, initSegs) { fluid.model.accessWithStrategy(root, EL, newValue, config, initSegs); }; fluid.model.accessWithStrategy = function (root, EL, newValue, config, initSegs, returnSegs) { // This function is written in this unfortunate style largely for efficiency reasons. In many cases // it should be capable of running with 0 allocations (EL is preparsed, initSegs is empty) if (!fluid.isPrimitive(EL) && !fluid.isArrayable(EL)) { var key = EL.type || "default"; var resolver = config.resolvers[key]; if (!resolver) { fluid.fail("Unable to find resolver of type " + key); } var trundler = fluid.model.makeTrundler(config); // very lightweight trundler for resolvers var valueSeg = {root: root, segs: initSegs}; valueSeg = resolver(valueSeg, EL, trundler); if (EL.path && valueSeg) { // every resolver supports this piece of output resolution valueSeg = trundler(valueSeg, EL.path); } return returnSegs ? valueSeg : (valueSeg ? valueSeg.root : undefined); } else { return fluid.model.accessImpl(root, EL, newValue, config, initSegs, returnSegs, fluid.model.traverseWithStrategy); } }; // Implementation notes: The EL path manipulation utilities here are somewhat more thorough // and expensive versions of those provided in Fluid.js - there is some duplication of // functionality. This is a tradeoff between stability and performance - the versions in // Fluid.js are the most frequently used and do not implement escaping of characters . // as \. and \ as \\ as the versions here. The implementations here are not // performant and are left here partially as an implementation note. Problems will // arise if clients manipulate JSON structures containing "." characters in keys as if they // are models. The basic utilities fluid.path(), fluid.parseEL and fluid.composePath are // the ones recommended for general users and the following implementations will // be upgraded to use regexes in future to make them better alternatives fluid.registerNamespace("fluid.pathUtil"); var getPathSegmentImpl = function (accept, path, i) { var segment = null; // TODO: rewrite this with regexes and replaces if (accept) { segment = ""; } var escaped = false; var limit = path.length; for (; i < limit; ++i) { var c = path.charAt(i); if (!escaped) { if (c === ".") { break; } else if (c === "\\") { escaped = true; } else if (segment !== null) { segment += c; } } else { escaped = false; if (segment !== null) { segment += c; } } } if (segment !== null) { accept[0] = segment; } return i; }; var globalAccept = []; // TODO: serious reentrancy risk here, why is this impl like this? /** A version of fluid.model.parseEL that apples escaping rules - this allows path segments * to contain period characters . - characters "\" and "}" will also be escaped. WARNING - * this current implementation is EXTREMELY slow compared to fluid.model.parseEL and should * not be used in performance-sensitive applications */ // supported, PUBLIC API function fluid.pathUtil.parseEL = function (path) { var togo = []; var index = 0; var limit = path.length; while (index < limit) { var firstdot = getPathSegmentImpl(globalAccept, path, index); togo.push(globalAccept[0]); index = firstdot + 1; } return togo; }; // supported, PUBLIC API function fluid.pathUtil.composeSegment = function (prefix, toappend) { toappend = toappend.toString(); for (var i = 0; i < toappend.length; ++i) { var c = toappend.charAt(i); if (c === "." || c === "\\" || c === "}") { prefix += "\\"; } prefix += c; } return prefix; }; /** Escapes a single path segment by replacing any character ".", "\" or "}" with * itself prepended by \ */ // supported, PUBLIC API function fluid.pathUtil.escapeSegment = function (segment) { return fluid.pathUtil.composeSegment("", segment); }; /** * Compose a prefix and suffix EL path, where the prefix is already escaped. * Prefix may be empty, but not null. The suffix will become escaped. */ // supported, PUBLIC API function fluid.pathUtil.composePath = function (prefix, suffix) { if (prefix.length !== 0) { prefix += "."; } return fluid.pathUtil.composeSegment(prefix, suffix); }; /** * Compose a set of path segments supplied as arguments into an escaped EL expression. Escaped version * of fluid.model.composeSegments */ // supported, PUBLIC API function fluid.pathUtil.composeSegments = function () { var path = ""; for (var i = 0; i < arguments.length; ++ i) { path = fluid.pathUtil.composePath(path, arguments[i]); } return path; }; fluid.model.unescapedParser = { parse: fluid.model.parseEL, compose: fluid.model.composeSegments }; // supported, PUBLIC API record fluid.model.defaultGetConfig = { parser: fluid.model.unescapedParser, strategies: [fluid.model.funcResolverStrategy, fluid.model.defaultFetchStrategy] }; // supported, PUBLIC API record fluid.model.defaultSetConfig = { parser: fluid.model.unescapedParser, strategies: [fluid.model.funcResolverStrategy, fluid.model.defaultFetchStrategy, fluid.model.defaultCreatorStrategy] }; fluid.model.escapedParser = { parse: fluid.pathUtil.parseEL, compose: fluid.pathUtil.composeSegments }; // supported, PUBLIC API record fluid.model.escapedGetConfig = { parser: fluid.model.escapedParser, strategies: [fluid.model.defaultFetchStrategy] }; // supported, PUBLIC API record fluid.model.escapedSetConfig = { parser: fluid.model.escapedParser, strategies: [fluid.model.defaultFetchStrategy, fluid.model.defaultCreatorStrategy] }; /** MODEL COMPONENT HIERARCHY AND RELAY SYSTEM **/ fluid.initSimpleModel = function (that, optionsModel) { that.model = optionsModel || {}; return that.model; }; fluid.initRelayModel = function (that, modelRelayModel) { return modelRelayModel; }; // TODO: This utility compensates for our lack of control over "wave of explosions" initialisation - we may // catch a model when it is apparently "completely initialised" and that's the best we can do, since we have // missed its own initial transaction fluid.isModelComplete = function (that) { return that.model !== fluid.inEvaluationMarker; }; // Enlist this model component as part of the "initial transaction" wave - note that "special transaction" init // is indexed by component, not by applier, and has special record type (complete + initModel), not transaction fluid.enlistModelComponent = function (that) { var instantiator = fluid.getInstantiator(that); var enlist = instantiator.modelTransactions.init[that.id]; if (!enlist) { enlist = { that: that, applier: fluid.getForComponent(that, "applier"), // required for FLUID-5504 even though currently unused complete: fluid.isModelComplete(that) }; instantiator.modelTransactions.init[that.id] = enlist; } return enlist; }; // Utility to coordinate with our crude "oscillation prevention system" which limits each link to 2 updates (presumably // in opposite directions). In the case of the initial transaction, we need to reset the count given that genuine // changes are arising in the system with each new enlisted model. TODO: if we ever get users operating their own // transactions, think of a way to incorporate this into that workflow fluid.clearLinkCounts = function (transRec, relaysAlso) { fluid.each(transRec, function (value, key) { if (typeof(value) === "number") { transRec[key] = 0; } else if (relaysAlso && value.options && typeof(value.options.relayCount) === "number") { value.options.relayCount = 0; } }); }; fluid.sortCompleteLast = function (reca, recb) { return (reca.completeOnInit ? 1 : 0) - (recb.completeOnInit ? 1 : 0); }; // Operate all coordinated transactions by bringing models to their respective initial values, and then commit them all fluid.operateInitialTransaction = function (instantiator, mrec) { var transId = fluid.allocateGuid(); var transRec = fluid.getModelTransactionRec(instantiator, transId); var transac; var transacs = fluid.transform(mrec, function (recel) { transac = recel.that.applier.initiate("init", transId); transRec[recel.that.applier.applierId] = {transaction: transac}; return transac; }); // TODO: This sort has very little effect in any current test (can be replaced by no-op - see FLUID-5339) - but // at least can't be performed in reverse order ("FLUID-3674 event coordination test" will fail) - need more cases var recs = fluid.values(mrec).sort(fluid.sortCompleteLast); fluid.each(recs, function (recel) { var that = recel.that; var transac = transacs[that.id]; if (recel.completeOnInit) { fluid.initModelEvent(that, transac, that.applier.changeListeners.listeners); } else { fluid.each(recel.initModels, function (initModel) { transac.fireChangeRequest({type: "ADD", segs: [], value: initModel}); fluid.clearLinkCounts(transRec, true); }); } var shadow = fluid.shadowForComponent(that); shadow.modelComplete = true; // technically this is a little early, but this flag is only read in fluid.connectModelRelay }); transac.commit(); // committing one representative transaction will commit them all }; // This modelComponent has now concluded initialisation - commit its initialisation transaction if it is the last such in the wave fluid.deenlistModelComponent = function (that) { var instantiator = fluid.getInstantiator(that); var mrec = instantiator.modelTransactions.init; that.model = undefined; // Abuse of the ginger system - in fact it is "currently in evaluation" - we need to return a proper initial model value even if no init occurred yet mrec[that.id].complete = true; // flag means - "complete as in ready to participate in this transaction" var incomplete = fluid.find_if(mrec, function (recel) { return recel.complete !== true; }); if (!incomplete) { fluid.operateInitialTransaction(instantiator, mrec); // NB: Don't call fluid.concludeTransaction since "init" is not a standard record - this occurs in commitRelays for the corresponding genuine record as usual instantiator.modelTransactions.init = {}; } }; fluid.transformToAdapter = function (transform, targetPath) { var basedTransform = {}; basedTransform[targetPath] = transform; return function (trans, newValue /*, sourceSegs, targetSegs */) { // TODO: More efficient model that can only run invalidated portion of transform (need to access changeMap of source transaction) fluid.model.transformWithRules(newValue, basedTransform, {finalApplier: trans}); }; }; fluid.parseModelReference = function (that, ref) { var parsed = fluid.parseContextReference(ref); parsed.segs = that.applier.parseEL(parsed.path); return parsed; }; fluid.parseValidModelReference = function (that, name, ref) { var reject = function (message) { fluid.fail("Error in " + name + ": " + ref + message); }; var parsed, target; if (ref.charAt(0) === "{") { parsed = fluid.parseModelReference(that, ref); if (parsed.segs[0] !== "model") { reject(" must be a reference into a component model beginning with \"model\""); } else { parsed.modelSegs = parsed.segs.slice(1); delete parsed.path; } target = fluid.resolveContext(parsed.context, that); if (!target) { reject(" must be a reference to an existing component"); } } else { target = that; parsed = { path: ref, modelSegs: that.applier.parseEL(ref) }; } if (!target.applier) { fluid.getForComponent(target, ["applier"]); } if (!target.applier) { reject(" must be a reference to a component with a ChangeApplier (descended from fluid.modelComponent)"); } parsed.that = target; parsed.applier = target.applier; // TODO: remove this when the old ChangeApplier is abolished if (!parsed.path) { parsed.path = target.applier.composeSegments.apply(null, parsed.modelSegs); } return parsed; }; // Gets global record for a particular transaction id - looks up applier id to transaction, // as well as looking up source id (linkId in below) to count/true fluid.getModelTransactionRec = function (instantiator, transId) { if (!transId) { fluid.fail("Cannot get transaction record without transaction id"); } var transRec = instantiator.modelTransactions[transId]; if (!transRec && !instantiator.free) { transRec = instantiator.modelTransactions[transId] = {}; transRec.externalChanges = {}; // index by applierId to changePath to listener record } return transRec; }; fluid.recordChangeListener = function (component, applier, sourceListener) { var shadow = fluid.shadowForComponent(component); fluid.recordListener(applier.modelChanged, sourceListener, shadow); }; // Used with various arg combinations from different sources. For standard "implicit relay" or fully lensed relay, // the first 4 args will be set, and "options" will be empty // For a model-dependent relay, this will be used in two halves - firstly, all of the model // sources will bind to the relay transform document itself. In this case the argument "targetApplier" within "options" will be set. // In this case, the component known as "target" is really the source - it is a component reference discovered by parsing the // relay document. // Secondly, the relay itself will schedule an invalidation (as if receiving change to "*" of its source - which may in most // cases actually be empty) and play through its transducer. "Source" component itself is never empty, since it is used for listener // degistration on destruction (check this is correct for external model relay). However, "sourceSegs" may be empty in the case // there is no "source" component registered for the link. This change is played in a "half-transactional" way - that is, we wait // for all other changes in the system to settle before playing the relay document, in order to minimise the chances of multiple // firing and corruption. This is done via the "preCommit" hook registered at top level in establishModelRelay. This listener // is transactional but it does not require the transaction to conclude in order to fire - it may be reused as many times as // required within the "overall" transaction whilst genuine (external) changes continue to arrive. fluid.registerDirectChangeRelay = function (target, targetSegs, source, sourceSegs, linkId, transducer, options) { var instantiator = fluid.getInstantiator(target); var targetApplier = options.targetApplier || target.applier; // implies the target is a relay document var sourceApplier = options.sourceApplier || source.applier; // implies the source is a relay document - listener will be transactional var applierId = targetApplier.applierId; targetSegs = fluid.makeArray(targetSegs); sourceSegs = sourceSegs ? fluid.makeArray(sourceSegs) : sourceSegs; // take copies since originals will be trashed var sourceListener = function (newValue, oldValue, path, changeRequest, trans, applier) { var transId = trans.id; var transRec = fluid.getModelTransactionRec(instantiator, transId); if (applier && trans && !transRec[applier.applierId]) { // don't trash existing record which may contain "options" (FLUID-5397) transRec[applier.applierId] = {transaction: trans}; // enlist the outer user's original transaction } var existing = transRec[applierId]; transRec[linkId] = transRec[linkId] || 0; // Crude "oscillation prevention" system limits each link to maximum of 2 operations per cycle (presumably in opposite directions) var relay = true; // TODO: See FLUID-5303 - we currently disable this check entirely to solve FLUID-5293 - perhaps we might remove link counts entirely if (relay) { ++transRec[linkId]; if (!existing) { var newTrans = targetApplier.initiate("relay", transId); // non-top-level transaction will defeat postCommit existing = transRec[applierId] = {transaction: newTrans, options: options}; } if (transducer && !options.targetApplier) { // TODO: This is just for safety but is still unusual and now abused. The transducer doesn't need the "newValue" since all the transform information // has been baked into the transform document itself. However, we now rely on this special signalling value to make sure we regenerate transforms in // the "forwardAdapter" transducer(existing.transaction, options.sourceApplier ? undefined : newValue, sourceSegs, targetSegs); } else if (newValue !== undefined) { existing.transaction.fireChangeRequest({type: "ADD", segs: targetSegs, value: newValue}); } } }; if (sourceSegs) { sourceApplier.modelChanged.addListener({ isRelay: true, segs: sourceSegs, transactional: options.transactional }, sourceListener); } if (source) { // TODO - we actually may require to register on THREE sources in the case modelRelay is attached to a // component which is neither source nor target. Note there will be problems if source, say, is destroyed and recreated, // and holder is not - relay will in that case be lost. Need to integrate relay expressions with IoCSS. fluid.recordChangeListener(source, sourceApplier, sourceListener); if (target !== source) { fluid.recordChangeListener(target, sourceApplier, sourceListener); } } }; // When called during parsing a contextualised model relay document, these arguments are reversed - "source" refers to the // current component, and "target" refers successively to the various "source" components. // "options" will be transformPackage fluid.connectModelRelay = function (source, sourceSegs, target, targetSegs, options) { var linkId = fluid.allocateGuid(); function enlistComponent(component) { var enlist = fluid.enlistModelComponent(component); if (enlist.complete) { var shadow = fluid.shadowForComponent(component); if (shadow.modelComplete) { enlist.completeOnInit = true; } } } enlistComponent(target); enlistComponent(source); // role of "source" and "target" may have been swapped in a modelRelay document if (options.update) { // it is a call via parseImplicitRelay for a relay document if (options.targetApplier) { // register changes from the model onto changes to the model relay document fluid.registerDirectChangeRelay(source, sourceSegs, target, targetSegs, linkId, null, { transactional: false, targetApplier: options.targetApplier, relayCount: options.relayCount, update: options.update }); } else { // if parsing a contextualised MR, skip the "orthogonal" registration - instead // register the "half-transactional" listener which binds changes from the relay itself onto the target fluid.registerDirectChangeRelay(target, targetSegs, source, [], linkId+"-transform", options.forwardAdapter, {transactional: true, sourceApplier: options.forwardApplier}); } } else { // more efficient branch where relay is uncontextualised fluid.registerDirectChangeRelay(target, targetSegs, source, sourceSegs, linkId, options.forwardAdapter, {transactional: false}); if (sourceSegs) { fluid.registerDirectChangeRelay(source, sourceSegs, target, targetSegs, linkId, options.backwardAdapter, {transactional: false}); } } }; fluid.model.guardedAdapter = function (componentThat, cond, func, args) { // TODO: We can't use fluid.isModelComplete here because of the broken half-transactional system - it may appear that model has arrived halfway through init transaction var isInit = componentThat.modelRelay === fluid.inEvaluationMarker; var condValue = cond[isInit ? "init" : "live"]; if (condValue) { func.apply(null, args); } }; fluid.makeTransformPackage = function (componentThat, transform, sourcePath, targetPath, forwardCond, backwardCond) { var that = { forwardHolder: {model: transform}, backwardHolder: {model: null} }; that.generateAdapters = function (trans) { // can't commit "half-transaction" or events will fire - violate encapsulation in this way that.forwardAdapterImpl = fluid.transformToAdapter(trans ? trans.newHolder.model : that.forwardHolder.model, targetPath); if (sourcePath !== null) { that.backwardHolder.model = fluid.model.transform.invertConfiguration(transform); that.backwardAdapterImpl = fluid.transformToAdapter(that.backwardHolder.model, sourcePath); } }; that.forwardAdapter = function (transaction, newValue) { // create a stable function reference for this possibly changing adapter if (newValue === undefined) { that.generateAdapters(); // TODO: Quick fix for incorrect scheduling of invalidation/transducing // "it so happens" that fluid.registerDirectChangeRelay invokes us with empty newValue in the case of invalidation -> transduction } fluid.model.guardedAdapter(componentThat, forwardCond, that.forwardAdapterImpl, arguments); }; // fired from fluid.model.updateRelays via invalidator event that.runTransform = function (trans) { trans.commit(); // this will reach the special "half-transactional listener" registered in fluid.connectModelRelay, // branch with options.targetApplier - by committing the transaction, we update the relay document in bulk and then cause // it to execute (via "transducer") trans.reset(); }; that.forwardApplier = fluid.makeNewChangeApplier(that.forwardHolder); that.forwardApplier.isRelayApplier = true; // special annotation so these can be discovered in the transaction record that.invalidator = fluid.makeEventFirer({name: "Invalidator for model relay with applier " + that.forwardApplier.applierId}); if (sourcePath !== null) { that.backwardApplier = fluid.makeNewChangeApplier(that.backwardHolder); that.backwardAdapter = function () { fluid.model.guardedAdapter(componentThat, backwardCond, that.backwardAdapterImpl, arguments); }; } that.update = that.invalidator.fire; // necessary so that both routes to fluid.connectModelRelay from here hit the first branch var implicitOptions = { relayCount: 0, // this count is updated in fluid.model.updateRelays targetApplier: that.forwardApplier, // this special field identifies us to fluid.connectModelRelay update: that.update, refCount: 0 }; that.forwardHolder.model = fluid.parseImplicitRelay(componentThat, transform, [], implicitOptions); that.refCount = implicitOptions.refCount; that.generateAdapters(); that.invalidator.addListener(that.generateAdapters); that.invalidator.addListener(that.runTransform); return that; }; fluid.singleTransformToFull = function (singleTransform) { var withPath = $.extend(true, {valuePath: ""}, singleTransform); return { "": { transform: withPath } }; }; fluid.model.relayConditions = { initOnly: {init: true, live: false}, liveOnly: {init: false, live: true}, never: {init: false, live: false}, always: {init: true, live: true} }; fluid.model.parseRelayCondition = function (condition) { return fluid.model.relayConditions[condition || "always"]; }; fluid.parseModelRelay = function (that, mrrec) { var parsedSource = mrrec.source ? fluid.parseValidModelReference(that, "modelRelay record member \"source\"", mrrec.source) : {path: null, modelSegs: null}; var parsedTarget = fluid.parseValidModelReference(that, "modelRelay record member \"target\"", mrrec.target); var transform = mrrec.singleTransform ? fluid.singleTransformToFull(mrrec.singleTransform) : mrrec.transform; if (!transform) { fluid.fail("Cannot parse modelRelay record without element \"singleTransform\" or \"transform\":", mrrec); } var forwardCond = fluid.model.parseRelayCondition(mrrec.forward), backwardCond = fluid.model.parseRelayCondition(mrrec.backward); var transformPackage = fluid.makeTransformPackage(that, transform, parsedSource.path, parsedTarget.path, forwardCond, backwardCond); if (transformPackage.refCount === 0) { // This first call binds changes emitted from the relay ends to each other, synchronously fluid.connectModelRelay(parsedSource.that || that, parsedSource.modelSegs, parsedTarget.that, parsedTarget.modelSegs, { forwardAdapter: transformPackage.forwardAdapter, backwardAdapter: transformPackage.backwardAdapter }); } else { // This second call binds changes emitted from the relay document itself onto the relay ends (using the "half-transactional system") fluid.connectModelRelay(parsedSource.that || that, parsedSource.modelSegs, parsedTarget.that, parsedTarget.modelSegs, transformPackage); } }; fluid.parseImplicitRelay = function (that, modelRec, segs, options) { var value; if (typeof(modelRec) === "string" && modelRec.charAt(0) === "{") { var parsed = fluid.parseModelReference(that, modelRec); var target = fluid.resolveContext(parsed.context, that); if (parsed.segs[0] === "model") { var modelSegs = parsed.segs.slice(1); ++options.refCount; fluid.connectModelRelay(that, segs, target, modelSegs, options); } else { value = fluid.getForComponent(target, parsed.segs); } } else if (fluid.isPrimitive(modelRec) || !fluid.isPlainObject(modelRec)) { value = modelRec; } else if (modelRec.expander && fluid.isPlainObject(modelRec.expander)) { value = fluid.expandOptions(modelRec, that); } else { value = fluid.freshContainer(modelRec); fluid.each(modelRec, function (innerValue, key) { segs.push(key); var innerTrans = fluid.parseImplicitRelay(that, innerValue, segs, options); if (innerTrans !== undefined) { value[key] = innerTrans; } segs.pop(); }); } return value; }; // Conclude the transaction by firing to all external listeners in priority order fluid.model.notifyExternal = function (transRec) { var allChanges = transRec ? fluid.values(transRec.externalChanges) : []; allChanges.sort(fluid.priorityComparator); for (var i = 0; i < allChanges.length; ++ i) { var change = allChanges[i]; var targetApplier = change.args[5]; // NOTE: This argument gets here via fluid.model.storeExternalChange from fluid.notifyModelChanges if (!targetApplier.destroyed) { // 3rd point of guarding for FLUID-5592 change.listener.apply(null, change.args); } } fluid.clearLinkCounts(transRec, true); // "options" structures for relayCount are aliased }; fluid.model.commitRelays = function (instantiator, transactionId) { var transRec = instantiator.modelTransactions[transactionId]; fluid.each(transRec, function (transEl) { // EXPLAIN: This must commit ALL current transactions, not just those for relays - why? if (transEl.transaction) { // some entries are links transEl.transaction.commit("relay"); transEl.transaction.reset(); } }); }; fluid.model.updateRelays = function (instantiator, transactionId) { var transRec = instantiator.modelTransactions[transactionId]; var updates = 0; fluid.each(transRec, function (transEl) { // TODO: integrate the "source" if any into this computation, and fire the relay if it has changed - perhaps by adding a listener // to it that updates changeRecord.changes (assuming we can find it) if (transEl.options && transEl.transaction && transEl.transaction.changeRecord.changes > 0 && transEl.options.relayCount < 2 && transEl.options.update) { transEl.options.relayCount++; fluid.clearLinkCounts(transRec); transEl.options.update(transEl.transaction, transRec); ++updates; } }); return updates; }; fluid.establishModelRelay = function (that, optionsModel, optionsML, optionsMR, applier) { fluid.mergeModelListeners(that, optionsML); var enlist = fluid.enlistModelComponent(that); fluid.each(optionsMR, function (mrrec) { fluid.parseModelRelay(that, mrrec); }); var initModels = fluid.transform(optionsModel, function (modelRec) { return fluid.parseImplicitRelay(that, modelRec, [], {refCount: 0}); }); enlist.initModels = initModels; var instantiator = fluid.getInstantiator(that); function updateRelays(transaction) { while (fluid.model.updateRelays(instantiator, transaction.id) > 0){} } function commitRelays(transaction, applier, code) { if (code !== "relay") { // don't commit relays if this commit is already a relay commit fluid.model.commitRelays(instantiator, transaction.id); } } function concludeTransaction(transaction, applier, code) { if (code !== "relay") { fluid.model.notifyExternal(instantiator.modelTransactions[transaction.id]); delete instantiator.modelTransactions[transaction.id]; } } applier.preCommit.addListener(updateRelays); applier.preCommit.addListener(commitRelays); applier.postCommit.addListener(concludeTransaction); fluid.deenlistModelComponent(that); return applier.holder.model; }; // Grade common to "old" and "new" model components fluid.defaults("fluid.commonModelComponent", { gradeNames: ["fluid.littleComponent", "autoInit"], mergePolicy: { modelListeners: fluid.makeMergeListenersPolicy(fluid.arrayConcatPolicy) } }); // supported, PUBLIC API grade fluid.defaults("fluid.modelComponent", { gradeNames: ["fluid.commonModelComponent", "autoInit"], members: { model: "@expand:fluid.initSimpleModel({that}, {that}.options.model)", applier: "@expand:fluid.makeChangeApplier({that}.model, {that}.options.changeApplierOptions)", modelListeners: "@expand:fluid.mergeModelListeners({that}, {that}.options.modelListeners)" }, mergePolicy: { model: "preserve" } }); // supported, PUBLIC API grade fluid.defaults("fluid.modelRelayComponent", { gradeNames: ["fluid.commonModelComponent", "fluid.eventedComponent", "autoInit"], changeApplierOptions: { relayStyle: true, cullUnchanged: true }, members: { model: "@expand:fluid.initRelayModel({that}, {that}.modelRelay)", applier: "@expand:fluid.makeNewChangeApplier({that}, {that}.options.changeApplierOptions)", modelRelay: "@expand:fluid.establishModelRelay({that}, {that}.options.model, {that}.options.modelListeners, {that}.options.modelRelay, {that}.applier)" }, mergePolicy: { model: { noexpand: true, func: fluid.arrayConcatPolicy }, modelRelay: { noexpand: true, func: fluid.arrayConcatPolicy } } }); // supported, PUBLIC API record fluid.defaults("fluid.standardComponent", { gradeNames: ["fluid.modelComponent", "fluid.eventedComponent", "autoInit"] }); // supported, PUBLIC API record fluid.defaults("fluid.standardRelayComponent", { gradeNames: ["fluid.modelRelayComponent", "autoInit"] }); fluid.modelChangedToChange = function (isNewApplier, args) { var newModel = args[0], oldModel = args[1], path = args[3]; // in 4th position for old applier return isNewApplier ? { value: args[0], oldValue: args[1], path: args[2] } : { value: fluid.get(newModel, path), oldValue: fluid.get(oldModel, path), path: path }; }; fluid.resolveModelListener = function (that, record, isNewApplier) { var togo = function () { if (fluid.isDestroyed(that)) { // first guarding point to resolve FLUID-5592 return; } var change = fluid.modelChangedToChange(isNewApplier, arguments); var args = [change]; var localRecord = {change: change, "arguments": args}; if (record.args) { args = fluid.expandOptions(record.args, that, {}, localRecord); } fluid.event.invokeListener(record.listener, fluid.makeArray(args)); }; fluid.event.impersonateListener(record.listener, togo); return togo; }; fluid.mergeModelListeners = function (that, listeners) { var listenerCount = 0; fluid.each(listeners, function (value, path) { if (typeof(value) === "string") { value = { funcName: value }; } var records = fluid.event.resolveListenerRecord(value, that, "modelListeners", null, false); var parsed = fluid.parseValidModelReference(that, "modelListeners entry", path); var isNewApplier = parsed.applier.preCommit; // Bypass fluid.event.dispatchListener by means of "standard = false" and enter our custom workflow including expanding "change": fluid.each(records.records, function (record) { var func = fluid.resolveModelListener(that, record, isNewApplier); var spec = { listener: func, // for initModelEvent listenerIndex: listenerCount, segs: parsed.modelSegs, path: parsed.path, includeSource: record.includeSource, excludeSource: record.excludeSource, priority: record.priority, guardSource: record.guardSource, // compatibility for obsolete system - will remove with old applier transactional: true }; ++listenerCount; if (record.guardSource) { fluid.addSourceGuardedListener(parsed.applier, spec, record.guardSource, func, "modelChanged", record.namespace, record.softNamespace); } else { parsed.applier.modelChanged.addListener(spec, func, record.namespace, record.softNamespace); } fluid.recordChangeListener(that, parsed.applier, func); function initModelEvent() { if (isNewApplier && fluid.isModelComplete(parsed.that)) { var trans = parsed.applier.initiate("init"); fluid.initModelEvent(that, trans, [spec]); trans.commit(); } } if (that !== parsed.that && !fluid.isModelComplete(that)) { // TODO: Use FLUID-4883 "latched events" when available // Don't confuse the end user by firing their listener before the component is constructed // TODO: Better detection than this is requred - we assume that the target component will not be discovered as part // of the initial transaction wave, but if it is, it will get a double notification - we really need "wave of explosions" // since we are currently too early in initialisation of THIS component in order to tell if other will be found // independently. that.events.onCreate.addListener(initModelEvent); } }); }); }; /** CHANGE APPLIER **/ /** COMMON UTILITIES common between old and new ChangeAppliers **/ /** Add a listener to a ChangeApplier event that only acts in the case the event * has not come from the specified source (typically ourself) * @param modelEvent An model event held by a changeApplier (typically applier.modelChanged) * @param path The path specification to listen to * @param source The source value to exclude (direct equality used) * @param func The listener to be notified of a change * @param [eventName] - optional - the event name to be listened to - defaults to "modelChanged" * @param [namespace] - optional - the event namespace */ fluid.addSourceGuardedListener = function(applier, path, source, func, eventName, namespace, softNamespace) { eventName = eventName || "modelChanged"; var wrapped = function (newValue, oldValue, path, changes) { // TODO: adapt signature if (!applier.hasChangeSource(source, changes)) { return func.apply(null, arguments); } }; fluid.event.impersonateListener(func, wrapped); applier[eventName].addListener(path, wrapped, namespace, softNamespace); }; /** Convenience method to fire a change event to a specified applier, including * a supplied "source" identified (perhaps for use with addSourceGuardedListener) */ fluid.fireSourcedChange = function (applier, path, value, source) { applier.fireChangeRequest({ path: path, value: value, source: source }); }; /** Dispatches a list of changes to the supplied applier */ fluid.requestChanges = function (applier, changes) { for (var i = 0; i < changes.length; ++i) { applier.fireChangeRequest(changes[i]); } }; // Automatically adapts requestChange onto fireChangeRequest fluid.bindRequestChange = function (that) { // The name "requestChange" will be deprecated in 1.5, removed in 2.0 that.requestChange = that.change = function (path, value, type) { var changeRequest = { path: path, value: value, type: type }; that.fireChangeRequest(changeRequest); }; }; fluid.identifyChangeListener = function (listener) { return fluid.event.identifyListener(listener) || listener; }; /** NEW CHANGEAPPLIER IMPLEMENTATION (Will be default in Infusion 2.0 onwards **/ fluid.typeCode = function (totest) { return fluid.isPrimitive(totest) || !fluid.isPlainObject(totest) ? "primitive" : fluid.isArrayable(totest) ? "array" : "object"; }; fluid.model.isChangedPath = function (changeMap, segs) { for (var i = 0; i <= segs.length; ++ i) { if (typeof(changeMap) === "string") { return true; } if (i < segs.length && changeMap) { changeMap = changeMap[segs[i]]; } } return false; }; fluid.model.setChangedPath = function (options, segs, value) { var notePath = function (record) { segs.unshift(record); fluid.model.setSimple(options, segs, value); segs.shift(); }; if (!fluid.model.isChangedPath(options.changeMap, segs)) { ++options.changes; notePath("changeMap"); } if (!fluid.model.isChangedPath(options.deltaMap, segs)) { ++options.deltas; notePath("deltaMap"); } }; fluid.model.fetchChangeChildren = function (target, i, segs, source, options) { fluid.each(source, function (value, key) { segs[i] = key; fluid.model.applyChangeStrategy(target, key, i, segs, value, options); segs.length = i; }); }; // Called with two primitives which are compared for equality. This takes account of "floating point slop" to avoid // continuing to propagate inverted values as changes // TODO: replace with a pluggable implementation fluid.model.isSameValue = function (a, b) { if (typeof(a) !== "number" || typeof(b) !== "number") { return a === b; } else { if (a === b) { return true; } else { var relError = Math.abs((a - b) / b); return relError < 1e-12; // 64-bit floats have approx 16 digits accuracy, this should deal with most reasonable transforms } } }; fluid.model.applyChangeStrategy = function (target, name, i, segs, source, options) { var targetSlot = target[name]; var sourceCode = fluid.typeCode(source); var targetCode = fluid.typeCode(targetSlot); var changedValue = fluid.NO_VALUE; if (sourceCode === "primitive") { if (!fluid.model.isSameValue(targetSlot, source)) { changedValue = source; ++options.unchanged; } } else if (targetCode !== sourceCode || sourceCode === "array" && source.length !== targetSlot.length) { // RH is not primitive - array or object and mismatching or any array rewrite changedValue = fluid.freshContainer(source); } if (changedValue !== fluid.NO_VALUE) { target[name] = changedValue; if (options.changeMap) { fluid.model.setChangedPath(options, segs, options.inverse ? "DELETE" : "ADD"); } } if (sourceCode !== "primitive") { fluid.model.fetchChangeChildren(target[name], i + 1, segs, source, options); } }; fluid.model.stepTargetAccess = function (target, type, segs, startpos, endpos, options) { for (var i = startpos; i < endpos; ++ i) { var oldTrunk = target[segs[i]]; target = fluid.model.traverseWithStrategy(target, segs, i, options[type === "ADD" ? "resolverSetConfig" : "resolverGetConfig"], segs.length - i - 1); if (oldTrunk !== target && options.changeMap) { fluid.model.setChangedPath(options, segs.slice(0, i + 1), "ADD"); } } return {root: target, last: segs[endpos]}; }; fluid.model.defaultAccessorConfig = function (options) { options = options || {}; options.resolverSetConfig = options.resolverSetConfig || fluid.model.defaultSetConfig; options.resolverGetConfig = options.resolverGetConfig || fluid.model.defaultGetConfig; return options; }; // After the 1.5 release, this will replace the old "applyChangeRequest" // Changes: "MERGE" action abolished // ADD/DELETE at root can be destructive // changes tracked in optional final argument holding "changeMap: {}, changes: 0, unchanged: 0" fluid.model.applyHolderChangeRequest = function (holder, request, options) { options = fluid.model.defaultAccessorConfig(options); options.deltaMap = options.changeMap ? {} : null; options.deltas = 0; var length = request.segs.length; var pen, atRoot = length === 0; if (atRoot) { pen = {root: holder, last: "model"}; } else { if (!holder.model) { holder.model = {}; fluid.model.setChangedPath(options, [], options.inverse ? "DELETE" : "ADD"); } pen = fluid.model.stepTargetAccess(holder.model, request.type, request.segs, 0, length - 1, options); } if (request.type === "ADD") { var value = request.value; var segs = fluid.makeArray(request.segs); fluid.model.applyChangeStrategy(pen.root, pen.last, length - 1, segs, value, options, atRoot); } else if (request.type === "DELETE") { if (pen.root && pen.root[pen.last] !== undefined) { delete pen.root[pen.last]; if (options.changeMap) { fluid.model.setChangedPath(options, request.segs, "DELETE"); } } } else { fluid.fail("Unrecognised change type of " + request.type); } return options.deltas ? options.deltaMap : null; }; /** Compare two models for equality using a deep algorithm. It is assumed that both models are JSON-equivalent and do * not contain circular links. * @param modela The first model to be compared * @param modelb The second model to be compared * @param options {Object} If supplied, will receive a map and summary of the change content between the objects. Structure is: * changeMap: {Object/String} An isomorphic map of the object structures to values "ADD" or "DELETE" indicating * that values have been added/removed at that location. Note that in the case the object structure differs at the root, <code>changeMap</code> will hold * the plain String value "ADD" or "DELETE" * changes: {Integer} Counts the number of changes between the objects - The two objects are identical iff <code>changes === 0</code>. * unchanged: {Integer} Counts the number of leaf (primitive) values at which the two objects are identical. Note that the current implementation will * double-count, this summary should be considered indicative rather than precise. * @return <code>true</code> if the models are identical */ // TODO: This algorithm is quite inefficient in that both models will be copied once each // supported, PUBLIC API function fluid.model.diff = function (modela, modelb, options) { options = options || {changes: 0, unchanged: 0, changeMap: {}}; // current algorithm can't avoid the expense of changeMap var typea = fluid.typeCode(modela); var typeb = fluid.typeCode(modelb); var togo; if (typea === "primitive" && typeb === "primitive") { togo = fluid.model.isSameValue(modela, modelb); } else if (typea === "primitive" ^ typeb === "primitive") { togo = false; } else { // Apply both forward and reverse changes - if no changes either way, models are identical // "ADD" reported in the reverse direction must be accounted as a "DELETE" var holdera = { model: fluid.copy(modela) }; fluid.model.applyHolderChangeRequest(holdera, {value: modelb, segs: [], type: "ADD"}, options); var holderb = { model: fluid.copy(modelb) }; options.inverse = true; fluid.model.applyHolderChangeRequest(holderb, {value: modela, segs: [], type: "ADD"}, options); togo = options.changes === 0; } if (togo === false && options.changes === 0) { // catch all primitive cases options.changes = 1; options.changeMap = modelb === undefined ? "DELETE" : "ADD"; } else if (togo === true && options.unchanged === 0) { options.unchanged = 1; } return togo; }; // Here we only support for now very simple expressions which have at most one // wildcard which must appear in the final segment fluid.matchChanges = function (changeMap, specSegs, newHolder) { var root = newHolder.model; var map = changeMap; var outSegs = ["model"]; var wildcard = false; var togo = []; for (var i = 0; i < specSegs.length; ++ i) { var seg = specSegs[i]; if (seg === "*") { if (i === specSegs.length - 1) { wildcard = true; } else { fluid.fail("Wildcard specification in modelChanged listener is only supported for the final path segment: " + specSegs.join(".")); } } else { outSegs.push(seg); map = fluid.isPrimitive(map) ? map : map[seg]; root = root ? root[seg] : undefined; } } if (map) { if (wildcard) { fluid.each(root, function (value, key) { togo.push(outSegs.concat(key)); }); } else { togo.push(outSegs); } } return togo; }; fluid.storeExternalChange = function (transRec, applier, invalidPath, spec, args) { var pathString = applier.composeSegments.apply(null, invalidPath); var keySegs = [applier.applierId, fluid.event.identifyListener(spec.listener), spec.listenerIndex, pathString]; var keyString = keySegs.join("|"); // These are unbottled in fluid.concludeTransaction transRec.externalChanges[keyString] = {listener: spec.listener, priority: spec.priority, args: args}; }; fluid.isExcludedChangeSource = function (transaction, spec) { if (!spec.excludeSource) { // mergeModelListeners initModelEvent fabricates a fake spec that bypasses processing return false; } var excluded = spec.excludeSource["*"]; for (var source in transaction.sources) { if (spec.excludeSource[source]) { excluded = true; } if (spec.includeSource[source]) { excluded = false; } } return excluded; }; fluid.notifyModelChanges = function (listeners, changeMap, newHolder, oldHolder, changeRequest, transaction, applier, that) { var instantiator = fluid.getInstantiator(that); var transRec = transaction && fluid.getModelTransactionRec(instantiator, transaction.id); for (var i = 0; i < listeners.length; ++ i) { var spec = listeners[i]; var invalidPaths = fluid.matchChanges(changeMap, spec.segs, newHolder); for (var j = 0; j < invalidPaths.length; ++ j) { if (applier.destroyed) { // 2nd guarding point for FLUID-5592 return; } var invalidPath = invalidPaths[j]; spec.listener = fluid.event.resolveListener(spec.listener); // TODO: process namespace and softNamespace rules, and propagate "sources" in 4th argument var args = [fluid.model.getSimple(newHolder, invalidPath), fluid.model.getSimple(oldHolder, invalidPath), invalidPath.slice(1), changeRequest, transaction, applier]; // FLUID-5489: Do not notify of null changes which were reported as a result of invalidating a higher path // TODO: We can improve greatly on efficiency by i) reporting a special code from fluid.matchChanges which signals the difference between invalidating a higher and lower path, // ii) improving fluid.model.diff to create fewer intermediate structures and no copies // TODO: The relay invalidation system is broken and must always be notified (branch 1) - since our old/new value detection is based on the wrong (global) timepoints in the transaction here, // rather than the "last received model" by the holder of the transform document if (!spec.isRelay) { var isNull = fluid.model.diff(args[0], args[1]); if (isNull) { continue; } var sourceExcluded = fluid.isExcludedChangeSource(transaction, spec); if (sourceExcluded) { continue; } } if (transRec && !spec.isRelay && spec.transactional) { // bottle up genuine external changes so we can sort and dedupe them later fluid.storeExternalChange(transRec, applier, invalidPath, spec, args); } else { spec.listener.apply(null, args); } } } }; fluid.bindELMethods = function (applier) { applier.parseEL = function (EL) { return fluid.model.pathToSegments(EL, applier.options.resolverSetConfig); }; applier.composeSegments = function () { return applier.options.resolverSetConfig.parser.compose.apply(null, arguments); }; }; fluid.initModelEvent = function (that, trans, listeners) { fluid.notifyModelChanges(listeners, "ADD", trans.oldHolder, fluid.emptyHolder, null, trans, that); }; fluid.emptyHolder = { model: undefined }; fluid.makeNewChangeApplier = function (holder, options) { options = fluid.model.defaultAccessorConfig(options); var applierId = fluid.allocateGuid(); var that = { applierId: applierId, holder: holder, changeListeners: { listeners: [], transListeners: [] }, options: options, modelChanged: {}, preCommit: fluid.makeEventFirer({name: "preCommit event for ChangeApplier " }), postCommit: fluid.makeEventFirer({name: "postCommit event for ChangeApplier "}) }; function preFireChangeRequest(changeRequest) { if (!changeRequest.type) { changeRequest.type = "ADD"; } changeRequest.segs = changeRequest.segs || that.parseEL(changeRequest.path); } that.destroy = function () { that.preCommit.destroy(); that.postCommit.destroy(); that.destroyed = true; }; that.modelChanged.addListener = function (spec, listener, namespace, softNamespace) { if (typeof(spec) === "string") { spec = {path: spec}; } else { spec = fluid.copy(spec); } spec.id = fluid.event.identifyListener(listener); spec.namespace = namespace; spec.softNamespace = softNamespace; if (typeof(listener) === "string") { // TODO: replicate this nonsense from Fluid.js until we remember its purpose listener = {globalName: listener}; } spec.listener = listener; if (spec.transactional !== false) { spec.transactional = true; } spec.segs = spec.segs || that.parseEL(spec.path); var collection = that.changeListeners[spec.transactional ? "transListeners" : "listeners"]; spec.excludeSource = fluid.arrayToHash(fluid.makeArray(spec.excludeSource || (spec.includeSource ? "*" : undefined))); spec.includeSource = fluid.arrayToHash(fluid.makeArray(spec.includeSource)); spec.priority = fluid.event.mapPriority(spec.priority, collection.length); collection.push(spec); }; that.modelChanged.removeListener = function (listener) { var id = fluid.event.identifyListener(listener); var namespace = typeof(listener) === "string" ? listener: null; var removePred = function (record) { return record.id === id || record.namespace === namespace; }; fluid.remove_if(that.changeListeners.listeners, removePred); fluid.remove_if(that.changeListeners.transListeners, removePred); }; that.modelChanged.isRelayEvent = true; // TODO: cheap helper for IoC testing framework - remove when old ChangeApplier goes that.fireChangeRequest = function (changeRequest) { var ation = that.initiate(); ation.fireChangeRequest(changeRequest); ation.commit(); }; that.initiate = function (source, transactionId) { source = source || "local"; var defeatPost = source === "relay"; // defeatPost is supplied for all non-top-level transactions var trans = { instanceId: fluid.allocateGuid(), // for debugging only id: transactionId || fluid.allocateGuid(), sources: {}, changeRecord: { resolverSetConfig: options.resolverSetConfig, // here to act as "options" in applyHolderChangeRequest resolverGetConfig: options.resolverGetConfig }, reset: function () { trans.oldHolder = holder; trans.newHolder = { model: fluid.copy(holder.model) }; trans.changeRecord.changes = 0; trans.changeRecord.unchanged = 0; // just for type consistency - we don't use these values in the ChangeApplier trans.changeRecord.changeMap = {}; }, commit: function (code) { that.preCommit.fire(trans, that, code); if (trans.changeRecord.changes > 0) { var oldHolder = {model: holder.model}; holder.model = trans.newHolder.model; fluid.notifyModelChanges(that.changeListeners.transListeners, trans.changeRecord.changeMap, holder, oldHolder, null, trans, that, holder); } if (!defeatPost) { that.postCommit.fire(trans, that, code); } }, fireChangeRequest: function (changeRequest) { preFireChangeRequest(changeRequest); changeRequest.transactionId = trans.id; var deltaMap = fluid.model.applyHolderChangeRequest(trans.newHolder, changeRequest, trans.changeRecord); fluid.notifyModelChanges(that.changeListeners.listeners, deltaMap, trans.newHolder, holder, changeRequest, trans, that, holder); } }; trans.sources[source] = true; trans.reset(); fluid.bindRequestChange(trans); return trans; }; that.hasChangeSource = function (source, changes) { // compatibility for old API return changes ? changes[source] : false; }; fluid.bindRequestChange(that); fluid.bindELMethods(that); return that; }; /** OLD CHANGEAPPLIER IMPLEMENTATION (Infusion 1.5 and before - this will be removed on Fluid 2.0) **/ /** Parses a path segment, following escaping rules, starting from character index i in the supplied path */ fluid.pathUtil.getPathSegment = function (path, i) { getPathSegmentImpl(globalAccept, path, i); return globalAccept[0]; }; /** Returns just the head segment of an EL path */ fluid.pathUtil.getHeadPath = function (path) { return fluid.pathUtil.getPathSegment(path, 0); }; /** Returns all of an EL path minus its first segment - if the path consists of just one segment, returns "" */ fluid.pathUtil.getFromHeadPath = function (path) { var firstdot = getPathSegmentImpl(null, path, 0); return firstdot === path.length ? "" : path.substring(firstdot + 1); }; function lastDotIndex(path) { // TODO: proper escaping rules return path.lastIndexOf("."); } /** Returns all of an EL path minus its final segment - if the path consists of just one segment, returns "" - * WARNING - this method does not follow escaping rules */ fluid.pathUtil.getToTailPath = function (path) { var lastdot = lastDotIndex(path); return lastdot === -1 ? "" : path.substring(0, lastdot); }; /** Returns the very last path component of an EL path * WARNING - this method does not follow escaping rules */ fluid.pathUtil.getTailPath = function (path) { var lastdot = lastDotIndex(path); return fluid.pathUtil.getPathSegment(path, lastdot + 1); }; /** Helpful utility for use in resolvers - matches a path which has already been * parsed into segments **/ fluid.pathUtil.matchSegments = function (toMatch, segs, start, end) { if (end - start !== toMatch.length) { return false; } for (var i = start; i < end; ++ i) { if (segs[i] !== toMatch[i - start]) { return false; } } return true; }; /** Determine the path by which a given path is nested within another **/ // TODO: This utility is not used in the framework, and will cease to be useful in client code // once we move over to the declarative system for change binding fluid.pathUtil.getExcessPath = function (base, longer) { var index = longer.indexOf(base); if (index !== 0) { fluid.fail("Path " + base + " is not a prefix of path " + longer); } if (base.length === longer.length) { return ""; } if (longer[base.length] !== ".") { fluid.fail("Path " + base + " is not properly nested in path " + longer); } return longer.substring(base.length + 1); }; /** Determines whether a particular EL path matches a given path specification. * The specification consists of a path with optional wildcard segments represented by "*". * @param spec (string) The specification to be matched * @param path (string) The path to be tested * @param exact (boolean) Whether the path must exactly match the length of the specification in * terms of path segments in order to count as match. If exact is falsy, short specifications will * match all longer paths as if they were padded out with "*" segments * @return (array of string) The path segments which matched the specification, or <code>null</code> if there was no match */ fluid.pathUtil.matchPath = function (spec, path, exact) { var togo = []; while (true) { if (((path === "") ^ (spec === "")) && exact) { return null; } // FLUID-4625 - symmetry on spec and path is actually undesirable, but this // quickly avoids at least missed notifications - improved (but slower) // implementation should explode composite changes if (!spec || !path) { break; } var spechead = fluid.pathUtil.getHeadPath(spec); var pathhead = fluid.pathUtil.getHeadPath(path); // if we fail to match on a specific component, fail. if (spechead !== "*" && spechead !== pathhead) { return null; } togo.push(pathhead); spec = fluid.pathUtil.getFromHeadPath(spec); path = fluid.pathUtil.getFromHeadPath(path); } return togo; }; fluid.model.isNullChange = function (model, request, resolverGetConfig) { if (request.type === "ADD" && !request.forceChange) { var existing = fluid.get(model, request.segs, resolverGetConfig); if (existing === request.value) { return true; } } }; /** Applies the supplied ChangeRequest object directly to the supplied model. */ fluid.model.applyChangeRequest = function (model, request, resolverSetConfig) { var pen = fluid.model.accessWithStrategy(model, request.path, fluid.VALUE, resolverSetConfig || fluid.model.defaultSetConfig, null, true); var last = pen.segs[pen.segs.length - 1]; if (request.type === "ADD" || request.type === "MERGE") { if (pen.segs.length === 0 || (request.type === "MERGE" && pen.root[last])) { if (request.type === "ADD") { fluid.clear(pen.root); } $.extend(true, pen.segs.length === 0 ? pen.root : pen.root[last], request.value); } else { pen.root[last] = request.value; } } else if (request.type === "DELETE") { if (pen.segs.length === 0) { fluid.clear(pen.root); } else { delete pen.root[last]; } } }; // Utility used for source tracking in changeApplier function sourceWrapModelChanged(modelChanged, threadLocal) { return function (changeRequest) { var sources = threadLocal().sources; var args = arguments; var source = changeRequest.source || ""; fluid.tryCatch(function () { if (sources[source] === undefined) { sources[source] = 0; } ++sources[source]; modelChanged.apply(null, args); }, null, function() { --sources[source]; }); }; } /** The core creator function constructing ChangeAppliers. See API documentation * at http://wiki.fluidproject.org/display/fluid/ChangeApplier+API for the various * options supported in the options structure */ fluid.makeChangeApplier = function (model, options) { return fluid.makeHolderChangeApplier({model: model}, options); }; /** Make a "new-style" ChangeApplier that allows the base model reference to be overwritten. This is * re-read on every access from the object "holder" (in typical usage, the component owning the * ChangeApplier). This implementation will be removed after the 1.5 release */ fluid.makeHolderChangeApplier = function (holder, options) { options = fluid.model.defaultAccessorConfig(options); var baseEvents = { guards: fluid.makeEventFirer({preventable: true, name: "guard event"}), postGuards: fluid.makeEventFirer({preventable: true, name: "postGuard event"}), modelChanged: fluid.makeEventFirer({name: "modelChanged event"}) }; var threadLocal = fluid.threadLocal(function() { return {sources: {}};}); var that = { // For now, we don't use "id" to avoid confusing component detection which uses // a simple algorithm looking for that field applierId: fluid.allocateGuid(), holder: holder, options: options, destroy: fluid.identity // dummy function to avoid confusing FLUID-5592 code - we don't support this subtlety for old appliers }; function makeGuardWrapper(cullUnchanged) { if (!cullUnchanged) { return null; } var togo = function (guard) { return function (model, changeRequest, internalApplier) { var oldRet = guard(model, changeRequest, internalApplier); if (oldRet === false) { return false; } else { if (fluid.model.isNullChange(model, changeRequest)) { togo.culled = true; return false; } } }; }; return togo; } function wrapListener(listener, spec) { var pathSpec = spec; var transactional = false; var priority = Number.MAX_VALUE; if (typeof (spec) === "string") { spec = {path: spec}; } pathSpec = spec.path; transactional = spec.transactional; if (spec.priority !== undefined) { priority = spec.priority; } if (pathSpec.charAt(0) === "!") { transactional = true; pathSpec = pathSpec.substring(1); } var wrapped = function (changePath, fireSpec, accum) { var guid = fluid.event.identifyListener(listener); var exist = fireSpec.guids[guid]; if (!exist || !accum) { var match = fluid.pathUtil.matchPath(pathSpec, changePath); if (match !== null) { var record = { match: match, pathSpec: pathSpec, listener: listener, priority: priority, transactional: transactional }; if (accum) { record.accumulate = [accum]; } fireSpec.guids[guid] = record; var collection = transactional ? "transListeners" : "listeners"; fireSpec[collection].push(record); fireSpec.all.push(record); } } else if (accum) { if (!exist.accumulate) { exist.accumulate = []; } exist.accumulate.push(accum); } }; fluid.event.impersonateListener(listener, wrapped); return wrapped; } function fireFromSpec(name, fireSpec, args, category, wrapper) { return baseEvents[name].fireToListeners(fireSpec[category], args, wrapper); } function fireComparator(recA, recB) { return recA.priority - recB.priority; } function prepareFireEvent(name, changePath, fireSpec, accum) { baseEvents[name].fire(changePath, fireSpec, accum); fireSpec.all.sort(fireComparator); fireSpec.listeners.sort(fireComparator); fireSpec.transListeners.sort(fireComparator); } function makeFireSpec() { return {guids: {}, all: [], listeners: [], transListeners: []}; } function getFireSpec(name, changePath) { var fireSpec = makeFireSpec(); prepareFireEvent(name, changePath, fireSpec); return fireSpec; } function fireEvent(name, changePath, args, wrapper) { var fireSpec = getFireSpec(name, changePath); return fireFromSpec(name, fireSpec, args, "all", wrapper); } function adaptListener(that, name) { that[name] = { addListener: function (spec, listener, namespace, softNamespace) { baseEvents[name].addListener(wrapListener(listener, spec), namespace, null, null, softNamespace); }, removeListener: function (listener) { baseEvents[name].removeListener(listener); } }; } adaptListener(that, "guards"); adaptListener(that, "postGuards"); adaptListener(that, "modelChanged"); function preFireChangeRequest(changeRequest) { if (!changeRequest.type) { changeRequest.type = "ADD"; } changeRequest.segs = that.parseEL(changeRequest.path); } var bareApplier = { fireChangeRequest: function (changeRequest) { that.fireChangeRequest(changeRequest, true); } }; fluid.bindRequestChange(bareApplier); that.fireChangeRequest = function (changeRequest) { preFireChangeRequest(changeRequest); var ation = that.initiate(); ation.fireChangeRequest(changeRequest); ation.commit(); }; that.fireChangeRequest = sourceWrapModelChanged(that.fireChangeRequest, threadLocal); fluid.bindRequestChange(that); fluid.bindELMethods(that); // TODO: modelChanged has been moved to new model for firing. Once we abolish "guards", fireAgglomerated can go too. // Possibly also all the prepareFireEvent/wrapListener/fireSpec nonsense too. function fireAgglomerated(eventName, formName, changes, args, accpos, matchpos) { var fireSpec = makeFireSpec(); for (var i = 0; i < changes.length; ++i) { prepareFireEvent(eventName, changes[i].path, fireSpec, changes[i]); } for (var j = 0; j < fireSpec[formName].length; ++j) { var spec = fireSpec[formName][j]; if (accpos !== undefined) { args[accpos] = spec.accumulate; } if (matchpos !== undefined) { args[matchpos] = spec.match; } var ret = spec.listener.apply(null, args); if (ret === false) { return false; } } } that.initiate = function (newModel) { var cancelled = false; var changes = []; if (options.thin) { newModel = holder.model; } else { newModel = newModel || {}; fluid.model.copyModel(newModel, holder.model); } var ation = { commit: function () { var oldModel; if (cancelled) { return false; } var ret = fireAgglomerated("postGuards", "transListeners", changes, [newModel, null, ation], 1); if (ret === false || cancelled) { return false; } if (options.thin) { oldModel = holder.model; } else { oldModel = {}; fluid.model.copyModel(oldModel, holder.model); fluid.clear(holder.model); fluid.model.copyModel(holder.model, newModel); } fireAgglomerated("modelChanged", "all", changes, [holder.model, oldModel, null, null], 2, 3); }, fireChangeRequest: function (changeRequest) { preFireChangeRequest(changeRequest); if (options.cullUnchanged && fluid.model.isNullChange(holder.model, changeRequest, options.resolverGetConfig)) { return; } var wrapper = makeGuardWrapper(options.cullUnchanged); var prevent = fireEvent("guards", changeRequest.path, [newModel, changeRequest, ation], wrapper); if (prevent === false && !(wrapper && wrapper.culled)) { cancelled = true; } if (!cancelled) { if (!(wrapper && wrapper.culled)) { fluid.model.applyChangeRequest(newModel, changeRequest, options.resolverSetConfig); changes.push(changeRequest); } } } }; ation.fireChangeRequest = sourceWrapModelChanged(ation.fireChangeRequest, threadLocal); fluid.bindRequestChange(ation); return ation; }; that.hasChangeSource = function (source) { return threadLocal().sources[source] > 0; }; return that; }; /** Old "SuperApplier" implementation - will be removed in 1.5 **/ fluid.makeSuperApplier = function () { var subAppliers = []; var that = {}; that.addSubApplier = function (path, subApplier) { subAppliers.push({path: path, subApplier: subApplier}); }; that.fireChangeRequest = function (request) { for (var i = 0; i < subAppliers.length; ++i) { var path = subAppliers[i].path; if (request.path.indexOf(path) === 0) { var subpath = request.path.substring(path.length + 1); var subRequest = fluid.copy(request); subRequest.path = subpath; // TODO: Deal with the as yet unsupported case of an EL rvalue DAR subAppliers[i].subApplier.fireChangeRequest(subRequest); } } }; fluid.bindRequestChange(that); return that; }; fluid.attachModel = function (baseModel, path, model) { var segs = fluid.model.parseEL(path); for (var i = 0; i < segs.length - 1; ++i) { var seg = segs[i]; var subModel = baseModel[seg]; if (!subModel) { baseModel[seg] = subModel = {}; } baseModel = subModel; } baseModel[segs[segs.length - 1]] = model; }; fluid.assembleModel = function (modelSpec) { var model = {}; var superApplier = fluid.makeSuperApplier(); var togo = {model: model, applier: superApplier}; for (var path in modelSpec) { var rec = modelSpec[path]; fluid.attachModel(model, path, rec.model); if (rec.applier) { superApplier.addSubApplier(path, rec.applier); } } return togo; }; })(jQuery, fluid_2_0); ;/* Copyright 2010 University of Toronto Copyright 2010-2011 OCAD University Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ var fluid_2_0 = fluid_2_0 || {}; var fluid = fluid || fluid_2_0; (function ($, fluid) { "use strict"; fluid.registerNamespace("fluid.model.transform"); /** Grade definitions for standard transformation function hierarchy **/ fluid.defaults("fluid.transformFunction", { gradeNames: "fluid.function" }); // uses standard layout and workflow involving inputPath fluid.defaults("fluid.standardInputTransformFunction", { gradeNames: "fluid.transformFunction" }); fluid.defaults("fluid.standardOutputTransformFunction", { gradeNames: "fluid.transformFunction" }); fluid.defaults("fluid.multiInputTransformFunction", { gradeNames: "fluid.transformFunction" }); // uses the standard layout and workflow involving inputPath and outputPath fluid.defaults("fluid.standardTransformFunction", { gradeNames: ["fluid.standardInputTransformFunction", "fluid.standardOutputTransformFunction"] }); fluid.defaults("fluid.lens", { gradeNames: "fluid.transformFunction", invertConfiguration: null // this function method returns "inverted configuration" rather than actually performing inversion // TODO: harmonise with strategy used in VideoPlayer_framework.js }); /*********************************** * Base utilities for transformers * ***********************************/ // unsupported, NON-API function fluid.model.transform.pathToRule = function (inputPath) { return { transform: { type: "fluid.transforms.value", inputPath: inputPath } }; }; // unsupported, NON-API function fluid.model.transform.literalValueToRule = function (value) { return { transform: { type: "fluid.transforms.literalValue", value: value } }; }; /** Accepts two fully escaped paths, either of which may be empty or null **/ fluid.model.composePaths = function (prefix, suffix) { prefix = prefix === 0 ? "0" : prefix || ""; suffix = suffix === 0 ? "0" : suffix || ""; return !prefix ? suffix : (!suffix ? prefix : prefix + "." + suffix); }; fluid.model.transform.accumulateInputPath = function (inputPath, transform, paths) { if (inputPath !== undefined) { paths.push(fluid.model.composePaths(transform.inputPrefix, inputPath)); } }; fluid.model.transform.accumulateStandardInputPath = function (input, transformSpec, transform, paths) { fluid.model.transform.getValue(undefined, transformSpec[input], transform); fluid.model.transform.accumulateInputPath(transformSpec[input + "Path"], transform, paths); }; fluid.model.transform.accumulateMultiInputPaths = function (inputVariables, transformSpec, transform, paths) { fluid.each(inputVariables, function (v, k) { fluid.model.transform.accumulateStandardInputPath(k, transformSpec, transform, paths); }); }; fluid.model.transform.getValue = function (inputPath, value, transform) { var togo; if (inputPath !== undefined) { // NB: We may one day want to reverse the crazy jQuery-like convention that "no path means root path" togo = fluid.get(transform.source, fluid.model.composePaths(transform.inputPrefix, inputPath), transform.resolverGetConfig); } if (togo === undefined) { togo = fluid.isPrimitive(value) ? value : transform.expand(value); } return togo; }; // distinguished value which indicates that a transformation rule supplied a // non-default output path, and so the user should be prevented from making use of it // in a compound transform definition fluid.model.transform.NONDEFAULT_OUTPUT_PATH_RETURN = {}; fluid.model.transform.setValue = function (userOutputPath, value, transform) { // avoid crosslinking to input object - this might be controlled by a "nocopy" option in future var toset = fluid.copy(value); var outputPath = fluid.model.composePaths(transform.outputPrefix, userOutputPath); // TODO: custom resolver config here to create non-hash output model structure if (toset !== undefined) { transform.applier.requestChange(outputPath, toset); } return userOutputPath ? fluid.model.transform.NONDEFAULT_OUTPUT_PATH_RETURN : toset; }; /* Resolves the <key> given as parameter by looking up the path <key>Path in the object * to be transformed. If not present, it resolves the <key> by using the literal value if primitive, * or expanding otherwise. <def> defines the default value if unableto resolve the key. If no * default value is given undefined is returned */ fluid.model.transform.resolveParam = function (transformSpec, transform, key, def) { var val = fluid.model.transform.getValue(transformSpec[key + "Path"], transformSpec[key], transform); return (val !== undefined) ? val : def; }; // Compute a "match score" between two pieces of model material, with 0 indicating a complete mismatch, and // higher values indicating increasingly good matches fluid.model.transform.matchValue = function (expected, actual, partialMatches) { var stats = {changes: 0, unchanged: 0, changeMap: {}}; fluid.model.diff(expected, actual, stats); // i) a pair with 0 matches counts for 0 in all cases // ii) without "partial match mode" (the default), we simply count matches, with any mismatch giving 0 // iii) with "partial match mode", a "perfect score" in the top 24 bits is // penalised for each mismatch, with a positive score of matches store in the bottom 24 bits return stats.unchanged === 0 ? 0 : (partialMatches ? 0xffffff000000 - 0x1000000 * stats.changes + stats.unchanged : (stats.changes ? 0 : 0xffffff000000 + stats.unchanged)); }; fluid.firstDefined = function (a, b) { return a === undefined ? b : a; }; // TODO: prefixApplier is a transform which is currently unused and untested fluid.model.transform.prefixApplier = function (transformSpec, transform) { if (transformSpec.inputPrefix) { transform.inputPrefixOp.push(transformSpec.inputPrefix); } if (transformSpec.outputPrefix) { transform.outputPrefixOp.push(transformSpec.outputPrefix); } transform.expand(transformSpec.value); if (transformSpec.inputPrefix) { transform.inputPrefixOp.pop(); } if (transformSpec.outputPrefix) { transform.outputPrefixOp.pop(); } }; fluid.defaults("fluid.model.transform.prefixApplier", { gradeNames: ["fluid.transformFunction"] }); // unsupported, NON-API function fluid.model.makePathStack = function (transform, prefixName) { var stack = transform[prefixName + "Stack"] = []; transform[prefixName] = ""; return { push: function (prefix) { var newPath = fluid.model.composePaths(transform[prefixName], prefix); stack.push(transform[prefixName]); transform[prefixName] = newPath; }, pop: function () { transform[prefixName] = stack.pop(); } }; }; fluid.model.transform.aliasStandardInput = function (transformSpec) { return { // alias input and value, and their paths value: transformSpec.value === undefined ? transformSpec.input : transformSpec.value, valuePath: transformSpec.valuePath === undefined ? transformSpec.inputPath : transformSpec.valuePath }; }; // unsupported, NON-API function fluid.model.transform.doTransform = function (transformSpec, transform, transformOpts) { var expdef = transformOpts.defaults; var transformFn = fluid.getGlobalValue(transformOpts.typeName); if (typeof(transformFn) !== "function") { fluid.fail("Transformation record specifies transformation function with name " + transformSpec.type + " which is not a function - ", transformFn); } if (!fluid.hasGrade(expdef, "fluid.transformFunction")) { // If no suitable grade is set up, assume that it is intended to be used as a standardTransformFunction expdef = fluid.defaults("fluid.standardTransformFunction"); } var transformArgs = [transformSpec, transform]; if (fluid.hasGrade(expdef, "fluid.standardInputTransformFunction")) { var valueHolder = fluid.model.transform.aliasStandardInput(transformSpec); var expanded = fluid.model.transform.getValue(valueHolder.valuePath, valueHolder.value, transform); transformArgs.unshift(expanded); // if the function has no input, the result is considered undefined, and this is returned if (expanded === undefined) { return undefined; } } else if (fluid.hasGrade(expdef, "fluid.multiInputTransformFunction")) { var inputs = {}; fluid.each(expdef.inputVariables, function (v, k) { inputs[k] = function () { var input = fluid.model.transform.getValue(transformSpec[k + "Path"], transformSpec[k], transform); // if no match, assign default if one exists (v != null) input = (input === undefined && v !== null) ? v : input; return input; }; }); transformArgs.unshift(inputs); } var transformed = transformFn.apply(null, transformArgs); if (fluid.hasGrade(expdef, "fluid.standardOutputTransformFunction")) { // "doOutput" flag is currently set nowhere, but could be used in future var outputPath = transformSpec.outputPath !== undefined ? transformSpec.outputPath : (transformOpts.doOutput ? "" : undefined); if (outputPath !== undefined && transformed !== undefined) { //If outputPath is given in the expander we want to: // (1) output to the document // (2) return undefined, to ensure that expanders higher up in the hierarchy doesn't attempt to output it again fluid.model.transform.setValue(transformSpec.outputPath, transformed, transform); transformed = undefined; } } return transformed; }; // unsupported, NON-API function fluid.model.transform.expandWildcards = function (transform, source) { fluid.each(source, function (value, key) { var q = transform.queuedTransforms; transform.pathOp.push(fluid.pathUtil.escapeSegment(key.toString())); for (var i = 0; i < q.length; ++i) { if (fluid.pathUtil.matchPath(q[i].matchPath, transform.path, true)) { var esCopy = fluid.copy(q[i].transformSpec); if (esCopy.inputPath === undefined || fluid.model.transform.hasWildcard(esCopy.inputPath)) { esCopy.inputPath = ""; } // TODO: allow some kind of interpolation for output path // TODO: Also, we now require outputPath to be specified in these cases for output to be produced as well.. Is that something we want to continue with? transform.inputPrefixOp.push(transform.path); transform.outputPrefixOp.push(transform.path); var transformOpts = fluid.model.transform.lookupType(esCopy.type); var result = fluid.model.transform.doTransform(esCopy, transform, transformOpts); if (result !== undefined) { fluid.model.transform.setValue(null, result, transform); } transform.outputPrefixOp.pop(); transform.inputPrefixOp.pop(); } } if (!fluid.isPrimitive(value)) { fluid.model.transform.expandWildcards(transform, value); } transform.pathOp.pop(); }); }; // unsupported, NON-API function fluid.model.transform.hasWildcard = function (path) { return typeof(path) === "string" && path.indexOf("*") !== -1; }; // unsupported, NON-API function fluid.model.transform.maybePushWildcard = function (transformSpec, transform) { var hw = fluid.model.transform.hasWildcard; var matchPath; if (hw(transformSpec.inputPath)) { matchPath = fluid.model.composePaths(transform.inputPrefix, transformSpec.inputPath); } else if (hw(transform.outputPrefix) || hw(transformSpec.outputPath)) { matchPath = fluid.model.composePaths(transform.outputPrefix, transformSpec.outputPath); } if (matchPath) { transform.queuedTransforms.push({transformSpec: transformSpec, outputPrefix: transform.outputPrefix, inputPrefix: transform.inputPrefix, matchPath: matchPath}); return true; } return false; }; fluid.model.sortByKeyLength = function (inObject) { var keys = fluid.keys(inObject); return keys.sort(fluid.compareStringLength(true)); }; // Three handler functions operating the (currently) three different processing modes // unsupported, NON-API function fluid.model.transform.handleTransformStrategy = function (transformSpec, transform, transformOpts) { if (fluid.model.transform.maybePushWildcard(transformSpec, transform)) { return; } else { return fluid.model.transform.doTransform(transformSpec, transform, transformOpts); } }; // unsupported, NON-API function fluid.model.transform.handleInvertStrategy = function (transformSpec, transform, transformOpts) { var invertor = transformOpts.defaults && transformOpts.defaults.invertConfiguration; if (invertor) { var inverted = fluid.invokeGlobalFunction(invertor, [transformSpec, transform]); transform.inverted.push(inverted); } }; // unsupported, NON-API function fluid.model.transform.handleCollectStrategy = function (transformSpec, transform, transformOpts) { var defaults = transformOpts.defaults; var standardInput = fluid.hasGrade(defaults, "fluid.standardInputTransformFunction"); var multiInput = fluid.hasGrade(defaults, "fluid.multiInputTransformFunction"); if (standardInput) { fluid.model.transform.accumulateStandardInputPath("input", transformSpec, transform, transform.inputPaths); } else if (multiInput) { fluid.model.transform.accumulateMultiInputPaths(defaults.inputVariables, transformSpec, transform, transform.inputPaths); } else { var collector = defaults.collectInputPaths; if (collector) { var collected = fluid.makeArray(fluid.invokeGlobalFunction(collector, [transformSpec, transform])); transform.inputPaths = transform.inputPaths.concat(collected); } } }; fluid.model.transform.lookupType = function (typeName, transformSpec) { if (!typeName) { fluid.fail("Transformation record is missing a type name: ", transformSpec); } if (typeName.indexOf(".") === -1) { typeName = "fluid.transforms." + typeName; } var defaults = fluid.defaults(typeName); return { defaults: defaults, typeName: typeName}; }; // A utility which is helpful in computing inverses involving compound values. // For example, with the valueMapper, compound input values are accepted as literals implicitly, // whereas as output values they must be escaped. This utility escapes a value if it is not primitive. fluid.model.transform.literaliseValue = function (value) { return fluid.isPrimitive(value) ? value : { literalValue: value }; }; // unsupported, NON-API function fluid.model.transform.processRule = function (rule, transform) { if (typeof(rule) === "string") { rule = fluid.model.transform.pathToRule(rule); } // special dispensation to allow "literalValue" to escape any value else if (rule.literalValue !== undefined) { rule = fluid.model.transform.literalValueToRule(rule.literalValue); } var togo; if (rule.transform) { var transformSpec, transformOpts; if (fluid.isArrayable(rule.transform)) { // if the transform holds an array, each transformer within that is responsible for its own output var transforms = rule.transform; togo = undefined; for (var i = 0; i < transforms.length; ++i) { transformSpec = transforms[i]; transformOpts = fluid.model.transform.lookupType(transformSpec.type); transform.transformHandler(transformSpec, transform, transformOpts); } } else { // else we just have a normal single transform which will return 'undefined' as a flag to defeat cascading output transformSpec = rule.transform; transformOpts = fluid.model.transform.lookupType(transformSpec.type); togo = transform.transformHandler(transformSpec, transform, transformOpts); } } // if rule is an array, save path for later use in schema strategy on final applier (so output will be interpreted as array) if (fluid.isArrayable(rule)) { transform.collectedFlatSchemaOpts = transform.collectedFlatSchemaOpts || {}; transform.collectedFlatSchemaOpts[transform.outputPrefix] = "array"; } fluid.each(rule, function (value, key) { if (key !== "transform") { transform.outputPrefixOp.push(key); var togo = transform.expand(value, transform); // Value expanders and arrays as rules implicitly outputs, unless they have nothing (undefined) to output if (togo !== undefined) { fluid.model.transform.setValue(null, togo, transform); // ensure that expanders further up does not try to output this value as well. togo = undefined; } transform.outputPrefixOp.pop(); } }); return togo; }; // unsupported, NON-API function // 3rd arg is disused by the framework and always defaults to fluid.model.transform.processRule fluid.model.transform.makeStrategy = function (transform, handleFn, transformFn) { transformFn = transformFn || fluid.model.transform.processRule; transform.expand = function (rules) { return transformFn(rules, transform); }; transform.outputPrefixOp = fluid.model.makePathStack(transform, "outputPrefix"); transform.inputPrefixOp = fluid.model.makePathStack(transform, "inputPrefix"); transform.transformHandler = handleFn; }; fluid.model.transform.invertConfiguration = function (rules) { var transform = { inverted: [] }; fluid.model.transform.makeStrategy(transform, fluid.model.transform.handleInvertStrategy); transform.expand(rules); return { transform: transform.inverted }; }; fluid.model.transform.collectInputPaths = function (rules) { var transform = { inputPaths: [] }; fluid.model.transform.makeStrategy(transform, fluid.model.transform.handleCollectStrategy); transform.expand(rules); return transform.inputPaths; }; // unsupported, NON-API function fluid.model.transform.flatSchemaStrategy = function (flatSchema, getConfig) { var keys = fluid.model.sortByKeyLength(flatSchema); return function (root, segment, index, segs) { var path = getConfig.parser.compose.apply(null, segs.slice(0, index)); // TODO: clearly this implementation could be much more efficient for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (fluid.pathUtil.matchPath(key, path, true) !== null) { return flatSchema[key]; } } }; }; // unsupported, NON-API function fluid.model.transform.defaultSchemaValue = function (schemaValue) { var type = fluid.isPrimitive(schemaValue) ? schemaValue : schemaValue.type; return type === "array" ? [] : {}; }; // unsupported, NON-API function fluid.model.transform.isomorphicSchemaStrategy = function (source, getConfig) { return function (root, segment, index, segs) { var existing = fluid.get(source, segs.slice(0, index), getConfig); return fluid.isArrayable(existing) ? "array" : "object"; }; }; // unsupported, NON-API function fluid.model.transform.decodeStrategy = function (source, options, getConfig) { if (options.isomorphic) { return fluid.model.transform.isomorphicSchemaStrategy(source, getConfig); } else if (options.flatSchema) { return fluid.model.transform.flatSchemaStrategy(options.flatSchema, getConfig); } }; // unsupported, NON-API function fluid.model.transform.schemaToCreatorStrategy = function (strategy) { return function (root, segment, index, segs) { if (root[segment] === undefined) { var schemaValue = strategy(root, segment, index, segs); root[segment] = fluid.model.transform.defaultSchemaValue(schemaValue); return root[segment]; } }; }; /** Transforms a model by a sequence of rules. Parameters as for fluid.model.transform, * only with an array accepted for "rules" */ fluid.model.transform.sequence = function (source, rules, options) { for (var i = 0; i < rules.length; ++i) { source = fluid.model.transform(source, rules[i], options); } return source; }; fluid.model.compareByPathLength = function (changea, changeb) { var pdiff = changea.path.length - changeb.path.length; return pdiff === 0 ? changea.sequence - changeb.sequence : pdiff; }; /** Fires an accumulated set of change requests in increasing order of target pathlength */ fluid.model.fireSortedChanges = function (changes, applier) { changes.sort(fluid.model.compareByPathLength); fluid.requestChanges(applier, changes); }; /** * Transforms a model based on a specified expansion rules objects. * Rules objects take the form of: * { * "target.path": "value.el.path" || { * transform: { * type: "transform.function.path", * ... * } * } * } * * @param {Object} source the model to transform * @param {Object} rules a rules object containing instructions on how to transform the model * @param {Object} options a set of rules governing the transformations. At present this may contain * the values <code>isomorphic: true</code> indicating that the output model is to be governed by the * same schema found in the input model, or <code>flatSchema</code> holding a flat schema object which * consists of a hash of EL path specifications with wildcards, to the values "array"/"object" defining * the schema to be used to construct missing trunk values. */ fluid.model.transformWithRules = function (source, rules, options) { options = options || {}; var getConfig = fluid.model.escapedGetConfig; var schemaStrategy = fluid.model.transform.decodeStrategy(source, options, getConfig); var transform = { source: source, target: { model: schemaStrategy ? fluid.model.transform.defaultSchemaValue(schemaStrategy(null, "", 0, [""])) : {} }, resolverGetConfig: getConfig, collectedFlatSchemaOpts: undefined, // to hold options for flat schema collected during transforms queuedChanges: [], queuedTransforms: [] // TODO: This is used only by wildcard applier - explain its operation }; fluid.model.transform.makeStrategy(transform, fluid.model.transform.handleTransformStrategy); transform.applier = { fireChangeRequest: function (changeRequest) { changeRequest.sequence = transform.queuedChanges.length; transform.queuedChanges.push(changeRequest); } }; fluid.bindRequestChange(transform.applier); transform.expand(rules); var setConfig = fluid.copy(fluid.model.escapedSetConfig); // Modify schemaStrategy if we collected flat schema options for the setConfig of finalApplier if (transform.collectedFlatSchemaOpts !== undefined) { $.extend(transform.collectedFlatSchemaOpts, options.flatSchema); schemaStrategy = fluid.model.transform.flatSchemaStrategy(transform.collectedFlatSchemaOpts, getConfig); } setConfig.strategies = [fluid.model.defaultFetchStrategy, schemaStrategy ? fluid.model.transform.schemaToCreatorStrategy(schemaStrategy) : fluid.model.defaultCreatorStrategy]; transform.finalApplier = options.finalApplier || fluid.makeNewChangeApplier(transform.target, {resolverSetConfig: setConfig}); if (transform.queuedTransforms.length > 0) { transform.typeStack = []; transform.pathOp = fluid.model.makePathStack(transform, "path"); fluid.model.transform.expandWildcards(transform, source); } fluid.model.fireSortedChanges(transform.queuedChanges, transform.finalApplier); return transform.target.model; }; $.extend(fluid.model.transformWithRules, fluid.model.transform); fluid.model.transform = fluid.model.transformWithRules; /** Utility function to produce a standard options transformation record for a single set of rules **/ fluid.transformOne = function (rules) { return { transformOptions: { transformer: "fluid.model.transformWithRules", config: rules } }; }; /** Utility function to produce a standard options transformation record for multiple rules to be applied in sequence **/ fluid.transformMany = function (rules) { return { transformOptions: { transformer: "fluid.model.transform.sequence", config: rules } }; }; })(jQuery, fluid_2_0); ;/* Copyright 2010 University of Toronto Copyright 2010-2011 OCAD University Copyright 2013 Raising the Floor - International Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ var fluid_2_0 = fluid_2_0 || {}; var fluid = fluid || fluid_2_0; (function ($, fluid) { "use strict"; fluid.registerNamespace("fluid.model.transform"); fluid.registerNamespace("fluid.transforms"); /********************************** * Standard transformer functions * **********************************/ fluid.defaults("fluid.transforms.value", { gradeNames: "fluid.standardTransformFunction", invertConfiguration: "fluid.transforms.value.invert" }); fluid.transforms.value = fluid.identity; fluid.transforms.value.invert = function (transformSpec, transformer) { var togo = fluid.copy(transformSpec); // TODO: this will not behave correctly in the face of compound "value" which contains // further transforms togo.inputPath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.outputPath); togo.outputPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.inputPath); return togo; }; // Export the use of the "value" transform under the "identity" name for FLUID-5293 fluid.transforms.identity = fluid.transforms.value; fluid.defaults("fluid.transforms.identity", { gradeNames: "fluid.transforms.value" }); fluid.defaults("fluid.transforms.literalValue", { gradeNames: "fluid.standardOutputTransformFunction" }); fluid.transforms.literalValue = function (transformSpec) { return transformSpec.value; }; fluid.defaults("fluid.transforms.arrayValue", { gradeNames: "fluid.standardTransformFunction" }); fluid.transforms.arrayValue = fluid.makeArray; fluid.defaults("fluid.transforms.count", { gradeNames: "fluid.standardTransformFunction" }); fluid.transforms.count = function (value) { return fluid.makeArray(value).length; }; fluid.defaults("fluid.transforms.round", { gradeNames: "fluid.standardTransformFunction" }); fluid.transforms.round = function (value) { return Math.round(value); }; fluid.defaults("fluid.transforms.delete", { gradeNames: "fluid.transformFunction" }); fluid.transforms["delete"] = function (transformSpec, transformer) { var outputPath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.outputPath); transformer.applier.requestChange(outputPath, null, "DELETE"); }; fluid.defaults("fluid.transforms.firstValue", { gradeNames: "fluid.transformFunction" }); fluid.transforms.firstValue = function (transformSpec, transformer) { if (!transformSpec.values || !transformSpec.values.length) { fluid.fail("firstValue transformer requires an array of values at path named \"values\", supplied", transformSpec); } for (var i = 0; i < transformSpec.values.length; i++) { var value = transformSpec.values[i]; // TODO: problem here - all of these transforms will have their side-effects (setValue) even if only one is chosen var expanded = transformer.expand(value); if (expanded !== undefined) { return expanded; } } }; fluid.defaults("fluid.transforms.linearScale", { gradeNames: [ "fluid.multiInputTransformFunction", "fluid.standardOutputTransformFunction", "fluid.lens" ], invertConfiguration: "fluid.transforms.linearScale.invert", inputVariables: { value: null, factor: 1, offset: 0 } }); /* simple linear transformation */ fluid.transforms.linearScale = function (inputs) { var value = inputs.value(); var factor = inputs.factor(); var offset = inputs.offset(); if (typeof(value) !== "number" || typeof(factor) !== "number" || typeof(offset) !== "number") { return undefined; } return value * factor + offset; }; /* TODO: This inversion doesn't work if the value and factors are given as paths in the source model */ fluid.transforms.linearScale.invert = function (transformSpec, transformer) { var togo = fluid.copy(transformSpec); if (togo.factor) { togo.factor = (togo.factor === 0) ? 0 : 1 / togo.factor; } if (togo.offset) { togo.offset = - togo.offset * (togo.factor !== undefined ? togo.factor : 1); } // TODO: This rubbish should be done by the inversion machinery by itself. We shouldn't have to repeat it in every // inversion rule togo.valuePath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.outputPath); togo.outputPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.valuePath); return togo; }; fluid.defaults("fluid.transforms.binaryOp", { gradeNames: [ "fluid.multiInputTransformFunction", "fluid.standardOutputTransformFunction" ], inputVariables: { left: null, right: null } }); fluid.transforms.binaryLookup = { "===": function (a, b) { return a === b; }, "!==": function (a, b) { return a !== b; }, "<=": function (a, b) { return a <= b; }, "<": function (a, b) { return a < b; }, ">=": function (a, b) { return a >= b; }, ">": function (a, b) { return a > b; }, "+": function (a, b) { return a + b; }, "-": function (a, b) { return a - b; }, "*": function (a, b) { return a * b; }, "/": function (a, b) { return a / b; }, "%": function (a, b) { return a % b; }, "&&": function (a, b) { return a && b; }, "||": function (a, b) { return a || b; } }; fluid.transforms.binaryOp = function (inputs, transformSpec, transformer) { var left = inputs.left(); var right = inputs.right(); var operator = fluid.model.transform.getValue(undefined, transformSpec.operator, transformer); var fun = fluid.transforms.binaryLookup[operator]; return (fun === undefined || left === undefined || right === undefined) ? undefined : fun(left, right); }; fluid.defaults("fluid.transforms.condition", { gradeNames: [ "fluid.multiInputTransformFunction", "fluid.standardOutputTransformFunction" ], inputVariables: { "true": null, "false": null, "condition": null } }); fluid.transforms.condition = function (inputs) { var condition = inputs.condition(); if (condition === null) { return undefined; } return inputs[condition ? "true" : "false"](); }; fluid.defaults("fluid.transforms.valueMapper", { gradeNames: ["fluid.transformFunction", "fluid.lens"], invertConfiguration: "fluid.transforms.valueMapper.invert", collectInputPaths: "fluid.transforms.valueMapper.collect" }); // unsupported, NON-API function fluid.model.transform.compareMatches = function (speca, specb) { return specb.matchValue - speca.matchValue; }; // unsupported, NON-API function fluid.model.transform.matchValueMapperFull = function (outerValue, transformSpec, transformer) { var o = transformSpec.options; if (o.length === 0) { fluid.fail("valueMapper supplied empty list of options: ", transformSpec); } var matchPower = []; for (var i = 0; i < o.length; ++i) { var option = o[i]; var value = fluid.firstDefined(fluid.model.transform.getValue(option.inputPath, undefined, transformer), outerValue); var matchValue = fluid.model.transform.matchValue(option.undefinedInputValue ? undefined : (option.inputValue === undefined ? transformSpec.defaultInputValue : option.inputValue), value, transformSpec.partialMatches || option.partialMatches); matchPower[i] = {index: i, matchValue: matchValue}; } matchPower.sort(fluid.model.transform.compareMatches); return (matchPower[0].matchValue <= 0 || o.length > 1 && matchPower[0].matchValue === matchPower[1].matchValue) ? -1 : matchPower[0].index; }; fluid.transforms.valueMapper = function (transformSpec, transformer) { if (!transformSpec.options) { fluid.fail("valueMapper requires a list or hash of options at path named \"options\", supplied ", transformSpec); } var value = fluid.model.transform.getValue(transformSpec.inputPath, undefined, transformer); var deref = fluid.isArrayable(transformSpec.options) ? // long form with list of records function (testVal) { var index = fluid.model.transform.matchValueMapperFull(testVal, transformSpec, transformer); return index === -1 ? null : transformSpec.options[index]; } : function (testVal) { return transformSpec.options[testVal]; }; var indexed = deref(value); if (!indexed) { // if no branch matches, try again using this value - WARNING, this seriously // threatens invertibility indexed = deref(transformSpec.defaultInputValue); } if (!indexed) { return; } var outputPath = indexed.outputPath === undefined ? transformSpec.defaultOutputPath : indexed.outputPath; transformer.outputPrefixOp.push(outputPath); var outputValue; if (fluid.isPrimitive(indexed)) { outputValue = indexed; } else { // if undefinedOutputValue is set, outputValue should be undefined if (indexed.undefinedOutputValue) { outputValue = undefined; } else { // get value from outputValue or outputValuePath. If none is found set the outputValue to be that of defaultOutputValue (or undefined) outputValue = fluid.model.transform.resolveParam(indexed, transformer, "outputValue", undefined); outputValue = (outputValue === undefined) ? transformSpec.defaultOutputValue : outputValue; } } // output if outputPath or defaultOutputPath have been specified and the relevant child hasn't done the outputting if (typeof(outputPath) === "string" && outputValue !== undefined) { fluid.model.transform.setValue(undefined, outputValue, transformer, transformSpec.merge); outputValue = undefined; } transformer.outputPrefixOp.pop(); return outputValue; }; fluid.transforms.valueMapper.invert = function (transformSpec, transformer) { var options = []; var togo = { type: "fluid.transforms.valueMapper", options: options }; var isArray = fluid.isArrayable(transformSpec.options); var findCustom = function (name) { return fluid.find(transformSpec.options, function (option) { if (option[name]) { return true; } }); }; var anyCustomOutput = findCustom("outputPath"); var anyCustomInput = findCustom("inputPath"); if (!anyCustomOutput) { togo.inputPath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.defaultOutputPath); } if (!anyCustomInput) { togo.defaultOutputPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.inputPath); } var def = fluid.firstDefined; fluid.each(transformSpec.options, function (option, key) { var outOption = {}; var origInputValue = def(isArray ? option.inputValue : key, transformSpec.defaultInputValue); if (origInputValue === undefined) { fluid.fail("Failure inverting configuration for valueMapper - inputValue could not be resolved for record " + key + ": ", transformSpec); } outOption.outputValue = fluid.model.transform.literaliseValue(origInputValue); var origOutputValue = def(option.outputValue, transformSpec.defaultOutputValue); outOption.inputValue = fluid.model.transform.getValue(option.outputValuePath, origOutputValue, transformer); if (anyCustomOutput) { outOption.inputPath = fluid.model.composePaths(transformer.outputPrefix, def(option.outputPath, transformSpec.outputPath)); } if (anyCustomInput) { outOption.outputPath = fluid.model.composePaths(transformer.inputPrefix, def(option.inputPath, transformSpec.inputPath)); } if (option.outputValuePath) { outOption.inputValuePath = option.outputValuePath; } options.push(outOption); }); return togo; }; fluid.transforms.valueMapper.collect = function (transformSpec, transformer) { var togo = []; fluid.model.transform.accumulateInputPath(transformSpec.inputPath, transformer, togo); fluid.each(transformSpec.options, function (option) { fluid.model.transform.accumulateInputPath(option.inputPath, transformer, togo); }); return togo; }; /* -------- arrayToSetMembership and setMembershipToArray ---------------- */ fluid.defaults("fluid.transforms.arrayToSetMembership", { gradeNames: ["fluid.standardInputTransformFunction", "fluid.lens"], invertConfiguration: "fluid.transforms.arrayToSetMembership.invert" }); fluid.transforms.arrayToSetMembership = function (value, transformSpec, transformer) { var options = transformSpec.options; if (!value || !fluid.isArrayable(value)) { fluid.fail("arrayToSetMembership didn't find array at inputPath nor passed as value.", transformSpec); } if (!options) { fluid.fail("arrayToSetMembership requires an options block set"); } if (transformSpec.presentValue === undefined) { transformSpec.presentValue = true; } if (transformSpec.missingValue === undefined) { transformSpec.missingValue = false; } fluid.each(options, function (outPath, key) { // write to output path given in options the value <presentValue> or <missingValue> depending on whether key is found in user input var outVal = ($.inArray(key, value) !== -1) ? transformSpec.presentValue : transformSpec.missingValue; fluid.model.transform.setValue(outPath, outVal, transformer); }); // TODO: Why does this transform make no return? }; fluid.transforms.arrayToSetMembership.invert = function (transformSpec, transformer) { var togo = fluid.copy(transformSpec); delete togo.inputPath; togo.type = "fluid.transforms.setMembershipToArray"; togo.outputPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.inputPath); var newOptions = {}; fluid.each(transformSpec.options, function (path, oldKey) { var newKey = fluid.model.composePaths(transformer.outputPrefix, path); newOptions[newKey] = oldKey; }); togo.options = newOptions; return togo; }; fluid.defaults("fluid.transforms.setMembershipToArray", { gradeNames: ["fluid.standardOutputTransformFunction"] }); fluid.transforms.setMembershipToArray = function (transformSpec, transformer) { var options = transformSpec.options; if (!options) { fluid.fail("setMembershipToArray requires an options block specified"); } if (transformSpec.presentValue === undefined) { transformSpec.presentValue = true; } if (transformSpec.missingValue === undefined) { transformSpec.missingValue = false; } var outputArr = []; fluid.each(options, function (arrVal, inPath) { var val = fluid.model.transform.getValue(inPath, undefined, transformer); if (val === transformSpec.presentValue) { outputArr.push(arrVal); } }); return outputArr; }; /* -------- objectToArray and arrayToObject -------------------- */ /** * Transforms the given array to an object. * Uses the transformSpec.options.key values from each object within the array as new keys. * * For example, with transformSpec.key = "name" and an input object like this: * * { * b: [ * { name: b1, v: v1 }, * { name: b2, v: v2 } * ] * } * * The output will be: * { * b: { * b1: { * v: v1 * } * }, * { * b2: { * v: v2 * } * } * } */ fluid.model.transform.applyPaths = function (operation, pathOp, paths) { for (var i = 0; i < paths.length; ++i) { if (operation === "push") { pathOp.push(paths[i]); } else { pathOp.pop(); } } }; fluid.model.transform.expandInnerValues = function (inputPath, outputPath, transformer, innerValues) { var inputPrefixOp = transformer.inputPrefixOp; var outputPrefixOp = transformer.outputPrefixOp; var apply = fluid.model.transform.applyPaths; apply("push", inputPrefixOp, inputPath); apply("push", outputPrefixOp, outputPath); var expanded = {}; fluid.each(innerValues, function (innerValue) { var expandedInner = transformer.expand(innerValue); if (!fluid.isPrimitive(expandedInner)) { $.extend(true, expanded, expandedInner); } else { expanded = expandedInner; } }); apply("pop", outputPrefixOp, outputPath); apply("pop", inputPrefixOp, inputPath); return expanded; }; fluid.defaults("fluid.transforms.arrayToObject", { gradeNames: ["fluid.standardTransformFunction", "fluid.lens" ], invertConfiguration: "fluid.transforms.arrayToObject.invert" }); fluid.transforms.arrayToObject = function (arr, transformSpec, transformer) { if (transformSpec.key === undefined) { fluid.fail("arrayToObject requires a 'key' option.", transformSpec); } if (!fluid.isArrayable(arr)) { fluid.fail("arrayToObject didn't find array at inputPath.", transformSpec); } var newHash = {}; var pivot = transformSpec.key; fluid.each(arr, function (v, k) { // check that we have a pivot entry in the object and it's a valid type: var newKey = v[pivot]; var keyType = typeof(newKey); if (keyType !== "string" && keyType !== "boolean" && keyType !== "number") { fluid.fail("arrayToObject encountered untransformable array due to missing or invalid key", v); } // use the value of the key element as key and use the remaining content as value var content = fluid.copy(v); delete content[pivot]; // fix sub Arrays if needed: if (transformSpec.innerValue) { content = fluid.model.transform.expandInnerValues([transformer.inputPrefix, transformSpec.inputPath, k.toString()], [newKey], transformer, transformSpec.innerValue); } newHash[newKey] = content; }); return newHash; }; fluid.transforms.arrayToObject.invert = function (transformSpec, transformer) { var togo = fluid.copy(transformSpec); togo.type = "fluid.transforms.objectToArray"; togo.inputPath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.outputPath); togo.outputPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.inputPath); // invert transforms from innerValue as well: // TODO: The Model Transformations framework should be capable of this, but right now the // issue is that we use a "private contract" to operate the "innerValue" slot. We need to // spend time thinking of how this should be formalised if (togo.innerValue) { var innerValue = togo.innerValue; for (var i = 0; i < innerValue.length; ++i) { innerValue[i] = fluid.model.transform.invertConfiguration(innerValue[i]); } } return togo; }; fluid.defaults("fluid.transforms.objectToArray", { gradeNames: "fluid.standardTransformFunction" }); /** * Transforms an object into array of objects. * This performs the inverse transform of fluid.transforms.arrayToObject. */ fluid.transforms.objectToArray = function (hash, transformSpec, transformer) { if (transformSpec.key === undefined) { fluid.fail("objectToArray requires a 'key' option.", transformSpec); } var newArray = []; var pivot = transformSpec.key; fluid.each(hash, function (v, k) { var content = {}; content[pivot] = k; if (transformSpec.innerValue) { v = fluid.model.transform.expandInnerValues([transformSpec.inputPath, k], [transformSpec.outputPath, newArray.length.toString()], transformer, transformSpec.innerValue); } $.extend(true, content, v); newArray.push(content); }); return newArray; }; fluid.defaults("fluid.transforms.limitRange", { gradeNames: "fluid.standardTransformFunction" }); fluid.transforms.limitRange = function (value, transformSpec) { var min = transformSpec.min; if (min !== undefined) { var excludeMin = transformSpec.excludeMin || 0; min += excludeMin; if (value < min) { value = min; } } var max = transformSpec.max; if (max !== undefined) { var excludeMax = transformSpec.excludeMax || 0; max -= excludeMax; if (value > max) { value = max; } } return value; }; fluid.defaults("fluid.transforms.free", { gradeNames: "fluid.transformFunction" }); fluid.transforms.free = function (transformSpec) { var args = fluid.makeArray(transformSpec.args); return fluid.invokeGlobalFunction(transformSpec.func, args); }; })(jQuery, fluid_2_0); ;// -*- mode: javascript; tab-width: 2; indent-tabs-mode: nil; -*- //------------------------------------------------------------------------------ // Web Array Math API - JavaScript polyfill // // Copyright(c) 2013 Marcus Geelnard // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the // use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not claim // that you wrote the original software. If you use this software in a // product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. //------------------------------------------------------------------------------ "use strict"; //------------------------------------------------------------------------------ // interface ArrayMath //------------------------------------------------------------------------------ (function () { var context = typeof (window) !== "undefined" ? window : typeof (self) !== "undefined" ? self : typeof module !== "undefined" && module.exports ? module.exports : global; if (context.ArrayMath) return; var ArrayMath = {}; ArrayMath.add = function (dst, x, y) { var k; if (x instanceof Float32Array) for (k = Math.min(dst.length, x.length, y.length) - 1; k >= 0; --k) dst[k] = x[k] + y[k]; else for (k = Math.min(dst.length, y.length) - 1; k >= 0; --k) dst[k] = x + y[k]; }; ArrayMath.sub = function (dst, x, y) { var k; if (x instanceof Float32Array) for (k = Math.min(dst.length, x.length, y.length) - 1; k >= 0; --k) dst[k] = x[k] - y[k]; else for (k = Math.min(dst.length, y.length) - 1; k >= 0; --k) dst[k] = x - y[k]; }; ArrayMath.mul = function (dst, x, y) { var k; if (x instanceof Float32Array) for (k = Math.min(dst.length, x.length, y.length) - 1; k >= 0; --k) dst[k] = x[k] * y[k]; else for (k = Math.min(dst.length, y.length) - 1; k >= 0; --k) dst[k] = x * y[k]; }; ArrayMath.mulCplx = function (dstReal, dstImag, xReal, xImag, yReal, yImag) { var k, xr, xi, yr, yi; if (xReal instanceof Float32Array) for (k = Math.min(dstReal.length, dstImag.length, xReal.length, xImag.length, yReal.length, yImag.length) - 1; k >= 0; --k) { xr = xReal[k], xi = xImag[k], yr = yReal[k], yi = yImag[k]; dstReal[k] = xr * yr - xi * yi; dstImag[k] = xr * yi + xi * yr; } else for (k = Math.min(dstReal.length, dstImag.length, yReal.length, yImag.length) - 1; k >= 0; --k) { yr = yReal[k], yi = yImag[k]; dstReal[k] = xReal * yr - xImag * yi; dstImag[k] = xReal * yi + xImag * yr; } }; ArrayMath.div = function (dst, x, y) { var k; if (x instanceof Float32Array) for (k = Math.min(dst.length, x.length, y.length) - 1; k >= 0; --k) dst[k] = x[k] / y[k]; else for (k = Math.min(dst.length, y.length) - 1; k >= 0; --k) dst[k] = x / y[k]; }; ArrayMath.divCplx = function (dstReal, dstImag, xReal, xImag, yReal, yImag) { var k, xr, xi, yr, yi, denom; if (xReal instanceof Float32Array) for (k = Math.min(dstReal.length, dstImag.length, xReal.length, xImag.length, yReal.length, yImag.length) - 1; k >= 0; --k) { xr = xReal[k], xi = xImag[k], yr = yReal[k], yi = yImag[k]; denom = 1 / (yr * yr + yi * yi); dstReal[k] = (xr * yr + xi * yi) * denom; dstImag[k] = (xi * yr - xr * yi) * denom; } else { for (k = Math.min(dstReal.length, dstImag.length, yReal.length, yImag.length) - 1; k >= 0; --k) { yr = yReal[k], yi = yImag[k]; denom = 1 / (yr * yr + yi * yi); dstReal[k] = (xReal * yr + xImag * yi) * denom; dstImag[k] = (xImag * yr - xReal * yi) * denom; } } }; ArrayMath.madd = function (dst, x, y, z) { var k; if (x instanceof Float32Array) for (k = Math.min(dst.length, x.length, y.length, z.length) - 1; k >= 0; --k) dst[k] = x[k] * y[k] + z[k]; else for (k = Math.min(dst.length, y.length, z.length) - 1; k >= 0; --k) dst[k] = x * y[k] + z[k]; }; ArrayMath.abs = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.abs(x[k]); }; ArrayMath.absCplx = function (dst, real, imag) { for (var k = Math.min(dst.length, real.length, imag.length) - 1; k >= 0; --k) dst[k] = Math.sqrt(real[k] * real[k] + imag[k] * imag[k]); }; ArrayMath.acos = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.acos(x[k]); }; ArrayMath.asin = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.asin(x[k]); }; ArrayMath.atan = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.atan(x[k]); }; ArrayMath.atan2 = function (dst, y, x) { for (var k = Math.min(dst.length, x.length, y.length) - 1; k >= 0; --k) dst[k] = Math.atan2(y[k], x[k]); }; ArrayMath.ceil = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.ceil(x[k]); }; ArrayMath.cos = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.cos(x[k]); }; ArrayMath.exp = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.exp(x[k]); }; ArrayMath.floor = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.floor(x[k]); }; ArrayMath.log = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.log(x[k]); }; ArrayMath.max = function (x) { var ret = -Infinity; for (var k = x.length - 1; k >= 0; --k) { var val = x[k]; if (val > ret) ret = val; } return ret; }; ArrayMath.min = function (x) { var ret = Infinity; for (var k = x.length - 1; k >= 0; --k) { var val = x[k]; if (val < ret) ret = val; } return ret; }; ArrayMath.pow = function (dst, x, y) { var k; if (y instanceof Float32Array) for (k = Math.min(dst.length, x.length, y.length) - 1; k >= 0; --k) dst[k] = Math.pow(x[k], y[k]); else { for (k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.pow(x[k], y); } }; ArrayMath.random = function (dst, low, high) { if (!low) low = 0; if (isNaN(parseFloat(high))) high = 1; var scale = high - low; for (var k = dst.length - 1; k >= 0; --k) dst[k] = Math.random() * scale + low; }; ArrayMath.round = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.round(x[k]); }; ArrayMath.sin = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.sin(x[k]); }; ArrayMath.sqrt = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.sqrt(x[k]); }; ArrayMath.tan = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = Math.tan(x[k]); }; ArrayMath.clamp = function (dst, x, xMin, xMax) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) { var val = x[k]; dst[k] = val < xMin ? xMin : val > xMax ? xMax : val; } }; ArrayMath.fract = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) { var val = x[k]; dst[k] = val - Math.floor(val); } }; ArrayMath.fill = function (dst, value) { for (var k = dst.length - 1; k >= 0; --k) { dst[k] = value; } }; ArrayMath.ramp = function (dst, first, last) { var maxIdx = dst.length - 1; if (maxIdx >= 0) dst[0] = first; if (maxIdx > 0) { var step = (last - first) / maxIdx; for (var k = 1; k <= maxIdx; ++k) dst[k] = first + step * k; } }; ArrayMath.sign = function (dst, x) { for (var k = Math.min(dst.length, x.length) - 1; k >= 0; --k) dst[k] = x[k] < 0 ? -1 : 1; }; ArrayMath.sum = function (x) { // TODO(m): We should use pairwise summation or similar here. var ret = 0; for (var k = x.length - 1; k >= 0; --k) ret += x[k]; return ret; }; ArrayMath.sampleLinear = function (dst, x, t) { var xLen = x.length, maxIdx = xLen - 1; for (var k = Math.min(dst.length, t.length) - 1; k >= 0; --k) { var t2 = t[k]; t2 = t2 < 0 ? 0 : t2 > maxIdx ? maxIdx : t2; var idx = Math.floor(t2); var w = t2 - idx; var p1 = x[idx]; var p2 = x[idx < maxIdx ? idx + 1 : maxIdx]; dst[k] = p1 + w * (p2 - p1); } }; ArrayMath.sampleLinearRepeat = function (dst, x, t) { var xLen = x.length, maxIdx = xLen - 1; for (var k = Math.min(dst.length, t.length) - 1; k >= 0; --k) { var t2 = t[k]; t2 = t2 - Math.floor(t2/xLen) * xLen; var idx = Math.floor(t2); var w = t2 - idx; var p1 = x[idx]; var p2 = x[idx < maxIdx ? idx + 1 : 0]; dst[k] = p1 + w * (p2 - p1); } }; ArrayMath.sampleCubic = function (dst, x, t) { var xLen = x.length, maxIdx = xLen - 1; for (var k = Math.min(dst.length, t.length) - 1; k >= 0; --k) { var t2 = t[k]; t2 = t2 < 0 ? 0 : t2 > maxIdx ? maxIdx : t2; var idx = Math.floor(t2); var w = t2 - idx; var w2 = w * w; var w3 = w2 * w; var h2 = -2*w3 + 3*w2; var h1 = 1 - h2; var h4 = w3 - w2; var h3 = h4 - w2 + w; var p1 = x[idx > 0 ? idx - 1 : 0]; var p2 = x[idx]; var p3 = x[idx < maxIdx ? idx + 1 : maxIdx]; var p4 = x[idx < maxIdx - 1 ? idx + 2 : maxIdx]; dst[k] = h1 * p2 + h2 * p3 + 0.5 * (h3 * (p3 - p1) + h4 * (p4 - p2)); } }; ArrayMath.sampleCubicRepeat = function (dst, x, t) { var xLen = x.length, maxIdx = xLen - 1; for (var k = Math.min(dst.length, t.length) - 1; k >= 0; --k) { var t2 = t[k]; t2 = t2 - Math.floor(t2/xLen) * xLen; var idx = Math.floor(t2); var w = t2 - idx; var w2 = w * w; var w3 = w2 * w; var h2 = -2*w3 + 3*w2; var h1 = 1 - h2; var h4 = w3 - w2; var h3 = h4 - w2 + w; var p1 = x[idx > 0 ? idx - 1 : maxIdx]; var p2 = x[idx]; var p3 = x[idx < maxIdx ? idx + 1 : 0]; var p4 = x[idx < maxIdx - 1 ? idx + 2 : (idx + 2 - Math.floor((idx + 2)/xLen) * xLen)]; dst[k] = h1 * p2 + h2 * p3 + 0.5 * (h3 * (p3 - p1) + h4 * (p4 - p2)); } }; ArrayMath.pack = function (dst, offset, stride, src1, src2, src3, src4) { var dstCount = Math.floor(Math.max(0, (dst.length - offset)) / stride); var count = Math.min(dstCount, src1.length); if (src2) { var count = Math.min(count, src2.length); if (src3) { var count = Math.min(count, src3.length); if (src4) { var count = Math.min(count, src4.length); for (var k = 0; k < count; ++k) { dst[offset] = src1[k]; dst[offset + 1] = src2[k]; dst[offset + 2] = src3[k]; dst[offset + 3] = src4[k]; offset += stride; } } else for (var k = 0; k < count; ++k) { dst[offset] = src1[k]; dst[offset + 1] = src2[k]; dst[offset + 2] = src3[k]; offset += stride; } } else for (var k = 0; k < count; ++k) { dst[offset] = src1[k]; dst[offset + 1] = src2[k]; offset += stride; } } else for (var k = 0; k < count; ++k) { dst[offset] = src1[k]; offset += stride; } }; ArrayMath.unpack = function (src, offset, stride, dst1, dst2, dst3, dst4) { var srcCount = Math.floor(Math.max(0, (src.length - offset)) / stride); var count = Math.min(srcCount, dst1.length); if (dst2) { var count = Math.min(count, dst2.length); if (dst3) { var count = Math.min(count, dst3.length); if (dst4) { var count = Math.min(count, dst4.length); for (var k = 0; k < count; ++k) { dst1[k] = src[offset]; dst2[k] = src[offset + 1]; dst3[k] = src[offset + 2]; dst4[k] = src[offset + 3]; offset += stride; } } else for (var k = 0; k < count; ++k) { dst1[k] = src[offset]; dst2[k] = src[offset + 1]; dst3[k] = src[offset + 2]; offset += stride; } } else for (var k = 0; k < count; ++k) { dst1[k] = src[offset]; dst2[k] = src[offset + 1]; offset += stride; } } else for (var k = 0; k < count; ++k) { dst1[k] = src[offset]; offset += stride; } }; context.ArrayMath = ArrayMath; })(); //------------------------------------------------------------------------------ // interface Filter //------------------------------------------------------------------------------ (function () { var context = typeof (window) !== "undefined" ? window : typeof (self) !== "undefined" ? self : typeof module !== "undefined" && module.exports ? module.exports : global; if (context.Filter) return; var Filter = function (bSize, aSize) { if (isNaN(parseFloat(bSize)) || !isFinite(bSize)) bSize = 1; if (!aSize) aSize = 0; this._b = new Float32Array(bSize); this._b[0] = 1; this._a = new Float32Array(aSize); this._bHist = new Float32Array(bSize); this._aHist = new Float32Array(aSize); }; Filter.prototype.filter = function (dst, x) { // Put commonly accessed objects and properties in local variables var a = this._a, aLen = a.length, b = this._b, bLen = b.length, aHist = this._aHist, bHist = this._bHist, xLen = x.length, dstLen = dst.length; // Perform run-in part using the history (slow) var bHistRunIn = bLen - 1; var aHistRunIn = aLen; var k; for (k = 0; (bHistRunIn || aHistRunIn) && k < xLen; ++k) { var m, noHistLen; // FIR part noHistLen = bLen - bHistRunIn; bHistRunIn && bHistRunIn--; var res = b[0] * x[k]; for (m = 1; m < noHistLen; ++m) res += b[m] * x[k - m]; for (; m < bLen; ++m) res += b[m] * bHist[m - noHistLen]; // Recursive part noHistLen = aLen - aHistRunIn; aHistRunIn && aHistRunIn--; for (m = 0; m < noHistLen; ++m) res -= a[m] * dst[k - 1 - m]; for (; m < aLen; ++m) res -= a[m] * aHist[m - noHistLen]; dst[k] = res; } // Perform history-free part (fast) if (bLen == 3 && aLen == 2) { // Optimized special case: biquad filter var b0 = b[0], b1 = b[1], b2 = b[2], a1 = a[0], a2 = a[1]; var x0 = x[k-1], x1 = x[k-2], x2; var y0 = dst[k-1], y1 = dst[k-2], y2; for (; k < xLen; ++k) { x2 = x1; x1 = x0; x0 = x[k]; y2 = y1; y1 = y0; y0 = b0 * x0 + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; dst[k] = y0; } } else { // Generic case for (; k < xLen; ++k) { var m; // FIR part var res = b[0] * x[k]; for (m = 1; m < bLen; ++m) res += b[m] * x[k - m]; // Recursive part for (m = 0; m < aLen; ++m) res -= a[m] * dst[k - 1 - m]; dst[k] = res; } } // Update history state var histCopy = Math.min(bLen - 1, xLen); for (k = bLen - 2; k >= histCopy; --k) bHist[k] = bHist[k - histCopy]; for (k = 0; k < histCopy; ++k) bHist[k] = x[xLen - 1 - k]; histCopy = Math.min(aLen, dstLen); for (k = aLen - 1; k >= histCopy; --k) aHist[k] = aHist[k - histCopy]; for (k = 0; k < histCopy; ++k) aHist[k] = dst[xLen - 1 - k]; }; Filter.prototype.clearHistory = function () { for (var k = this._bHist.length - 1; k >= 0; --k) this._bHist[k] = 0; for (var k = this._aHist.length - 1; k >= 0; --k) this._aHist[k] = 0; }; Filter.prototype.setB = function (values) { var len = Math.min(this._b.length, values.length); for (var k = 0; k < len; ++k) this._b[k] = values[k]; }; Filter.prototype.setA = function (values) { var len = Math.min(this._a.length, values.length); for (var k = 0; k < len; ++k) this._a[k] = values[k]; }; context.Filter = Filter; })(); //------------------------------------------------------------------------------ // interface FFT // // NOTE: This is essentially a hand-translation of the C language Kiss FFT // library, copyright by Mark Borgerding, relicensed with permission from the // author. // // The algorithm implements mixed radix FFT and supports transforms of any size // (not just powers of 2). For optimal performance, use sizes that can be // factorized into factors 2, 3, 4 and 5. //------------------------------------------------------------------------------ (function () { var context = typeof (window) !== "undefined" ? window : typeof (self) !== "undefined" ? self : typeof module !== "undefined" && module.exports ? module.exports : global; if (context.FFT) return; var butterfly2 = function (outRe, outIm, outIdx, stride, twRe, twIm, m) { var scratch0Re, scratch0Im, out0Re, out0Im, out1Re, out1Im, tRe, tIm; var tw1 = 0, idx0 = outIdx, idx1 = outIdx + m; var scale = 0.7071067811865475; // sqrt(1/2) var idx0End = idx0 + m; while (idx0 < idx0End) { // out0 = out[idx0] / sqrt(2) out0Re = outRe[idx0] * scale; out0Im = outIm[idx0] * scale; // out1 = out[idx1] / sqrt(2) out1Re = outRe[idx1] * scale; out1Im = outIm[idx1] * scale; // scratch0 = out1 * tw[tw1] tRe = twRe[tw1]; tIm = twIm[tw1]; scratch0Re = out1Re * tRe - out1Im * tIm; scratch0Im = out1Re * tIm + out1Im * tRe; // out[idx1] = out0 - scratch0 outRe[idx1] = out0Re - scratch0Re; outIm[idx1] = out0Im - scratch0Im; // out[idx0] = out0 + scratch0 outRe[idx0] = out0Re + scratch0Re; outIm[idx0] = out0Im + scratch0Im; tw1 += stride; ++idx0; ++idx1; } }; var butterfly3 = function (outRe, outIm, outIdx, stride, twRe, twIm, m) { var scratch0Re, scratch0Im, scratch1Re, scratch1Im, scratch2Re, scratch2Im, scratch3Re, scratch3Im, out0Re, out0Im, out1Re, out1Im, out2Re, out2Im, tRe, tIm; var tw1 = 0, tw2 = 0, stride2 = 2 * stride, idx0 = outIdx, idx1 = outIdx + m, idx2 = outIdx + 2 * m; var epi3Im = twIm[stride*m]; var scale = 0.5773502691896258; // sqrt(1/3) var idx0End = idx0 + m; while (idx0 < idx0End) { // out0 = out[idx0] / sqrt(3) out0Re = outRe[idx0] * scale; out0Im = outIm[idx0] * scale; // out1 = out[idx1] / sqrt(3) out1Re = outRe[idx1] * scale; out1Im = outIm[idx1] * scale; // out2 = out[idx2] / sqrt(3) out2Re = outRe[idx2] * scale; out2Im = outIm[idx2] * scale; // scratch1 = out1 * tw[tw1] tRe = twRe[tw1]; tIm = twIm[tw1]; scratch1Re = out1Re * tRe - out1Im * tIm; scratch1Im = out1Re * tIm + out1Im * tRe; // scratch2 = out2 * tw[tw2] tRe = twRe[tw2]; tIm = twIm[tw2]; scratch2Re = out2Re * tRe - out2Im * tIm; scratch2Im = out2Re * tIm + out2Im * tRe; // scratch3 = scratch1 + scratch2 scratch3Re = scratch1Re + scratch2Re; scratch3Im = scratch1Im + scratch2Im; // scratch0 = scratch1 - scratch2 scratch0Re = scratch1Re - scratch2Re; scratch0Im = scratch1Im - scratch2Im; // out1 = out0 - scratch3 / 2 out1Re = out0Re - scratch3Re * 0.5; out1Im = out0Im - scratch3Im * 0.5; // scratch0 *= epi3.i scratch0Re *= epi3Im; scratch0Im *= epi3Im; // out[idx0] = out0 + scratch3 outRe[idx0] = out0Re + scratch3Re; outIm[idx0] = out0Im + scratch3Im; outRe[idx2] = out1Re + scratch0Im; outIm[idx2] = out1Im - scratch0Re; outRe[idx1] = out1Re - scratch0Im; outIm[idx1] = out1Im + scratch0Re; tw1 += stride; tw2 += stride2; ++idx0; ++idx1; ++idx2; } }; var butterfly4 = function (outRe, outIm, outIdx, stride, twRe, twIm, m, inverse) { var scratch0Re, scratch0Im, scratch1Re, scratch1Im, scratch2Re, scratch2Im, scratch3Re, scratch3Im, scratch4Re, scratch4Im, scratch5Re, scratch5Im, out0Re, out0Im, out1Re, out1Im, out2Re, out2Im, out3Re, out3Im, tRe, tIm; var tw1 = 0, tw2 = 0, tw3 = 0, stride2 = 2 * stride, stride3 = 3 * stride, idx0 = outIdx, idx1 = outIdx + m, idx2 = outIdx + 2 * m, idx3 = outIdx + 3 * m; var scale = 0.5; // sqrt(1/4) var idx0End = idx0 + m; while (idx0 < idx0End) { // out0 = out[idx0] / sqrt(4) out0Re = outRe[idx0] * scale; out0Im = outIm[idx0] * scale; // out1 = out[idx1] / sqrt(4) out1Re = outRe[idx1] * scale; out1Im = outIm[idx1] * scale; // out2 = out[idx2] / sqrt(4) out2Re = outRe[idx2] * scale; out2Im = outIm[idx2] * scale; // out3 = out[idx3] / sqrt(4) out3Re = outRe[idx3] * scale; out3Im = outIm[idx3] * scale; // scratch0 = out1 * tw[tw1] tRe = twRe[tw1]; tIm = twIm[tw1]; scratch0Re = out1Re * tRe - out1Im * tIm; scratch0Im = out1Re * tIm + out1Im * tRe; // scratch1 = out2 * tw[tw2] tRe = twRe[tw2]; tIm = twIm[tw2]; scratch1Re = out2Re * tRe - out2Im * tIm; scratch1Im = out2Re * tIm + out2Im * tRe; // scratch2 = out3 * tw[tw3] tRe = twRe[tw3]; tIm = twIm[tw3]; scratch2Re = out3Re * tRe - out3Im * tIm; scratch2Im = out3Re * tIm + out3Im * tRe; // scratch5 = out0 - scratch1 scratch5Re = out0Re - scratch1Re; scratch5Im = out0Im - scratch1Im; // out0 += scratch1 out0Re += scratch1Re; out0Im += scratch1Im; // scratch3 = scratch0 + scratch2 scratch3Re = scratch0Re + scratch2Re; scratch3Im = scratch0Im + scratch2Im; // scratch4 = scratch0 - scratch2 scratch4Re = scratch0Re - scratch2Re; scratch4Im = scratch0Im - scratch2Im; // out[idx2] = out0 - scratch3 outRe[idx2] = out0Re - scratch3Re; outIm[idx2] = out0Im - scratch3Im; // out[idx0] = out0 + scratch3 outRe[idx0] = out0Re + scratch3Re; outIm[idx0] = out0Im + scratch3Im; if (inverse) { outRe[idx1] = scratch5Re - scratch4Im; outIm[idx1] = scratch5Im + scratch4Re; outRe[idx3] = scratch5Re + scratch4Im; outIm[idx3] = scratch5Im - scratch4Re; } else { outRe[idx1] = scratch5Re + scratch4Im; outIm[idx1] = scratch5Im - scratch4Re; outRe[idx3] = scratch5Re - scratch4Im; outIm[idx3] = scratch5Im + scratch4Re; } tw1 += stride; tw2 += stride2; tw3 += stride3; ++idx0; ++idx1; ++idx2; ++idx3; } }; var butterfly5 = function (outRe, outIm, outIdx, stride, twRe, twIm, m) { var scratch0Re, scratch0Im, scratch1Re, scratch1Im, scratch2Re, scratch2Im, scratch3Re, scratch3Im, scratch4Re, scratch4Im, scratch5Re, scratch5Im, scratch6Re, scratch6Im, scratch7Re, scratch7Im, scratch8Re, scratch8Im, scratch9Re, scratch9Im, scratch10Re, scratch10Im, scratch11Re, scratch11Im, scratch12Re, scratch12Im, out0Re, out0Im, out1Re, out1Im, out2Re, out2Im, out3Re, out3Im, out4Re, out4Im, tRe, tIm; var tw1 = 0, tw2 = 0, tw3 = 0, tw4 = 0, stride2 = 2 * stride, stride3 = 3 * stride, stride4 = 4 * stride; var idx0 = outIdx, idx1 = outIdx + m, idx2 = outIdx + 2 * m, idx3 = outIdx + 3 * m, idx4 = outIdx + 4 * m; // ya = tw[stride*m]; var yaRe = twRe[stride * m], yaIm = twIm[stride * m]; // yb = tw[stride*2*m]; var ybRe = twRe[stride * 2 * m], ybIm = twIm[stride * 2 * m]; var scale = 0.4472135954999579; // sqrt(1/5) var idx0End = idx0 + m; while (idx0 < idx0End) { // out0 = out[idx0] / sqrt(5) out0Re = outRe[idx0] * scale; out0Im = outIm[idx0] * scale; // out1 = out[idx1] / sqrt(5) out1Re = outRe[idx1] * scale; out1Im = outIm[idx1] * scale; // out2 = out[idx2] / sqrt(5) out2Re = outRe[idx2] * scale; out2Im = outIm[idx2] * scale; // out3 = out[idx3] / sqrt(5) out3Re = outRe[idx3] * scale; out3Im = outIm[idx3] * scale; // out4 = out[idx4] / sqrt(5) out4Re = outRe[idx4] * scale; out4Im = outIm[idx4] * scale; // scratch0 = out0; scratch0Re = out0Re; scratch0Im = out0Im; // scratch1 = out1 * tw[tw1] tRe = twRe[tw1]; tIm = twIm[tw1]; scratch1Re = out1Re * tRe - out1Im * tIm; scratch1Im = out1Re * tIm + out1Im * tRe; // scratch2 = out2 * tw[tw2] tRe = twRe[tw2]; tIm = twIm[tw2]; scratch2Re = out2Re * tRe - out2Im * tIm; scratch2Im = out2Re * tIm + out2Im * tRe; // scratch3 = out3 * tw[tw3] tRe = twRe[tw3]; tIm = twIm[tw3]; scratch3Re = out3Re * tRe - out3Im * tIm; scratch3Im = out3Re * tIm + out3Im * tRe; // scratch4 = out4 * tw[tw4] tRe = twRe[tw4]; tIm = twIm[tw4]; scratch4Re = out4Re * tRe - out4Im * tIm; scratch4Im = out4Re * tIm + out4Im * tRe; // scratch7 = scratch1 + scratch4 scratch7Re = scratch1Re + scratch4Re; scratch7Im = scratch1Im + scratch4Im; // scratch10 = scratch1 - scratch4 scratch10Re = scratch1Re - scratch4Re; scratch10Im = scratch1Im - scratch4Im; // scratch8 = scratch2 + scratch2 scratch8Re = scratch2Re + scratch3Re; scratch8Im = scratch2Im + scratch3Im; // scratch9 = scratch2 - scratch3 scratch9Re = scratch2Re - scratch3Re; scratch9Im = scratch2Im - scratch3Im; // out[idx0] = out0 + scratch7 + scratch8 outRe[idx0] = out0Re + scratch7Re + scratch8Re; outIm[idx0] = out0Im + scratch7Im + scratch8Im; scratch5Re = scratch0Re + scratch7Re * yaRe + scratch8Re * ybRe; scratch5Im = scratch0Im + scratch7Im * yaRe + scratch8Im * ybRe; scratch6Re = scratch10Im * yaIm + scratch9Im * ybIm; scratch6Im = -scratch10Re * yaIm - scratch9Re * ybIm; // out[idx1] = scratch5 - scratch6 outRe[idx1] = scratch5Re - scratch6Re; outIm[idx1] = scratch5Im - scratch6Im; // out[idx4] = scratch5 + scratch6 outRe[idx4] = scratch5Re + scratch6Re; outIm[idx4] = scratch5Im + scratch6Im; scratch11Re = scratch0Re + scratch7Re * ybRe + scratch8Re * yaRe; scratch11Im = scratch0Im + scratch7Im * ybRe + scratch8Im * yaRe; scratch12Re = -scratch10Im * ybIm + scratch9Im * yaIm; scratch12Im = scratch10Re * ybIm - scratch9Re * yaIm; // out[idx2] = scratch11 + scratch12 outRe[idx2] = scratch11Re + scratch12Re; outIm[idx2] = scratch11Im + scratch12Im; // out[idx3] = scratch11 - scratch12 outRe[idx3] = scratch11Re - scratch12Re; outIm[idx3] = scratch11Im - scratch12Im; tw1 += stride; tw2 += stride2; tw3 += stride3; tw4 += stride4; ++idx0; ++idx1; ++idx2; ++idx3; ++idx4; } }; var butterflyN = function (outRe, outIm, outIdx, stride, twRe, twIm, m, p, size) { var u, q1, q, idx0; var out0Re, out0Im, aRe, aIm, tRe, tIm; // FIXME: Allocate statically var scratchRe = new Float32Array(p); var scratchIm = new Float32Array(p); var scale = Math.sqrt(1 / p); for (u = 0; u < m; ++u) { idx0 = outIdx + u; for (q1 = 0; q1 < p; ++q1) { // scratch[q1] = out[idx0] / sqrt(p) scratchRe[q1] = outRe[idx0] * scale; scratchIm[q1] = outIm[idx0] * scale; idx0 += m; } idx0 = outIdx + u; var tw1Incr = stride * u; for (q1 = 0; q1 < p; ++q1) { // out0 = scratch[0] out0Re = scratchRe[0]; out0Im = scratchIm[0]; var tw1 = 0; for (q = 1; q < p; ++q) { tw1 += tw1Incr; if (tw1 >= size) tw1 -= size; // out0 += scratch[q] * tw[tw1] aRe = scratchRe[q], aIm = scratchIm[q]; tRe = twRe[tw1], tIm = twIm[tw1]; out0Re += aRe * tRe - aIm * tIm; out0Im += aRe * tIm + aIm * tRe; } // out[idx0] = out0 outRe[idx0] = out0Re; outIm[idx0] = out0Im; idx0 += m; tw1Incr += stride; } } }; var work = function (outRe, outIm, outIdx, fRe, fIm, fIdx, stride, inStride, factors, factorsIdx, twRe, twIm, size, inverse) { var p = factors[factorsIdx++]; // Radix var m = factors[factorsIdx++]; // Stage's FFT length / p var outIdxBeg = outIdx; var outIdxEnd = outIdx + p * m; var fIdxIncr = stride * inStride; if (m == 1) { do { outRe[outIdx] = fRe[fIdx]; outIm[outIdx] = fIm[fIdx]; fIdx += fIdxIncr; ++outIdx; } while (outIdx != outIdxEnd); } else { do { // DFT of size m*p performed by doing p instances of smaller DFTs of // size m, each one takes a decimated version of the input. work(outRe, outIm, outIdx, fRe, fIm, fIdx, stride * p, inStride, factors, factorsIdx, twRe, twIm, size, inverse); fIdx += fIdxIncr; outIdx += m; } while (outIdx != outIdxEnd); } outIdx = outIdxBeg; // Recombine the p smaller DFTs switch (p) { case 2: butterfly2(outRe, outIm, outIdx, stride, twRe, twIm, m); break; case 3: butterfly3(outRe, outIm, outIdx, stride, twRe, twIm, m); break; case 4: butterfly4(outRe, outIm, outIdx, stride, twRe, twIm, m, inverse); break; case 5: butterfly5(outRe, outIm, outIdx, stride, twRe, twIm, m); break; default: butterflyN(outRe, outIm, outIdx, stride, twRe, twIm, m, p, size); break; } }; /* facBuf is populated by p1,m1,p2,m2, ... where p[i] * m[i] = m[i-1] m0 = n */ var factor = function (n, facBuf) { // Factor out powers of 4, powers of 2, then any remaining primes var p = 4; var floorSqrt = Math.floor(Math.sqrt(n)); var idx = 0; do { while (n % p) { switch (p) { case 4: p = 2; break; case 2: p = 3; break; default: p += 2; break; } if (p > floorSqrt) p = n; } n = Math.floor(n / p); facBuf[idx++] = p; facBuf[idx++] = n; } while (n > 1); }; var FFT = function (size) { if (!size) size = 256; Object.defineProperty(this, "size", { configurable: false, writable: false, value: size }); // Allocate arrays for twiddle factors this._twiddlesFwdRe = new Float32Array(size); this._twiddlesFwdIm = new Float32Array(size); this._twiddlesInvRe = this._twiddlesFwdRe; this._twiddlesInvIm = new Float32Array(size); // Init twiddle factors (both forward & reverse) for (var i = 0; i < size; ++i) { var phase = -2 * Math.PI * i / size; var cosPhase = Math.cos(phase), sinPhase = Math.sin(phase); this._twiddlesFwdRe[i] = cosPhase; this._twiddlesFwdIm[i] = sinPhase; this._twiddlesInvIm[i] = -sinPhase; } // Allocate arrays for radix plan this._factors = new Int32Array(2 * 32); // MAXFACTORS = 32 // Init radix factors (mixed radix breakdown) // FIXME: Something seems to go wrong when using an FFT size that can be // factorized into more than one butterflyN (e.g. try an FFT size of 11*13). factor(size, this._factors); }; FFT.prototype.forwardCplx = function (dstReal, dstImag, xReal, xImag) { var twRe = this._twiddlesFwdRe; var twIm = this._twiddlesFwdIm; work(dstReal, dstImag, 0, xReal, xImag, 0, 1, 1, this._factors, 0, twRe, twIm, this.size, false); }; FFT.prototype.forward = function (dstReal, dstImag, x) { // FIXME: Optimize this case (real input signal) this.forwardCplx(dstReal, dstImag, x, new Float32Array(this.size)); }; FFT.prototype.inverseCplx = function (dstReal, dstImag, xReal, xImag) { var twRe = this._twiddlesInvRe; var twIm = this._twiddlesInvIm; work(dstReal, dstImag, 0, xReal, xImag, 0, 1, 1, this._factors, 0, twRe, twIm, this.size, true); }; FFT.prototype.inverse = function (dst, xReal, xImag) { // FIXME: Optimize this case (real output signal) this.inverseCplx(dst, new Float32Array(this.size), xReal, xImag); }; context.FFT = FFT; })(); ; /** Random.js library. * * The code is licensed as LGPL. */ /* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 THE COPYRIGHT OWNER OR 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. Any feedback is very welcome. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) */ var Random = function(seed) { seed = (seed === undefined) ? (new Date()).getTime() : seed; if (typeof(seed) !== 'number' // ARG_CHECK || Math.ceil(seed) != Math.floor(seed)) { // ARG_CHECK throw new TypeError("seed value must be an integer"); // ARG_CHECK } // ARG_CHECK /* Period parameters */ this.N = 624; this.M = 397; this.MATRIX_A = 0x9908b0df; /* constant vector a */ this.UPPER_MASK = 0x80000000; /* most significant w-r bits */ this.LOWER_MASK = 0x7fffffff; /* least significant r bits */ this.mt = new Array(this.N); /* the array for the state vector */ this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */ //this.init_genrand(seed); this.init_by_array([seed], 1); }; /* initializes mt[N] with a seed */ Random.prototype.init_genrand = function(s) { this.mt[0] = s >>> 0; for (this.mti=1; this.mti<this.N; this.mti++) { var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30); this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti; /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ this.mt[this.mti] >>>= 0; /* for >32 bit machines */ } }; /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ /* slight change for C++, 2004/2/26 */ Random.prototype.init_by_array = function(init_key, key_length) { var i, j, k; this.init_genrand(19650218); i=1; j=0; k = (this.N>key_length ? this.N : key_length); for (; k; k--) { var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30); this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525))) + init_key[j] + j; /* non linear */ this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; } if (j>=key_length) j=0; } for (k=this.N-1; k; k--) { var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30); this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i; /* non linear */ this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ i++; if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; } } this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ }; /* generates a random number on [0,0xffffffff]-interval */ Random.prototype.genrand_int32 = function() { var y; var mag01 = new Array(0x0, this.MATRIX_A); /* mag01[x] = x * MATRIX_A for x=0,1 */ if (this.mti >= this.N) { /* generate N words at one time */ var kk; if (this.mti == this.N+1) /* if init_genrand() has not been called, */ this.init_genrand(5489); /* a default initial seed is used */ for (kk=0;kk<this.N-this.M;kk++) { y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK); this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (;kk<this.N-1;kk++) { y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK); this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK); this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; this.mti = 0; } y = this.mt[this.mti++]; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y >>> 0; }; /* generates a random number on [0,0x7fffffff]-interval */ Random.prototype.genrand_int31 = function() { return (this.genrand_int32()>>>1); }; /* generates a random number on [0,1]-real-interval */ Random.prototype.genrand_real1 = function() { return this.genrand_int32()*(1.0/4294967295.0); /* divided by 2^32-1 */ }; /* generates a random number on [0,1)-real-interval */ Random.prototype.random = function() { if (this.pythonCompatibility) { if (this.skip) { this.genrand_int32(); } this.skip = true; } return this.genrand_int32()*(1.0/4294967296.0); /* divided by 2^32 */ }; /* generates a random number on (0,1)-real-interval */ Random.prototype.genrand_real3 = function() { return (this.genrand_int32() + 0.5)*(1.0/4294967296.0); /* divided by 2^32 */ }; /* generates a random number on [0,1) with 53-bit resolution*/ Random.prototype.genrand_res53 = function() { var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); }; /* These real versions are due to Isaku Wada, 2002/01/09 added */ /**************************************************************************/ Random.prototype.LOG4 = Math.log(4.0); Random.prototype.SG_MAGICCONST = 1.0 + Math.log(4.5); Random.prototype.exponential = function (lambda) { if (arguments.length != 1) { // ARG_CHECK throw new SyntaxError("exponential() must " // ARG_CHECK + " be called with 'lambda' parameter"); // ARG_CHECK } // ARG_CHECK var r = this.random(); return -Math.log(r) / lambda; }; Random.prototype.gamma = function (alpha, beta) { if (arguments.length != 2) { // ARG_CHECK throw new SyntaxError("gamma() must be called" // ARG_CHECK + " with alpha and beta parameters"); // ARG_CHECK } // ARG_CHECK /* Based on Python 2.6 source code of random.py. */ if (alpha > 1.0) { var ainv = Math.sqrt(2.0 * alpha - 1.0); var bbb = alpha - this.LOG4; var ccc = alpha + ainv; while (true) { var u1 = this.random(); if ((u1 < 1e-7) || (u > 0.9999999)) { continue; } var u2 = 1.0 - this.random(); var v = Math.log(u1 / (1.0 - u1)) / ainv; var x = alpha * Math.exp(v); var z = u1 * u1 * u2; var r = bbb + ccc * v - x; if ((r + this.SG_MAGICCONST - 4.5 * z >= 0.0) || (r >= Math.log(z))) { return x * beta; } } } else if (alpha == 1.0) { var u = this.random(); while (u <= 1e-7) { u = this.random(); } return - Math.log(u) * beta; } else { while (true) { var u = this.random(); var b = (Math.E + alpha) / Math.E; var p = b * u; if (p <= 1.0) { var x = Math.pow(p, 1.0 / alpha); } else { var x = - Math.log((b - p) / alpha); } var u1 = this.random(); if (p > 1.0) { if (u1 <= Math.pow(x, (alpha - 1.0))) { break; } } else if (u1 <= Math.exp(-x)) { break; } } return x * beta; } }; Random.prototype.normal = function (mu, sigma) { if (arguments.length != 2) { // ARG_CHECK throw new SyntaxError("normal() must be called" // ARG_CHECK + " with mu and sigma parameters"); // ARG_CHECK } // ARG_CHECK var z = this.lastNormal; this.lastNormal = NaN; if (!z) { var a = this.random() * 2 * Math.PI; var b = Math.sqrt(-2.0 * Math.log(1.0 - this.random())); z = Math.cos(a) * b; this.lastNormal = Math.sin(a) * b; } return mu + z * sigma; }; Random.prototype.pareto = function (alpha) { if (arguments.length != 1) { // ARG_CHECK throw new SyntaxError("pareto() must be called" // ARG_CHECK + " with alpha parameter"); // ARG_CHECK } // ARG_CHECK var u = this.random(); return 1.0 / Math.pow((1 - u), 1.0 / alpha); }; Random.prototype.triangular = function (lower, upper, mode) { // http://en.wikipedia.org/wiki/Triangular_distribution if (arguments.length != 3) { // ARG_CHECK throw new SyntaxError("triangular() must be called" // ARG_CHECK + " with lower, upper and mode parameters"); // ARG_CHECK } // ARG_CHECK var c = (mode - lower) / (upper - lower); var u = this.random(); if (u <= c) { return lower + Math.sqrt(u * (upper - lower) * (mode - lower)); } else { return upper - Math.sqrt((1 - u) * (upper - lower) * (upper - mode)); } }; Random.prototype.uniform = function (lower, upper) { if (arguments.length != 2) { // ARG_CHECK throw new SyntaxError("uniform() must be called" // ARG_CHECK + " with lower and upper parameters"); // ARG_CHECK } // ARG_CHECK return lower + this.random() * (upper - lower); }; Random.prototype.weibull = function (alpha, beta) { if (arguments.length != 2) { // ARG_CHECK throw new SyntaxError("weibull() must be called" // ARG_CHECK + " with alpha and beta parameters"); // ARG_CHECK } // ARG_CHECK var u = 1.0 - this.random(); return alpha * Math.pow(-Math.log(u), 1.0 / beta); }; if (typeof window === "undefined" && typeof module !== "undefined" && module.exports) { module.exports = Random; } ;/*! Flocking 0.1, Copyright 2011-2014 Colin Clark | flockingjs.org */ /* * Flocking - Creative audio synthesis for the Web! * http://github.com/colinbdclark/flocking * * Copyright 2011-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, Float32Array, window, AudioContext, webkitAudioContext*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; var $ = fluid.registerNamespace("jQuery"); flock.fluid = fluid; flock.init = function (options) { var enviroOpts = !options ? undefined : { components: { audioSystem: { options: { model: options } } } }; var enviro = flock.enviro(enviroOpts); fluid.staticEnvironment.environment = flock.environment = enviro; // flock.enviro.shared is deprecated. Use "flock.environment" // or an IoC reference to {environment} instead flock.enviro.shared = enviro; return enviro; }; flock.ALL_CHANNELS = 32; // TODO: This should go. flock.OUT_UGEN_ID = "flocking-out"; flock.PI = Math.PI; flock.TWOPI = 2.0 * Math.PI; flock.HALFPI = Math.PI / 2.0; flock.LOG01 = Math.log(0.1); flock.LOG001 = Math.log(0.001); flock.ROOT2 = Math.sqrt(2); flock.rates = { AUDIO: "audio", CONTROL: "control", SCHEDULED: "scheduled", DEMAND: "demand", CONSTANT: "constant" }; fluid.registerNamespace("flock.debug"); flock.debug.failHard = true; flock.browser = function () { if (typeof navigator === "undefined") { return {}; } // This is a modified version of jQuery's browser detection code, // which they removed from jQuery 2.0. // Some of us still have to live in the messy reality of the web. var ua = navigator.userAgent.toLowerCase(), browser = {}, match, matched; match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; matched = { browser: match[1] || "", version: match[2] || "0" }; if (matched.browser) { browser[matched.browser] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if (browser.chrome) { browser.webkit = true; } else if (browser.webkit) { browser.safari = true; } return browser; }; // TODO: Move to components in the static environment and into the appropriate platform files. fluid.registerNamespace("flock.platform"); flock.platform.isBrowser = typeof window !== "undefined"; flock.platform.hasRequire = typeof require !== "undefined"; flock.platform.os = flock.platform.isBrowser ? window.navigator.platform : fluid.require("os").platform(); flock.platform.isLinux = flock.platform.os.indexOf("Linux") > -1; flock.platform.isAndroid = flock.platform.isLinux && flock.platform.os.indexOf("arm") > -1; flock.platform.isIOS = flock.platform.os === "iPhone" || flock.platform.os === "iPad" || flock.platform.os === "iPod"; flock.platform.isMobile = flock.platform.isAndroid || flock.platform.isIOS; flock.platform.browser = flock.browser(); flock.platform.isWebAudio = typeof AudioContext !== "undefined" || typeof webkitAudioContext !== "undefined"; flock.platform.audioEngine = flock.platform.isBrowser ? "webAudio" : "nodejs"; fluid.staticEnvironment.audioEngine = fluid.typeTag("flock.platform." + flock.platform.audioEngine); flock.shim = { URL: flock.platform.isBrowser ? (window.URL || window.webkitURL || window.msURL) : undefined }; flock.requireModule = function (moduleName, globalName) { if (flock.platform.isBrowser) { return window[globalName || moduleName]; } if (!flock.platform.hasRequire) { return undefined; } var resolvedName = flock.requireModule.paths[moduleName] || moduleName; var togo = require(resolvedName); return globalName ? togo[globalName] : togo; }; flock.requireModule.paths = { webarraymath: "../third-party/webarraymath/js/webarraymath.js", Random: "../third-party/simjs/js/random-0.26.js" }; /************* * Utilities * *************/ flock.noOp = function () {}; flock.isIterable = function (o) { var type = typeof o; return o && o.length !== undefined && type !== "string" && type !== "function"; }; flock.hasTag = function (obj, tag) { if (!obj || !tag) { return false; } return obj.tags && obj.tags.indexOf(tag) > -1; }; // TODO: Chrome profiler marks this function as unoptimized. // This should probably be factored into separate functions for // new and existing arrays. (e.g. "generate" vs. "fill") flock.generate = function (bufOrSize, generator) { var buf = typeof bufOrSize === "number" ? new Float32Array(bufOrSize) : bufOrSize, isFunc = typeof generator === "function", i; for (i = 0; i < buf.length; i++) { buf[i] = isFunc ? generator(i, buf) : generator; } return buf; }; flock.generate.silence = function (bufOrSize) { if (typeof bufOrSize === "number") { return new Float32Array(bufOrSize); } var buf = bufOrSize, i; for (i = 0; i < buf.length; i++) { buf[i] = 0.0; } return buf; }; /** * Performs an in-place reversal of all items in the array. * * @arg {Iterable} b a buffer or array to reverse * @return {Iterable} the buffer, reversed */ flock.reverse = function (b) { if (!b || !flock.isIterable(b) || b.length < 2) { return b; } // A native implementation of reverse() exists for regular JS arrays // and is partially implemented for TypedArrays. Use it if possible. if (typeof b.reverse === "function") { return b.reverse(); } var t; for (var l = 0, r = b.length - 1; l < r; l++, r--) { t = b[l]; b[l] = b[r]; b[r] = t; } return b; }; /** * Randomly selects an index from the specified array. */ flock.randomIndex = function (arr) { var max = arr.length - 1; return Math.round(Math.random() * max); }; /** * Randomly selects an item from an array-like object. * * @param {Array-like object} arr the array to choose from * @param {Function} a selection strategy; defaults to flock.randomIndex * @return a randomly selected list item */ flock.arrayChoose = function (arr, strategy) { strategy = strategy || flock.randomIndex; arr = fluid.makeArray(arr); var idx = strategy(arr); return arr[idx]; }; /** * Randomly selects an item from an array or object. * * @param {Array-like object|Object} collection the object to choose from * @return a randomly selected item from collection */ flock.choose = function (collection, strategy) { var key, val; if (flock.isIterable(collection)) { val = flock.arrayChoose(collection, strategy); return val; } key = flock.arrayChoose(collection.keys, strategy); val = collection[key]; return val; }; /** * Normalizes the specified buffer in place to the specified value. * * @param {Arrayable} buffer the buffer to normalize * @param {Number} normal the value to normalize the buffer to * @param {Arrayable} a buffer to output values into; if omitted, buffer will be modified in place * @return the buffer, normalized in place */ flock.normalize = function (buffer, normal, output) { output = output || buffer; var maxVal = 0.0, i, current, val; normal = normal === undefined ? 1.0 : normal; // Find the maximum value in the buffer. for (i = 0; i < buffer.length; i++) { current = Math.abs(buffer[i]); if (current > maxVal) { maxVal = current; } } // And then normalize the buffer in place. if (maxVal > 0.0) { for (i = 0; i < buffer.length; i++) { val = buffer[i]; output[i] = (val / maxVal) * normal; } } return output; }; flock.generateFourierTable = function (size, scale, numHarms, phase, amps) { phase *= flock.TWOPI; return flock.generate(size, function (i) { var harm, amp, w, val = 0.0; for (harm = 0; harm < numHarms; harm++) { amp = amps ? amps[harm] : 1.0; w = (harm + 1) * (i * scale); val += amp * Math.cos(w + phase); } return val; }); }; flock.generateNormalizedFourierTable = function (size, scale, numHarms, phase, ampGenFn) { var amps = flock.generate(numHarms, function (harm) { return ampGenFn(harm + 1); // Harmonics are indexed from 1 instead of 0. }); var table = flock.generateFourierTable(size, scale, numHarms, phase, amps); return flock.normalize(table); }; flock.fillTable = function (sizeOrTable, fillFn) { var len = typeof (sizeOrTable) === "number" ? sizeOrTable : sizeOrTable.length; return fillFn(sizeOrTable, flock.TWOPI / len); }; flock.tableGenerators = { sin: function (size, scale) { return flock.generate(size, function (i) { return Math.sin(i * scale); }); }, tri: function (size, scale) { return flock.generateNormalizedFourierTable(size, scale, 1000, 1.0, function (harm) { // Only odd harmonics, // amplitudes decreasing by the inverse square of the harmonic number return harm % 2 === 0 ? 0.0 : 1.0 / (harm * harm); }); }, saw: function (size, scale) { return flock.generateNormalizedFourierTable(size, scale, 10, -0.25, function (harm) { // All harmonics, // amplitudes decreasing by the inverse of the harmonic number return 1.0 / harm; }); }, square: function (size, scale) { return flock.generateNormalizedFourierTable(size, scale, 10, -0.25, function (harm) { // Only odd harmonics, // amplitudes decreasing by the inverse of the harmonic number return harm % 2 === 0 ? 0.0 : 1.0 / harm; }); }, hann: function (size) { // Hanning envelope: sin^2(i) for i from 0 to pi return flock.generate(size, function (i) { var y = Math.sin(Math.PI * i / size); return y * y; }); }, sinWindow: function (size) { return flock.generate(size, function (i) { return Math.sin(Math.PI * i / size); }); } }; flock.range = function (buf) { var range = { max: Number.NEGATIVE_INFINITY, min: Infinity }; var i, val; for (i = 0; i < buf.length; i++) { val = buf[i]; if (val > range.max) { range.max = val; } if (val < range.min) { range.min = val; } } return range; }; flock.scale = function (buf) { if (!buf) { return; } var range = flock.range(buf), mul = (range.max - range.min) / 2, sub = (range.max + range.min) / 2, i; for (i = 0; i < buf.length; i++) { buf[i] = (buf[i] - sub) / mul; } return buf; }; flock.copyBuffer = function (buffer, start, end) { if (end === undefined) { end = buffer.length; } var len = end - start, target = new Float32Array(len), i, j; for (i = start, j = 0; i < end; i++, j++) { target[j] = buffer[i]; } return target; }; flock.parseMidiString = function (midiStr) { if (!midiStr || midiStr.length < 2) { return NaN; } midiStr = midiStr.toLowerCase(); var secondChar = midiStr.charAt(1), splitIdx = secondChar === "#" || secondChar === "b" ? 2 : 1, note = midiStr.substring(0, splitIdx), octave = Number(midiStr.substring(splitIdx)), pitchClass = flock.midiFreq.noteNames[note], midiNum = octave * 12 + pitchClass; return midiNum; }; flock.midiFreq = function (midi, a4Freq, a4NoteNum, notesPerOctave) { a4Freq = a4Freq === undefined ? 440 : a4Freq; a4NoteNum = a4NoteNum === undefined ? 69 : a4NoteNum; notesPerOctave = notesPerOctave || 12; if (typeof midi === "string") { midi = flock.parseMidiString(midi); } return a4Freq * Math.pow(2, (midi - a4NoteNum) * 1 / notesPerOctave); }; flock.midiFreq.noteNames = { "b#": 0, "c": 0, "c#": 1, "db": 1, "d": 2, "d#": 3, "eb": 3, "e": 4, "e#": 5, "f": 5, "f#": 6, "gb": 6, "g": 7, "g#": 8, "ab": 8, "a": 9, "a#": 10, "bb": 10, "b": 11, "cb": 11 }; flock.interpolate = { /** * Performs simple truncation. */ none: function (idx, table) { idx = idx % table.length; return table[idx | 0]; }, /** * Performs linear interpolation. */ linear: function (idx, table) { var len = table.length; idx = idx % len; var i1 = idx | 0, i2 = (i1 + 1) % len, frac = idx - i1, y1 = table[i1], y2 = table[i2]; return y1 + frac * (y2 - y1); }, /** * Performs Hermite cubic interpolation. * * Based on Laurent De Soras' implementation at: * http://www.musicdsp.org/showArchiveComment.php?ArchiveID=93 * * @param idx {Number} an index into the table * @param table {Arrayable} the table from which values around idx should be drawn and interpolated * @return {Number} an interpolated value */ hermite: function (idx, table) { var len = table.length, intPortion = Math.floor(idx), i0 = intPortion % len, frac = idx - intPortion, im1 = i0 > 0 ? i0 - 1 : len - 1, i1 = (i0 + 1) % len, i2 = (i0 + 2) % len, xm1 = table[im1], x0 = table[i0], x1 = table[i1], x2 = table[i2], c = (x1 - xm1) * 0.5, v = x0 - x1, w = c + v, a = w + v + (x2 - x0) * 0.5, bNeg = w + a, val = (((a * frac) - bNeg) * frac + c) * frac + x0; return val; } }; flock.interpolate.cubic = flock.interpolate.hermite; flock.log = { fail: function (msg) { fluid.log(fluid.logLevel.FAIL, msg); }, warn: function (msg) { fluid.log(fluid.logLevel.WARN, msg); }, debug: function (msg) { fluid.log(fluid.logLevel.INFO, msg); } }; flock.fail = function (msg) { if (flock.debug.failHard) { throw new Error(msg); } else { flock.log.fail(msg); } }; flock.pathParseError = function (root, path, token) { var msg = "Error parsing path '" + path + "'. Segment '" + token + "' could not be resolved. Root object was: " + fluid.prettyPrintJSON(root); flock.fail(msg); }; flock.get = function (root, path) { if (!root) { return fluid.getGlobalValue(path); } if (arguments.length === 1 && typeof root === "string") { return fluid.getGlobalValue(root); } if (!path || path === "") { return; } var tokenized = path === "" ? [] : String(path).split("."), valForSeg = root[tokenized[0]], i; for (i = 1; i < tokenized.length; i++) { if (valForSeg === null || valForSeg === undefined) { flock.pathParseError(root, path, tokenized[i - 1]); return; } valForSeg = valForSeg[tokenized[i]]; } return valForSeg; }; flock.set = function (root, path, value) { if (!root || !path || path === "") { return; } var tokenized = String(path).split("."), l = tokenized.length, prop = tokenized[0], i, type; for (i = 1; i < l; i++) { root = root[prop]; type = typeof root; if (type !== "object") { flock.fail("Error while setting a value at path '" + path + "'. A non-container object was found at segment '" + prop + "'. Value: " + root); return; } prop = tokenized[i]; if (root[prop] === undefined) { root[prop] = {}; } } root[prop] = value; return value; }; flock.invoke = function (root, path, args) { var fn = typeof root === "function" ? root : flock.get(root, path); if (typeof fn !== "function") { flock.fail("Path '" + path + "' does not resolve to a function."); return; } return fn.apply(null, args); }; flock.input = {}; flock.input.shouldExpand = function (inputName) { return flock.parse.specialInputs.indexOf(inputName) < 0; }; // TODO: Replace this with a regular expression; // this produces too much garbage! flock.input.pathExpander = function (path) { var segs = fluid.model.parseEL(path), separator = "inputs", len = segs.length, penIdx = len - 1, togo = [], i; for (i = 0; i < penIdx; i++) { var seg = segs[i]; var nextSeg = segs[i + 1]; togo.push(seg); if (nextSeg === "model" || nextSeg === "options") { togo = togo.concat(segs.slice(i + 1, penIdx)); break; } if (!isNaN(Number(nextSeg))) { continue; } togo.push(separator); } togo.push(segs[penIdx]); return togo.join("."); }; flock.input.expandPaths = function (paths) { var expanded = {}, path, expandedPath, value; for (path in paths) { expandedPath = flock.input.pathExpander(path); value = paths[path]; expanded[expandedPath] = value; } return expanded; }; flock.input.expandPath = function (path) { return (typeof path === "string") ? flock.input.pathExpander(path) : flock.input.expandPaths(path); }; flock.input.getValueForPath = function (root, path) { path = flock.input.expandPath(path); var input = flock.get(root, path); // If the unit generator is a valueType ugen, return its value, otherwise return the ugen itself. return flock.hasTag(input, "flock.ugen.valueType") ? input.inputs.value : input; }; flock.input.getValuesForPathArray = function (root, paths) { var values = {}, i, path; for (i = 0; i < paths.length; i++) { path = paths[i]; values[path] = flock.input.get(root, path); } return values; }; flock.input.getValuesForPathObject = function (root, pathObj) { var key; for (key in pathObj) { pathObj[key] = flock.input.get(root, key); } return pathObj; }; /** * Gets the value of the ugen at the specified path. * * @param {String} path the ugen's path within the synth graph * @return {Number|UGen} a scalar value in the case of a value ugen, otherwise the ugen itself */ flock.input.get = function (root, path) { return typeof path === "string" ? flock.input.getValueForPath(root, path) : flock.isIterable(path) ? flock.input.getValuesForPathArray(root, path) : flock.input.getValuesForPathObject(root, path); }; flock.input.resolveValue = function (root, path, val, target, inputName, previousInput, valueParser) { // Check to see if the value is actually a "get expression" // (i.e. an EL path wrapped in ${}) and resolve it if necessary. if (typeof val === "string") { var extracted = fluid.extractEL(val, flock.input.valueExpressionSpec); if (extracted) { var resolved = flock.input.getValueForPath(root, extracted); if (resolved === undefined) { flock.log.debug("The value expression '" + val + "' resolved to undefined. " + "If this isn't expected, check to ensure that your path is valid."); } return resolved; } } return flock.input.shouldExpand(inputName) && valueParser ? valueParser(val, path, target, previousInput) : val; }; flock.input.valueExpressionSpec = { ELstyle: "${}" }; flock.input.setValueForPath = function (root, path, val, baseTarget, valueParser) { path = flock.input.expandPath(path); var previousInput = flock.get(root, path), lastDotIdx = path.lastIndexOf("."), inputName = path.slice(lastDotIdx + 1), target = lastDotIdx > -1 ? flock.get(root, path.slice(0, path.lastIndexOf(".inputs"))) : baseTarget, resolvedVal = flock.input.resolveValue(root, path, val, target, inputName, previousInput, valueParser); flock.set(root, path, resolvedVal); if (target && target.onInputChanged) { target.onInputChanged(inputName); } return resolvedVal; }; flock.input.setValuesForPaths = function (root, valueMap, baseTarget, valueParser) { var resultMap = {}, path, val, result; for (path in valueMap) { val = valueMap[path]; result = flock.input.set(root, path, val, baseTarget, valueParser); resultMap[path] = result; } return resultMap; }; /** * Sets the value of the ugen at the specified path. * * @param {String} path the ugen's path within the synth graph * @param {Number || UGenDef} val a scalar value (for Value ugens) or a UGenDef object * @return {UGen} the newly created UGen that was set at the specified path */ flock.input.set = function (root, path, val, baseTarget, valueParser) { return typeof path === "string" ? flock.input.setValueForPath(root, path, val, baseTarget, valueParser) : flock.input.setValuesForPaths(root, path, baseTarget, valueParser); }; fluid.defaults("flock.nodeList", { gradeNames: ["fluid.eventedComponent", "autoInit"], members: { nodes: [], namedNodes: {} }, invokers: { insert: { funcName: "flock.nodeList.insert", // TODO: Backwards arguments? args: [ "{arguments}.0", // The index to insert it at. "{arguments}.1", // The node to insert. "{that}.nodes", "{that}.events.onInsert.fire" ] }, head: { func: "{that}.insert", args: [0, "{arguments}.0"] }, tail: { funcName: "flock.nodeList.tail", args: ["{arguments}.0", "{that}.nodes", "{that}.insert"] }, before: { funcName: "flock.nodeList.before", args: [ "{arguments}.0", // Reference node. "{arguments}.1", // Node to add. "{that}.nodes", "{that}.insert" ] }, after: { funcName: "flock.nodeList.after", args: [ "{arguments}.0", // Reference node. "{arguments}.1", // Node to add. "{that}.nodes", "{that}.insert" ] }, remove: { funcName: "flock.nodeList.remove", args: [ "{arguments}.0", // Node to remove. "{that}.nodes", "{that}.events.onRemove.fire" ] }, replace: { funcName: "flock.nodeList.replace", args: [ // TODO: Backwards arguments? "{arguments}.0", // New node. "{arguments}.1", // Old node. "{that}.nodes", "{that}.head", "{that}.events.onRemove.fire", "{that}.events.onInsert.fire" ] }, clearAll: { func: "{that}.events.onClearAll.fire" } }, events: { onInsert: null, onRemove: null, onClearAll: null }, listeners: { onClearAll: [ { func: "fluid.clear", args: "{that}.nodes" }, { func: "fluid.clear", args: "{that}.namedNodes" } ], onInsert: { funcName: "flock.nodeList.registerNode", args: ["{arguments}.0", "{that}.namedNodes"] }, onRemove: { funcName: "flock.nodeList.unregisterNode", args: ["{arguments}.0", "{that}.namedNodes"] } } }); flock.nodeList.insert = function (idx, node, nodes, onInsert) { if (idx < 0) { idx = 0; } nodes.splice(idx, 0, node); onInsert(node, idx); return idx; }; flock.nodeList.registerNode = function (node, namedNodes) { if (!node.nickName) { return; } namedNodes[node.nickName] = node; }; flock.nodeList.before = function (refNode, node, nodes, insertFn) { var refIdx = nodes.indexOf(refNode); return insertFn(refIdx, node); }; flock.nodeList.after = function (refNode, node, nodes, insertFn) { var refIdx = nodes.indexOf(refNode), atIdx = refIdx + 1; return insertFn(atIdx, node); }; flock.nodeList.tail = function (node, nodes, insertFn) { var idx = nodes.length; return insertFn(idx, node); }; flock.nodeList.remove = function (node, nodes, onRemove) { var idx = nodes.indexOf(node); if (idx > -1) { nodes.splice(idx, 1); onRemove(node); } return idx; }; flock.nodeList.unregisterNode = function (node, namedNodes) { delete namedNodes[node.nickName]; }; flock.nodeList.replace = function (newNode, oldNode, nodes, notFoundFn, onRemove, onInsert) { var idx = nodes.indexOf(oldNode); if (idx < 0) { return notFoundFn(newNode); } nodes[idx] = newNode; onRemove(oldNode); onInsert(newNode); return idx; }; /*********************** * Synths and Playback * ***********************/ fluid.defaults("flock.audioSystem", { gradeNames: ["fluid.standardRelayComponent", "autoInit"], channelRange: { min: 1, max: 32 }, outputBusRange: { min: 2, max: 1024 }, inputBusRange: { min: 1, // TODO: This constraint should be removed. max: 32 }, model: { rates: { audio: 44100, control: 689.0625, scheduled: 0, demand: 0, constant: 0 }, blockSize: 64, numBlocks: 16, chans: 2, numInputBuses: 2, numBuses: 8, bufferSize: "@expand:flock.audioSystem.defaultBufferSize()" }, modelRelay: [ { target: "rates.control", singleTransform: { type: "fluid.transforms.binaryOp", left: "{that}.model.rates.audio", operator: "/", right: "{that}.model.blockSize" } }, { target: "numBlocks", singleTransform: { type: "fluid.transforms.binaryOp", left: "{that}.model.bufferSize", operator: "/", right: "{that}.model.blockSize" } }, { target: "chans", singleTransform: { type: "fluid.transforms.limitRange", input: "{that}.model.chans", min: "{that}.options.channelRange.min", max: "{that}.options.channelRange.max" } }, { target: "numInputBuses", singleTransform: { type: "fluid.transforms.limitRange", input: "{that}.model.numInputBuses", min: "{that}.options.inputBusRange.min", max: "{that}.options.inputBusRange.max" } }, { target: "numBuses", singleTransform: { type: "fluid.transforms.free", func: "flock.audioSystem.clampNumBuses", args: ["{that}.model.numBuses", "{that}.options.outputBusRange", "{that}.model.chans"] } } ] }); flock.audioSystem.clampNumBuses = function (numBuses, outputBusRange, chans) { numBuses = Math.max(numBuses, Math.max(chans, outputBusRange.min)); numBuses = Math.min(numBuses, outputBusRange.max); return numBuses; }; flock.audioSystem.defaultBufferSize = function () { return flock.platform.isMobile ? 8192 : flock.platform.browser.mozilla ? 2048 : 1024; }; /***************** * Node Evalutor * *****************/ fluid.defaults("flock.nodeEvaluator", { gradeNames: ["fluid.standardRelayComponent", "autoInit"], model: "{audioSystem}.model", members: { nodes: "{enviro}.nodes", buses: "{busManager}.buses" }, invokers: { gen: { funcName: "flock.nodeEvaluator.gen", args: ["{that}.nodes"] }, clearBuses: { funcName: "flock.nodeEvaluator.clearBuses", args: [ "{that}.model.numBuses", "{that}.model.blockSize", "{that}.buses" ] } } }); flock.nodeEvaluator.gen = function (nodes) { var i, node; // Now evaluate each node. for (i = 0; i < nodes.length; i++) { node = nodes[i]; node.genFn(node); } }; flock.nodeEvaluator.clearBuses = function (numBuses, busLen, buses) { for (var i = 0; i < numBuses; i++) { var bus = buses[i]; for (var j = 0; j < busLen; j++) { bus[j] = 0; } } }; fluid.defaults("flock.audioStrategy", { gradeNames: ["fluid.standardRelayComponent"], components: { nodeEvaluator: { type: "flock.nodeEvaluator" } }, invokers: { reset: { func: "{that}.events.onReset.fire" } }, events: { onStart: "{enviro}.events.onStart", onStop: "{enviro}.events.onStop", onReset: "{enviro}.events.onReset" } }); // TODO: Refactor how buses work so that they're clearly // delineated into types--input, output, and interconnect. // TODO: Get rid of the concept of buses altogether. fluid.defaults("flock.busManager", { gradeNames: ["fluid.standardRelayComponent", "autoInit"], model: { nextAvailableBus: { input: 0, interconnect: 0 } }, members: { buses: { expander: { funcName: "flock.enviro.createAudioBuffers", args: ["{audioSystem}.model.numBuses", "{audioSystem}.model.blockSize"] } } }, invokers: { acquireNextBus: { funcName: "flock.busManager.acquireNextBus", args: [ "{arguments}.0", // The type of bus, either "input" or "interconnect". "{that}.buses", "{that}.applier", "{that}.model", "{audioSystem}.model.chans", "{audioSystem}.model.numInputBuses" ] } } }); flock.busManager.acquireNextBus = function (type, buses, applier, m, chans, numInputBuses) { var busNum = m.nextAvailableBus[type]; if (busNum === undefined) { flock.fail("An invalid bus type was specified when invoking " + "flock.busManager.acquireNextBus(). Type was: " + type); return; } // Input buses start immediately after the output buses. var offsetBusNum = busNum + chans, offsetBusMax = chans + numInputBuses; // Interconnect buses are after the input buses. if (type === "interconnect") { offsetBusNum += numInputBuses; offsetBusMax = buses.length; } if (offsetBusNum >= offsetBusMax) { flock.fail("Unable to aquire a bus. There are insufficient buses available. " + "Please use an existing bus or configure additional buses using the enviroment's " + "numBuses and numInputBuses parameters."); return; } applier.change("nextAvailableBus." + type, ++busNum); return offsetBusNum; }; fluid.defaults("flock.enviro", { gradeNames: ["fluid.standardRelayComponent", "flock.nodeList", "autoInit"], members: { buffers: {}, bufferSources: {} }, components: { asyncScheduler: { type: "flock.scheduler.async" }, audioSystem: { type: "flock.audioSystem.platform" }, audioStrategy: { type: "flock.audioStrategy.platform", options: { audioSettings: "{audioSystem}.model" } }, busManager: { type: "flock.busManager" } }, model: { isPlaying: false }, invokers: { /** * Generates a block of samples by evaluating all registered nodes. */ gen: "flock.enviro.gen({audioStrategy}.nodeEvaluator)", /** * Starts generating samples from all synths. * * @param {Number} dur optional duration to play in seconds */ start: "flock.enviro.start({that}.model, {that}.events.onStart.fire)", /** * Deprecated. Use start() instead. */ play: "{that}.start", /** * Stops generating samples. */ stop: "flock.enviro.stop({that}.model, {that}.events.onStop.fire)", /** * Fully resets the state of the environment. */ reset: "{that}.events.onReset.fire()", /** * Registers a shared buffer. * * @param {BufferDesc} bufDesc the buffer description object to register */ registerBuffer: "flock.enviro.registerBuffer({arguments}.0, {that}.buffers)", /** * Releases a shared buffer. * * @param {String|BufferDesc} bufDesc the buffer description (or string id) to release */ releaseBuffer: "flock.enviro.releaseBuffer({arguments}.0, {that}.buffers)", /** * Saves a buffer to the user's computer. * * @param {String|BufferDesc} id the id of the buffer to save * @param {String} path the path to save the buffer to (if relevant) */ saveBuffer: { funcName: "flock.enviro.saveBuffer", args: [ "{arguments}.0", "{that}.buffers", "{audioStrategy}" ] } }, events: { onStart: null, onPlay: "{that}.events.onStart", // Deprecated. Use onStart instead. onStop: null, onReset: null }, listeners: { onStart: [ "{that}.applier.change(isPlaying, true)", ], onStop: [ "{that}.applier.change(isPlaying, false)" ], onReset: [ "{that}.stop()", "{asyncScheduler}.clearAll()", { func: "{that}.applier.change", args: ["nextAvailableBus.input", []] }, { func: "{that}.applier.change", args: ["nextAvailableBus.interconnect", []] }, "{that}.clearAll()" ] } }); flock.enviro.registerBuffer = function (bufDesc, buffers) { if (bufDesc.id) { buffers[bufDesc.id] = bufDesc; } }; flock.enviro.releaseBuffer = function (bufDesc, buffers) { if (!bufDesc) { return; } var id = typeof bufDesc === "string" ? bufDesc : bufDesc.id; delete buffers[id]; }; flock.enviro.saveBuffer = function (o, buffers, audioStrategy) { if (typeof o === "string") { o = { buffer: o }; } if (typeof o.buffer === "string") { var id = o.buffer; o.buffer = buffers[id]; o.buffer.id = id; } o.type = o.type || "wav"; o.path = o.path || o.buffer.id + "." + o.type; o.format = o.format || "int16"; return audioStrategy.saveBuffer(o, o.buffer); }; flock.enviro.gen = function (nodeEvaluator) { nodeEvaluator.clearBuses(); nodeEvaluator.gen(); }; flock.enviro.start = function (model, onStart) { if (!model.isPlaying) { onStart(); } }; flock.enviro.stop = function (model, onStop) { if (model.isPlaying) { onStop(); } }; flock.enviro.createAudioBuffers = function (numBufs, blockSize) { var bufs = [], i; for (i = 0; i < numBufs; i++) { bufs[i] = new Float32Array(blockSize); } return bufs; }; fluid.defaults("flock.autoEnviro", { gradeNames: ["fluid.eventedComponent", "autoInit"], members: { enviro: "@expand:flock.autoEnviro.initEnvironment()" } }); flock.autoEnviro.initEnvironment = function () { if (!flock.environment) { flock.init(); } return flock.environment; }; fluid.defaults("flock.node", { gradeNames: ["flock.autoEnviro", "fluid.standardRelayComponent", "autoInit"], model: {} }); fluid.defaults("flock.ugenNodeList", { gradeNames: ["flock.nodeList", "autoInit"], invokers: { /** * Inserts a unit generator and all its inputs into the node list, * starting at the specified index. * * Note that the node itself will not be inserted into the list at this index; * its inputs must must be ahead of it in the list. * * @param {Number} idx the index to start adding the new node and its inputs at * @param {UGen} node the node to add, along with its inputs * @return {Number} the index at which the specified node was inserted */ insertTree: { funcName: "flock.ugenNodeList.insertTree", args: [ "{arguments}.0", // The index at whcih to add the new node. "{arguments}.1", // The node to add. "{that}.insert" ] }, /** * Removes the specified unit generator and all its inputs from the node list. * * @param {UGen} node the node to remove along with its inputs * @return {Number} the index at which the node was removed */ removeTree: { funcName: "flock.ugenNodeList.removeTree", args: [ "{arguments}.0", // The node to remove. "{that}.remove" ] }, /** * Replaces one node and all its inputs with a new node and its inputs. * * @param {UGen} newNode the node to add to the list * @param {UGen} oldNode the node to remove from the list * @return {Number} idx the index at which the new node was added */ //flock.ugenNodeList.replaceTree = function (newNode, oldNode, insertFn, removeFn) { replaceTree: { funcName: "flock.ugenNodeList.replaceTree", args: [ "{arguments}.0", // The node to add. "{arguments}.1", // The node to replace. "{that}.nodes", "{that}.insert", "{that}.remove" ] }, /** * Swaps one node in the list for another in place, attaching the previous unit generator's * inputs to the new one. If a list of inputsToReattach is specified, only these inputs will * be swapped. * * Note that this function will directly modify the nodes in question. * * @param {UGen} newNode the node to add to the list, swapping it in place for the old one * @param {UGen} oldNode the node remove from the list * @param {Array} inputsToReattach a list of inputNames to attach to the new node from the old one * @return the index at which the new node was inserted */ //flock.ugenNodeList.swapTree = function (newNode, oldNode, inputsToReattach, removeFn, replaceTreeFn, replaceFn) { swapTree: { funcName: "flock.ugenNodeList.swapTree", args: [ "{arguments}.0", // The node to add. "{arguments}.1", // The node to replace. "{arguments}.2", // A list of inputs to attach to the new node from the old. "{that}.remove", "{that}.replaceTree", "{that}.replace" ] } } }); flock.ugenNodeList.insertTree = function (idx, node, insertFn) { var inputs = node.inputs, key, input; for (key in inputs) { input = inputs[key]; if (flock.isUGen(input)) { idx = flock.ugenNodeList.insertTree(idx, input, insertFn); idx++; } } return insertFn(idx, node); }; flock.ugenNodeList.removeTree = function (node, removeFn) { var inputs = node.inputs, key, input; for (key in inputs) { input = inputs[key]; if (flock.isUGen(input)) { flock.ugenNodeList.removeTree(input, removeFn); } } return removeFn(node); }; flock.ugenNodeList.replaceTree = function (newNode, oldNode, nodes, insertFn, removeFn) { if (!oldNode) { // Can't use .tail() because it won't recursively add inputs. return flock.ugenNodeList.insertTree(nodes.length, newNode, insertFn); } var idx = flock.ugenNodeList.removeTree(oldNode, removeFn); flock.ugenNodeList.insertTree(idx, newNode, insertFn); return idx; }; flock.ugenNodeList.swapTree = function (newNode, oldNode, inputsToReattach, removeFn, replaceTreeFn, replaceFn) { if (!inputsToReattach) { newNode.inputs = oldNode.inputs; } else { flock.ugenNodeList.reattachInputs(newNode, oldNode, inputsToReattach, removeFn); flock.ugenNodeList.replaceInputs(newNode, oldNode, inputsToReattach, replaceTreeFn); } return replaceFn(newNode, oldNode); }; flock.ugenNodeList.reattachInputs = function (newNode, oldNode, inputsToReattach, removeFn) { for (var inputName in oldNode.inputs) { if (inputsToReattach.indexOf(inputName) < 0) { flock.ugenNodeList.removeTree(oldNode.inputs[inputName], removeFn); } else { newNode.inputs[inputName] = oldNode.inputs[inputName]; } } }; flock.ugenNodeList.replaceInputs = function (newNode, oldNode, inputsToReattach, replaceTreeFn) { for (var inputName in newNode.inputs) { if (inputsToReattach.indexOf(inputName) < 0) { replaceTreeFn( newNode.inputs[inputName], oldNode.inputs[inputName] ); } } }; /** * Synths represent a collection of signal-generating units, * wired together to form an instrument. * They are created with a synthDef object, which is a declarative structure * that describes the synth's unit generator graph. */ fluid.defaults("flock.synth", { gradeNames: ["flock.node", "flock.ugenNodeList", "autoInit"], addToEnvironment: "tail", rate: flock.rates.AUDIO, members: { rate: "{that}.options.rate", audioSettings: "{enviro}.audioSystem.model", // TODO: Move this. out: { expander: { funcName: "flock.synth.parseSynthDef", args: [ "{that}.options.synthDef", "{that}.rate", "{enviro}.audioSystem.model", "{that}.enviro.buffers", "{that}.enviro.busManager.buses", "{that}.tail" ] } }, genFn: "@expand:fluid.getGlobalValue({that}.options.invokers.gen.funcName)" }, components: { enviro: "{environment}" }, model: { blockSize: "@expand:flock.synth.calcBlockSize({that}.rate, {enviro}.audioSystem.model)" }, invokers: { /** * Plays the synth. This is a convenience method that will add the synth to the tail of the * environment's node graph and then play the environmnent. * * @param {Number} dur optional duration to play this synth in seconds */ play: { funcName: "flock.synth.play", args: ["{that}", "{that}.enviro", "{that}.addToEnvironment"] }, /** * Stops the synth if it is currently playing. * This is a convenience method that will remove the synth from the environment's node graph. */ pause: { funcName: "flock.synth.pause", args: ["{that}", "{that}.enviro"] }, /** * Sets the value of the ugen at the specified path. * * @param {String} path the ugen's path within the synth graph * @param {Number || UGenDef} val a scalar value (for Value ugens) or a UGenDef object * @param {Boolean} swap ?? * @return {UGen} the newly created UGen that was set at the specified path */ set: { funcName: "flock.synth.set", args: ["{that}", "{that}.namedNodes", "{arguments}.0", "{arguments}.1", "{arguments}.2"] }, /** * Gets the value of the ugen at the specified path. * * @param {String} path the ugen's path within the synth graph * @return {Number|UGen} a scalar value in the case of a value ugen, otherwise the ugen itself */ get: { funcName: "flock.input.get", args: ["{that}.namedNodes", "{arguments}.0"] }, /** * Deprecated. * * Gets or sets the value of a ugen at the specified path * * @param {String} path the ugen's path within the synth graph * @param {Number || UGenDef || Array} val an optional value to to set--a scalar value, a UGenDef object, or an array of UGenDefs * @param {Boolean || Object} swap specifies if the existing inputs should be swapped onto the new value * @return {Number || UGenDef || Array} the value that was set or retrieved */ input: { funcName: "flock.synth.input", args: [ "{arguments}", "{that}.get", "{that}.set" ] }, /** * Generates one block of audio rate signal by evaluating this synth's unit generator graph. */ gen: { funcName: "flock.synth.gen", args: "{that}" }, /** * Adds the synth to its environment's list of active nodes. * * @param {String || Boolean || Number} position the place to insert the node at; * if undefined, the synth's addToEnvironment option will be used. */ addToEnvironment: { funcName: "flock.synth.addToEnvironment", args: ["{that}", "{arguments}.0", "{that}.options", "{that}.enviro"] } }, listeners: { onCreate: { funcName: "flock.synth.addToEnvironment", args: ["{that}", undefined, "{that}.options", "{that}.enviro"] }, onDestroy: { "func": "{that}.pause" } } }); flock.synth.calcBlockSize = function (rate, audioSettings) { return rate === flock.rates.AUDIO ? audioSettings.blockSize : 1; }; flock.synth.parseSynthDef = function (synthDef, rate, audioSettings, buffers, buses, tailFn) { if (!synthDef) { fluid.log(fluid.logLevel.IMPORTANT, "Warning: Instantiating a flock.synth instance with an empty synth def."); } // At demand or schedule rates, override the rate of all non-constant ugens. var overrideRate = rate === flock.rates.SCHEDULED || rate === flock.rates.DEMAND; // Parse the synthDef into a graph of unit generators. return flock.parse.synthDef(synthDef, { rate: rate, overrideRate: overrideRate, visitors: tailFn, buffers: buffers, buses: buses, audioSettings: audioSettings }); }; flock.synth.play = function (synth, enviro, addToEnviroFn) { if (enviro.nodes.indexOf(synth) === -1) { var position = synth.options.addToEnvironment || "tail"; addToEnviroFn(position); } // TODO: This behaviour is confusing // since calling mySynth.play() will cause // all synths in the environment to be played. // This functionality should be removed. if (!enviro.model.isPlaying) { enviro.play(); } }; flock.synth.pause = function (synth, enviro) { enviro.remove(synth); }; flock.synth.set = function (that, namedNodes, path, val, swap) { return flock.input.set(namedNodes, path, val, undefined, function (ugenDef, path, target, prev) { return flock.synth.ugenValueParser(that, ugenDef, prev, swap); }); }; flock.synth.gen = function (that) { var nodes = that.nodes, m = that.model, i, node; for (i = 0; i < nodes.length; i++) { node = nodes[i]; if (node.gen !== undefined) { node.gen(node.model.blockSize); // TODO: De-thatify. } m.value = node.model.value; } }; flock.synth.input = function (args, getFn, setFn) { //path, val, swap var path = args[0]; return !path ? undefined : typeof path === "string" ? args.length < 2 ? getFn(path) : setFn.apply(null, args) : flock.isIterable(path) ? getFn(path) : setFn.apply(null, args); }; flock.synth.addToEnvironment = function (synth, position, options, enviro) { if (position === undefined) { position = options.addToEnvironment; } // Add this synth to the tail of the synthesis environment if appropriate. if (position === undefined || position === null || position === false) { return; } var type = typeof (position); if (type === "string" && position === "head" || position === "tail") { enviro[position](synth); } else if (type === "number") { enviro.insert(position, synth); } else { enviro.tail(synth); } }; // TODO: Reduce all these dependencies on "that" (i.e. a synth instance). flock.synth.ugenValueParser = function (that, ugenDef, prev, swap) { if (ugenDef === null || ugenDef === undefined) { return prev; } var parsed = flock.parse.ugenDef(ugenDef, { audioSettings: that.audioSettings, buses: that.enviro.buses, buffers: that.enviro.buffers }); var newUGens = flock.isIterable(parsed) ? parsed : (parsed !== undefined ? [parsed] : []), oldUGens = flock.isIterable(prev) ? prev : (prev !== undefined ? [prev] : []); var replaceLen = Math.min(newUGens.length, oldUGens.length), replaceFn = swap ? that.swapTree : that.replaceTree, i, atIdx, j; // TODO: Improve performance by handling arrays inline instead of repeated function calls. for (i = 0; i < replaceLen; i++) { atIdx = replaceFn(newUGens[i], oldUGens[i]); } for (j = i; j < newUGens.length; j++) { atIdx++; that.insertTree(atIdx, newUGens[j]); } for (j = i; j < oldUGens.length; j++) { that.removeTree(oldUGens[j]); } return parsed; }; fluid.defaults("flock.synth.value", { gradeNames: ["flock.synth", "autoInit"], rate: "demand", addToEnvironment: false, invokers: { value: { funcName: "flock.synth.value.genValue", args: ["{that}.model", "{that}.gen"] } } }); flock.synth.value.genValue = function (m, genFn) { genFn(1); return m.value; }; fluid.defaults("flock.synth.frameRate", { gradeNames: ["flock.synth.value", "autoInit"], rate: "scheduled", fps: 60, audioSettings: { rates: { scheduled: "{that}.options.fps" } } }); // TODO: At the moment, flock.synth.group attempts to act as a proxy for // a collection of synths, allowing users to address it as if it were // a single synth. However, it does nothing to ensure that its contained synths // are managed properly with the environment. There's currently no way to ensure that // when a group is removed from the environment, all its synths are too. // This should be completely refactored in favour of an approach using dynamic components. fluid.defaults("flock.synth.group", { gradeNames: ["flock.synth", "autoInit"], members: { out: null, }, methodEventMap: { "onSet": "set", "onGen": "gen", "onPlay": "play", "onPause": "pause" }, invokers: { play: "{that}.events.onPlay.fire", pause: "{that}.events.onPause.fire", set: "{that}.events.onSet.fire", get: "flock.synth.group.get({arguments}, {that}.nodes)", input: { funcName: "flock.synth.group.input", args: ["{arguments}", "{that}.get", "{that}.events.onSet.fire"] }, gen: { funcName: "flock.synth.group.gen", args: "{that}" } }, events: { onSet: null, onGen: null, onPlay: null, onPause: null }, listeners: { onInsert: [ { funcName: "flock.synth.group.bindMethods", args: [ "{arguments}.0", // The newly added node. "{that}.options.methodEventMap", "{that}.events", "addListener" ] }, // Brute force and unreliable way of ensuring that // children of a group don't get directly added to the environment. { funcName: "flock.synth.pause", args: ["{arguments}.0", "{that}.enviro"] } ], onRemove: { funcName: "flock.synth.group.bindMethods", args: [ "{arguments}.0", // The removed node. "{that}.options.methodEventMap", "{that}.events", "removeListener" ] } } }); flock.synth.group.gen = function (that) { flock.nodeEvaluator.gen(that.nodes); }; flock.synth.group.get = function (args, nodes) { var tailIdx = nodes.length - 1, tailNode = nodes[tailIdx]; return tailNode.get.apply(tailNode, args); }; flock.synth.group.input = function (args, onGet, onSet) { var evt = args.length > 1 ? onSet : onGet; return evt.apply(null, args); }; flock.synth.group.bindMethods = function (node, methodEventMap, events, eventActionName) { for (var eventName in methodEventMap) { var methodName = methodEventMap[eventName], method = node[methodName], firer = events[eventName], eventAction = firer[eventActionName]; eventAction(method); } }; fluid.defaults("flock.synth.polyphonic", { gradeNames: ["flock.synth.group", "autoInit"], maxVoices: 16, amplitudeNormalizer: "static", // "dynamic", "static", Function, falsey amplitudeKey: "env.sustain", noteSpecs: { on: { "env.gate": 1 }, off: { "env.gate": 0 } }, components: { voiceAllocator: { type: "flock.synth.voiceAllocator.lazy", options: { // TODO: Replace these with distributeOptions. synthDef: "{polyphonic}.options.synthDef", maxVoices: "{polyphonic}.options.maxVoices", amplitudeNormalizer: "{polyphonic}.options.amplitudeNormalizer", amplitudeKey: "{polyphonic}.options.amplitudeKey", listeners: { onCreateVoice: "{polyphonic}.tail({arguments}.0)" } } } }, invokers: { noteChange: { funcName: "flock.synth.polyphonic.noteChange", args: [ "{arguments}.0", // The voice synth to change. "{arguments}.1", // The note event name (i.e. "on" or "off"). "{arguments}.2", // The note change spec to apply. "{that}.options.noteSpecs" ] }, noteOn: { funcName: "flock.synth.polyphonic.noteOn", args: [ "{arguments}.0", // Note name. "{arguments}.1", // Optional changeSpec "{voiceAllocator}", "{that}.noteOff", "{that}.noteChange" ] }, noteOff: { funcName: "flock.synth.polyphonic.noteOff", args: [ "{arguments}.0", // Note name. "{arguments}.1", // Optional changeSpec "{voiceAllocator}", "{that}.noteChange" ] }, createVoice: { funcName: "flock.synth.polyphonic.createVoice", args: ["{that}.options", "{that}.insert"] } } }); flock.synth.polyphonic.noteChange = function (voice, eventName, changeSpec, noteSpecs) { var noteEventSpec = noteSpecs[eventName]; changeSpec = $.extend({}, noteEventSpec, changeSpec); voice.input(changeSpec); }; flock.synth.polyphonic.noteOn = function (noteName, changeSpec, voiceAllocator, noteOff, noteChange) { var voice = voiceAllocator.getFreeVoice(); if (voiceAllocator.activeVoices[noteName]) { noteOff(noteName); } voiceAllocator.activeVoices[noteName] = voice; noteChange(voice, "on", changeSpec); return voice; }; flock.synth.polyphonic.noteOff = function (noteName, changeSpec, voiceAllocator, noteChange) { var voice = voiceAllocator.activeVoices[noteName]; if (!voice) { return null; } noteChange(voice, "off", changeSpec); delete voiceAllocator.activeVoices[noteName]; voiceAllocator.freeVoices.push(voice); return voice; }; fluid.defaults("flock.synth.voiceAllocator", { gradeNames: ["fluid.standardComponent", "autoInit"], maxVoices: 16, amplitudeNormalizer: "static", // "dynamic", "static", Function, falsey amplitudeKey: "env.sustain", members: { activeVoices: {}, freeVoices: [] }, invokers: { createVoice: { funcName: "flock.synth.voiceAllocator.createVoice", args: ["{that}.options", "{that}.events.onCreateVoice.fire"] } }, events: { onCreateVoice: null } }); flock.synth.voiceAllocator.createVoice = function (options, onCreateVoice) { var voice = flock.synth({ synthDef: options.synthDef, addToEnvironment: false }); var normalizer = options.amplitudeNormalizer, ampKey = options.amplitudeKey, normValue; if (normalizer) { if (typeof normalizer === "function") { normalizer(voice, ampKey); } else if (normalizer === "static") { normValue = 1.0 / options.maxVoices; voice.input(ampKey, normValue); } // TODO: Implement dynamic voice normalization. } onCreateVoice(voice); return voice; }; fluid.defaults("flock.synth.voiceAllocator.lazy", { gradeNames: ["flock.synth.voiceAllocator", "autoInit"], invokers: { getFreeVoice: { funcName: "flock.synth.voiceAllocator.lazy.get", args: [ "{that}.freeVoices", "{that}.activeVoices", "{that}.createVoice", "{that}.options.maxVoices" ] } } }); flock.synth.voiceAllocator.lazy.get = function (freeVoices, activeVoices, createVoiceFn, maxVoices) { return freeVoices.length > 1 ? freeVoices.pop() : Object.keys(activeVoices).length > maxVoices ? null : createVoiceFn(); }; fluid.defaults("flock.synth.voiceAllocator.pool", { gradeNames: ["flock.synth.voiceAllocator", "autoInit"], invokers: { getFreeVoice: "flock.synth.voiceAllocator.pool.get({that}.freeVoices)" } }); flock.synth.voiceAllocator.pool.get = function (freeVoices) { if (freeVoices.length > 0) { return freeVoices.pop(); } }; flock.synth.voiceAllocator.pool.allocateVoices = function (freeVoices, createVoiceFn, maxVoices) { for (var i = 0; i < maxVoices; i++) { freeVoices[i] = createVoiceFn(); } }; /** * flock.band provides an IoC-friendly interface for a collection of named synths. */ // TODO: Unit tests. fluid.defaults("flock.band", { gradeNames: ["fluid.eventedComponent", "autoInit"], invokers: { play: { func: "{that}.events.onPlay.fire" }, pause: { func: "{that}.events.onPause.fire" }, set: { func: "{that}.events.onSet.fire" } }, events: { onPlay: null, onPause: null, onSet: null }, distributeOptions: [ { source: "{that}.options.childListeners", removeSource: true, target: "{that fluid.eventedComponent}.options.listeners" }, { source: "{that}.options.synthListeners", removeSource: true, target: "{that flock.synth}.options.listeners" } ], childListeners: { "{band}.events.onDestroy": { func: "{that}.destroy" } }, synthListeners: { "{band}.events.onPlay": { func: "{that}.play" }, "{band}.events.onPause": { func: "{that}.pause" }, "{band}.events.onSet": { func: "{that}.set" } } }); /******************************* * Error Handling Conveniences * *******************************/ flock.bufferDesc = function () { throw new Error("flock.bufferDesc is not defined. Did you forget to include the flocking-buffers.js file?"); }; }()); ;/* * Flocking Audio Buffers * http://github.com/colinbdclark/flocking * * Copyright 2013-14, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, AudioBuffer*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; // Based on Brian Cavalier and John Hann's Tiny Promises library. // https://github.com/unscriptable/promises/blob/master/src/Tiny2.js function Promise() { var resolve = function (result) { complete("resolve", result); promise.state = "fulfilled"; }; var reject = function (err) { complete("reject", err); promise.state = "rejected"; }; var then = function (resolve, reject) { if (callbacks) { callbacks.push({ resolve: resolve, reject: reject }); } else { var fn = promise.state === "fulfilled" ? resolve : reject; fn(promise.value); } return this; }; var callbacks = [], promise = { state: "pending", value: undefined, resolve: resolve, reject: reject, then: then, safe: { then: function safeThen(resolve, reject) { promise.then(resolve, reject); return this; } } }; function complete(type, result) { var rejector = function (resolve, reject) { reject(result); return this; }; var resolver = function (resolve) { resolve(result); return this; }; promise.value = result; promise.then = type === "reject" ? rejector : resolver; promise.resolve = promise.reject = function () { throw new Error("Promise already completed"); }; invokeCallbacks(type, result); } function invokeCallbacks (type, result) { var i, cb; for (i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb[type]) { cb[type](result); } } callbacks = null; } return promise; } fluid.defaults("flock.promise", { gradeNames: ["fluid.eventedComponent", "autoInit"], members: { promise: { expander: { funcName: "flock.promise.make" } } } }); flock.promise.make = function () { return new Promise(); }; // TODO: This is actually part of the interpreter's expansion process // and should be clearly named as such. flock.bufferDesc = function (data, sampleRate, numChannels) { var fn = flock.platform.isWebAudio && data instanceof AudioBuffer ? flock.bufferDesc.fromAudioBuffer : flock.isIterable(data) ? flock.bufferDesc.fromChannelArray : flock.bufferDesc.expand; return fn(data, sampleRate, numChannels); }; flock.bufferDesc.inferFormat = function (bufDesc, sampleRate, numChannels) { var format = bufDesc.format, data = bufDesc.data; format.sampleRate = sampleRate || format.sampleRate || 44100; format.numChannels = numChannels || format.numChannels || bufDesc.data.channels.length; format.numSampleFrames = format.numSampleFrames || data.channels.length > 0 ? data.channels[0].length : 0; format.duration = format.numSampleFrames / format.sampleRate; return bufDesc; }; flock.bufferDesc.fromChannelArray = function (arr, sampleRate, numChannels) { if (arr instanceof Float32Array) { arr = [arr]; } var bufDesc = { container: {}, format: { numChannels: numChannels, sampleRate: sampleRate, numSampleFrames: arr[0].length }, data: { channels: arr } }; return flock.bufferDesc.inferFormat(bufDesc, sampleRate, numChannels); }; flock.bufferDesc.expand = function (bufDesc, sampleRate, numChannels) { bufDesc = bufDesc || { data: { channels: [] } }; bufDesc.container = bufDesc.container || {}; bufDesc.format = bufDesc.format || {}; bufDesc.format.numChannels = numChannels || bufDesc.format.numChannels || bufDesc.data.channels.length; // TODO: Duplication with inferFormat. if (bufDesc.data && bufDesc.data.channels) { // Special case for an unwrapped single-channel array. if (bufDesc.format.numChannels === 1 && bufDesc.data.channels.length !== 1) { bufDesc.data.channels = [bufDesc.data.channels]; } if (bufDesc.format.numChannels !== bufDesc.data.channels.length) { throw new Error("The specified number of channels does not match " + "the actual channel data. " + "numChannels was: " + bufDesc.format.numChannels + " but the sample data contains " + bufDesc.data.channels.length + " channels."); } } return flock.bufferDesc.inferFormat(bufDesc, sampleRate, numChannels); }; flock.bufferDesc.fromAudioBuffer = function (audioBuffer) { var desc = { container: {}, format: { sampleRate: audioBuffer.sampleRate, numChannels: audioBuffer.numberOfChannels, numSampleFrames: audioBuffer.length, duration: audioBuffer.duration }, data: { channels: [] } }, i; for (i = 0; i < audioBuffer.numberOfChannels; i++) { desc.data.channels.push(audioBuffer.getChannelData(i)); } return desc; }; /** * Represents a source for fetching buffers. */ fluid.defaults("flock.bufferSource", { gradeNames: ["fluid.standardComponent", "autoInit"], model: { state: "start", src: null }, components: { bufferPromise: { createOnEvent: "onRefreshPromise", type: "flock.promise", options: { listeners: { onCreate: { "this": "{that}.promise", method: "then", args: ["{bufferSource}.events.afterFetch.fire", "{bufferSource}.events.onError.fire"] } } } } }, invokers: { get: { funcName: "flock.bufferSource.get", args: ["{that}", "{arguments}.0"] }, set: { funcName: "flock.bufferSource.set", args: ["{that}", "{arguments}.0"] }, error: { funcName: "flock.bufferSource.error", args: ["{that}", "{arguments}.0"] } }, listeners: { onCreate: { funcName: "{that}.events.onRefreshPromise.fire" }, onRefreshPromise: { funcName: "{that}.applier.requestChange", args: ["state", "start"] }, onFetch: { funcName: "{that}.applier.requestChange", args: ["state", "in-progress"] }, afterFetch: [ { funcName: "{that}.applier.requestChange", args: ["state", "fetched"] }, { funcName: "{that}.events.onBufferUpdated.fire", // TODO: Replace with boiling? args: ["{arguments}.0"] } ], onBufferUpdated: "{environment}.registerBuffer({arguments}.0)", onError: { funcName: "{that}.applier.requestChange", args: ["state", "error"] } }, events: { onRefreshPromise: null, onError: null, onFetch: null, afterFetch: null, onBufferUpdated: null } }); flock.bufferSource.get = function (that, bufDef) { if (that.model.state === "in-progress" || (bufDef.src === that.model.src && !bufDef.replace)) { // We've already fetched the buffer or are in the process of doing so. return that.bufferPromise.promise; } if (bufDef.src) { if ((that.model.state === "fetched" || that.model.state === "errored") && (that.model.src !== bufDef.src || bufDef.replace)) { that.events.onRefreshPromise.fire(); } if (that.model.state === "start") { that.model.src = bufDef.src; that.events.onFetch.fire(bufDef); flock.audio.decode({ src: bufDef.src, success: function (bufDesc) { if (bufDef.id) { bufDesc.id = bufDef.id; } that.set(bufDesc); }, error: that.error }); } } return that.bufferPromise.promise; }; flock.bufferSource.set = function (that, bufDesc) { var state = that.model.state; if (state === "start" || state === "in-progress") { that.bufferPromise.promise.resolve(bufDesc); } return that.bufferPromise.promise; }; flock.bufferSource.error = function (that, msg) { that.bufferPromise.promise.reject(msg); return that.bufferPromise.promise; }; /** * A Buffer Loader is responsible for loading a collection * of buffers asynchronously, and will fire an event when they * are all ready. */ fluid.defaults("flock.bufferLoader", { gradeNames: ["fluid.eventedComponent", "autoInit"], members: { buffers: [] }, // A list of BufferDef objects to resolve. bufferDefs: [], events: { afterBuffersLoaded: null }, listeners: { onCreate: { funcName: "flock.bufferLoader.loadBuffers", args: ["{that}.options.bufferDefs", "{that}.buffers", "{that}.events.afterBuffersLoaded.fire"] } } }); flock.bufferLoader.idFromURL = function (url) { var lastSlash = url.lastIndexOf("/"), idStart = lastSlash > -1 ? lastSlash + 1 : 0, ext = url.lastIndexOf("."), idEnd = ext > -1 ? ext : url.length; return url.substring(idStart, idEnd); }; flock.bufferLoader.idsFromURLs = function (urls) { return fluid.transform(urls, flock.bufferLoader.idFromURL); }; flock.bufferLoader.expandFileSequence = function (fileURLs) { fileURLs = fileURLs || []; var bufDefs = [], i, url, id; for (i = 0; i < fileURLs.length; i++) { url = fileURLs[i]; id = flock.bufferLoader.idFromURL(url); bufDefs.push({ id: id, url: url }); } return bufDefs; }; flock.bufferLoader.loadBuffers = function (bufferDefs, decodedBuffers, afterBuffersLoaded) { bufferDefs = fluid.makeArray(bufferDefs); // TODO: This is a sign that flock.parse.bufferForDef is still terribly broken. var bufferTarget = { setBuffer: function (decoded) { decodedBuffers.push(decoded); if (decodedBuffers.length === bufferDefs.length) { afterBuffersLoaded(decodedBuffers); } } }; for (var i = 0; i < bufferDefs.length; i++) { var bufDef = bufferDefs[i]; if (bufDef.id === undefined && bufDef.url !== undefined) { bufDef.id = flock.bufferLoader.idFromURL(bufDef.url); } // TODO: Hardcoded reference to the shared environment. flock.parse.bufferForDef(bufferDefs[i], bufferTarget, flock.environment); } }; }()); ;/* * Flocking Parser * http://github.com/colinbdclark/flocking * * Copyright 2011-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, Float32Array*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; var $ = fluid.registerNamespace("jQuery"); fluid.registerNamespace("flock.parse"); flock.parse.synthDef = function (ugenDef, options) { if (!ugenDef) { ugenDef = []; } if (!flock.parse.synthDef.hasOutUGen(ugenDef)) { // We didn't get an out ugen specified, so we need to make one. ugenDef = flock.parse.synthDef.makeOutUGen(ugenDef, options); } return flock.parse.ugenForDef(ugenDef, options); }; flock.parse.synthDef.hasOutUGen = function (synthDef) { // TODO: This is hostile to third-party extension. return !flock.isIterable(synthDef) && ( synthDef.id === flock.OUT_UGEN_ID || synthDef.ugen === "flock.ugen.out" || synthDef.ugen === "flock.ugen.valueOut" ); }; flock.parse.synthDef.makeOutUGen = function (ugenDef, options) { ugenDef = { id: flock.OUT_UGEN_ID, ugen: "flock.ugen.valueOut", inputs: { sources: ugenDef } }; if (options.rate === flock.rates.AUDIO) { ugenDef.ugen = "flock.ugen.out"; ugenDef.inputs.bus = 0; ugenDef.inputs.expand = options.audioSettings.chans; } return ugenDef; }; flock.parse.makeUGen = function (ugenDef, parsedInputs, options) { var rates = options.audioSettings.rates, blockSize = options.audioSettings.blockSize; // Assume audio rate if no rate was specified by the user. if (!ugenDef.rate) { ugenDef.rate = flock.rates.AUDIO; } var sampleRate; // Set the ugen's sample rate value according to the rate the user specified. if (ugenDef.options && ugenDef.options.sampleRate !== undefined) { sampleRate = ugenDef.options.sampleRate; } else { sampleRate = rates[ugenDef.rate]; } // TODO: Infusion options merging! ugenDef.options = $.extend(true, {}, ugenDef.options, { sampleRate: sampleRate, rate: ugenDef.rate, audioSettings: { rates: rates, blockSize: blockSize } }); // TODO: When we switch to Infusion options merging, these should have a mergePolicy of preserve. ugenDef.options.buffers = options.buffers; ugenDef.options.buses = options.buses; var outputBufferSize = ugenDef.rate === flock.rates.AUDIO ? blockSize : 1, outputBuffers; if (flock.hasTag(ugenDef.options, "flock.ugen.multiChannelOutput")) { var numOutputs = ugenDef.options.numOutputs || 1; outputBuffers = []; for (var i = 0; i < numOutputs; i++) { outputBuffers.push(new Float32Array(outputBufferSize)); } } else { outputBuffers = new Float32Array(outputBufferSize); } return flock.invoke(undefined, ugenDef.ugen, [ parsedInputs, outputBuffers, ugenDef.options ]); }; flock.parse.reservedWords = ["id", "ugen", "rate", "inputs", "options"]; flock.parse.specialInputs = ["value", "buffer", "list", "table", "envelope", "durations", "values"]; flock.parse.expandInputs = function (ugenDef) { if (ugenDef.inputs) { return ugenDef; } var inputs = {}, prop; // Copy any non-reserved properties from the top-level ugenDef object into the inputs property. for (prop in ugenDef) { if (flock.parse.reservedWords.indexOf(prop) === -1) { inputs[prop] = ugenDef[prop]; delete ugenDef[prop]; } } ugenDef.inputs = inputs; return ugenDef; }; flock.parse.ugenDefForConstantValue = function (value) { return { ugen: "flock.ugen.value", rate: flock.rates.CONSTANT, inputs: { value: value } }; }; flock.parse.expandValueDef = function (ugenDef) { var type = typeof (ugenDef); if (type === "number") { return flock.parse.ugenDefForConstantValue(ugenDef); } if (type === "object") { return ugenDef; } throw new Error("Invalid value type found in ugen definition. UGenDef was: " + fluid.prettyPrintJSON(ugenDef)); }; flock.parse.rateMap = { "ar": flock.rates.AUDIO, "kr": flock.rates.CONTROL, "sr": flock.rates.SCHEDULED, "dr": flock.rates.DEMAND, "cr": flock.rates.CONSTANT }; flock.parse.expandRate = function (ugenDef, options) { ugenDef.rate = flock.parse.rateMap[ugenDef.rate] || ugenDef.rate; if (options.overrideRate && ugenDef.rate !== flock.rates.CONSTANT) { ugenDef.rate = options.rate; } return ugenDef; }; flock.parse.ugenDef = function (ugenDefs, options) { var parseFn = flock.isIterable(ugenDefs) ? flock.parse.ugensForDefs : flock.parse.ugenForDef; var parsed = parseFn(ugenDefs, options); return parsed; }; flock.parse.ugenDef.mergeOptions = function (ugenDef) { // TODO: Infusion options merging. var defaults = fluid.defaults(ugenDef.ugen) || {}; // TODO: Insane! defaults = fluid.copy(defaults); defaults.options = defaults.ugenOptions; delete defaults.ugenOptions; // return $.extend(true, {}, defaults, ugenDef); }; flock.parse.ugensForDefs = function (ugenDefs, options) { var parsed = [], i; for (i = 0; i < ugenDefs.length; i++) { parsed[i] = flock.parse.ugenForDef(ugenDefs[i], options); } return parsed; }; /** * Creates a unit generator for the specified unit generator definition spec. * * ugenDefs are plain old JSON objects describing the characteristics of the desired unit generator, including: * - ugen: the type of unit generator, as string (e.g. "flock.ugen.sinOsc") * - rate: the rate at which the ugen should be run, either "audio", "control", or "constant" * - id: an optional unique name for the unit generator, which will make it available as a synth input * - inputs: a JSON object containing named key/value pairs for inputs to the unit generator * OR * - inputs keyed by name at the top level of the ugenDef * * @param {UGenDef} ugenDef the unit generator definition to parse * @param {Object} options an options object containing: * {Object} audioSettings the environment's audio settings * {Array} buses the environment's global buses * {Array} buffers the environment's global buffers * {Array of Functions} visitors an optional list of visitor functions to invoke when the ugen has been created * @return the parsed unit generator object */ flock.parse.ugenForDef = function (ugenDef, options) { options = $.extend(true, { audioSettings: flock.environment.audioSystem.model, buses: flock.environment.busManager.buses, buffers: flock.environment.buffers }, options); var o = options, visitors = o.visitors, rates = o.audioSettings.rates; // If we receive a plain scalar value, expand it into a value ugenDef. ugenDef = flock.parse.expandValueDef(ugenDef); // We received an array of ugen defs. if (flock.isIterable(ugenDef)) { return flock.parse.ugensForDefs(ugenDef, options); } ugenDef = flock.parse.expandInputs(ugenDef); flock.parse.expandRate(ugenDef, options); ugenDef = flock.parse.ugenDef.mergeOptions(ugenDef, options); var inputDefs = ugenDef.inputs, inputs = {}, inputDef; // TODO: This notion of "special inputs" should be refactored as a pluggable system of // "input expanders" that are responsible for processing input definitions of various sorts. // In particular, buffer management should be here so that we can initialize bufferDefs more // proactively and remove this behaviour from flock.ugen.buffer. for (inputDef in inputDefs) { var inputDefVal = inputDefs[inputDef]; if (inputDefVal === null) { continue; // Skip null inputs. } // Create ugens for all inputs except special inputs. inputs[inputDef] = flock.input.shouldExpand(inputDef, ugenDef) ? flock.parse.ugenForDef(inputDefVal, options) : // Parse the ugendef and create a ugen instance. inputDefVal; // Don't instantiate a ugen, just pass the def on as-is. } if (!ugenDef.ugen) { throw new Error("Unit generator definition lacks a 'ugen' property; " + "can't initialize the synth graph. Value: " + fluid.prettyPrintJSON(ugenDef)); } var ugen = flock.parse.makeUGen(ugenDef, inputs, options); if (ugenDef.id) { ugen.id = ugenDef.id; ugen.nickName = ugenDef.id; // TODO: Normalize nicknames and ids. } ugen.options.ugenDef = ugenDef; if (visitors) { visitors = fluid.makeArray(visitors); fluid.each(visitors, function (visitor) { visitor(ugen, ugenDef, rates); }); } return ugen; }; flock.parse.expandBufferDef = function (bufDef) { return typeof bufDef === "string" ? {id: bufDef} : (flock.isIterable(bufDef) || bufDef.data || bufDef.format) ? flock.bufferDesc(bufDef) : bufDef; }; flock.parse.bufferForDef = function (bufDef, ugen, enviro) { bufDef = flock.parse.expandBufferDef(bufDef); if (bufDef.data && bufDef.data.channels) { bufDef = flock.bufferDesc(bufDef); flock.parse.bufferForDef.resolveBuffer(bufDef, ugen, enviro); } else { flock.parse.bufferForDef.resolveDef(bufDef, ugen, enviro); } }; flock.parse.bufferForDef.findSource = function (defOrDesc, enviro) { var source; if (enviro && defOrDesc.id) { source = enviro.bufferSources[defOrDesc.id]; if (!source) { source = enviro.bufferSources[defOrDesc.id] = flock.bufferSource(); } } else { source = flock.bufferSource(); } return source; }; flock.parse.bufferForDef.bindToPromise = function (p, source, ugen) { // TODO: refactor this. var success = function (bufDesc) { source.events.onBufferUpdated.addListener(success); if (ugen) { ugen.setBuffer(bufDesc); } }; var error = function (msg) { if (!msg && source.model.src && source.model.src.indexOf(".aif")) { msg = "if this is an AIFF file, you might need to include" + " flocking-audiofile-compatibility.js in some browsers."; } throw new Error("Error while resolving buffer " + source.model.src + ": " + msg); }; p.then(success, error); }; flock.parse.bufferForDef.resolveDef = function (bufDef, ugen, enviro) { var source = flock.parse.bufferForDef.findSource(bufDef, enviro), p; bufDef.src = bufDef.url || bufDef.src; if (bufDef.selector && typeof(document) !== "undefined") { bufDef.src = document.querySelector(bufDef.selector).files[0]; } p = source.get(bufDef); flock.parse.bufferForDef.bindToPromise(p, source, ugen); }; flock.parse.bufferForDef.resolveBuffer = function (bufDesc, ugen, enviro) { var source = flock.parse.bufferForDef.findSource(bufDesc, enviro), p = source.set(bufDesc); flock.parse.bufferForDef.bindToPromise(p, source, ugen); }; }()); ;/* * Flocking Audio File Utilities * http://github.com/colinbdclark/flocking * * Copyright 2011-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, ArrayBuffer, Uint8Array, File, FileReader */ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; /** * Applies the specified function in the next round of the event loop. */ // TODO: Replace this and the code that depends on it with a good Promise implementation. flock.applyDeferred = function (fn, args, delay) { if (!fn) { return; } delay = typeof (delay) === "undefined" ? 0 : delay; setTimeout(function () { fn.apply(null, args); }, delay); }; /********************* * Network utilities * *********************/ fluid.registerNamespace("flock.net"); /** * Loads an ArrayBuffer into memory using XMLHttpRequest. */ flock.net.readBufferFromUrl = function (options) { var src = options.src, xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { options.success(xhr.response, flock.file.parseFileExtension(src)); } else { if (!options.error) { throw new Error(xhr.statusText); } options.error(xhr.statusText); } } }; xhr.open(options.method || "GET", src, true); xhr.responseType = options.responseType || "arraybuffer"; xhr.send(options.data); }; /***************** * File Utilties * *****************/ fluid.registerNamespace("flock.file"); flock.file.mimeTypes = { "audio/wav": "wav", "audio/x-wav": "wav", "audio/wave": "wav", "audio/x-aiff": "aiff", "audio/aiff": "aiff", "sound/aiff": "aiff" }; flock.file.typeAliases = { "aif": "aiff", "wave": "wav" }; flock.file.parseFileExtension = function (fileName) { var lastDot = fileName.lastIndexOf("."), ext, alias; // TODO: Better error handling in cases where we've got unrecognized file extensions. // i.e. we should try to read the header instead of relying on extensions. if (lastDot < 0) { return undefined; } ext = fileName.substring(lastDot + 1); ext = ext.toLowerCase(); alias = flock.file.typeAliases[ext]; return alias || ext; }; flock.file.parseMIMEType = function (mimeType) { return flock.file.mimeTypes[mimeType]; }; /** * Converts a binary string to an ArrayBuffer, suitable for use with a DataView. * * @param {String} s the raw string to convert to an ArrayBuffer * * @return {Uint8Array} the converted buffer */ flock.file.stringToBuffer = function (s) { var len = s.length, b = new ArrayBuffer(len), v = new Uint8Array(b), i; for (i = 0; i < len; i++) { v[i] = s.charCodeAt(i); } return v.buffer; }; /** * Asynchronously parses the specified data URL into an ArrayBuffer. */ flock.file.readBufferFromDataUrl = function (options) { var url = options.src, delim = url.indexOf(","), header = url.substring(0, delim), data = url.substring(delim + 1), base64Idx = header.indexOf(";base64"), isBase64 = base64Idx > -1, mimeTypeStartIdx = url.indexOf("data:") + 5, mimeTypeEndIdx = isBase64 ? base64Idx : delim, mimeType = url.substring(mimeTypeStartIdx, mimeTypeEndIdx); if (isBase64) { data = atob(data); } flock.applyDeferred(function () { var buffer = flock.file.stringToBuffer(data); options.success(buffer, flock.file.parseMIMEType(mimeType)); }); }; /** * Asynchronously reads the specified File into an ArrayBuffer. */ flock.file.readBufferFromFile = function (options) { var reader = new FileReader(); reader.onload = function (e) { options.success(e.target.result, flock.file.parseFileExtension(options.src.name)); }; reader.readAsArrayBuffer(options.src); return reader; }; fluid.registerNamespace("flock.audio"); /** * Asychronously loads an ArrayBuffer into memory. * * Options: * - src: the URL to load the array buffer from * - method: the HTTP method to use (if applicable) * - data: the data to be sent as part of the request (it's your job to query string-ize this if it's an HTTP request) * - success: the success callback, which takes the ArrayBuffer response as its only argument * - error: a callback that will be invoked if an error occurs, which takes the error message as its only argument */ flock.audio.loadBuffer = function (options) { var src = options.src || options.url; if (!src) { return; } if (src instanceof ArrayBuffer) { flock.applyDeferred(options.success, [src, options.type]); } var reader = flock.audio.loadBuffer.readerForSource(src); reader(options); }; flock.audio.loadBuffer.readerForSource = function (src) { return (typeof (File) !== "undefined" && src instanceof File) ? flock.file.readBufferFromFile : src.indexOf("data:") === 0 ? flock.file.readBufferFromDataUrl : flock.net.readBufferFromUrl; }; /** * Loads and decodes an audio file. By default, this is done asynchronously in a Web Worker. * This decoder currently supports WAVE and AIFF file formats. */ flock.audio.decode = function (options) { var success = options.success; var wrappedSuccess = function (rawData, type) { var strategies = flock.audio.decoderStrategies, strategy = strategies[type] || strategies["default"]; if (options.decoder) { strategy = typeof (options.decoder) === "string" ? fluid.getGlobalValue(options.decoder) : options.decoder; } strategy({ rawData: rawData, type: type, success: success, error: options.error, sampleRate: options.sampleRate || (flock.environment ? flock.environment.audioSystem.model.rates.audio : undefined) }); }; options.success = wrappedSuccess; flock.audio.loadBuffer(options); }; /** * Asynchronously decodes the specified ArrayBuffer rawData using * the browser's Web Audio Context. */ flock.audio.decode.webAudio = function (o) { var ctx = flock.environment.audioSystem.context, success = function (audioBuffer) { var bufDesc = flock.bufferDesc.fromAudioBuffer(audioBuffer); o.success(bufDesc); }; ctx.decodeAudioData(o.rawData, success, o.error); }; flock.audio.decoderStrategies = { "default": flock.audio.decode.webAudio }; flock.audio.registerDecoderStrategy = function (type, strategy) { if (!type) { return; } if (typeof type === "object") { for (var key in type) { flock.audio.decoderStrategies[key] = type[key]; } return; } if (typeof strategy === "string") { strategy = fluid.getGlobalValue(strategy); } flock.audio.decoderStrategies[type] = strategy; }; }()); ;/* * Flocking Audio Encoders * http://github.com/colinbdclark/flocking * * Copyright 2015, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, ArrayBuffer, Uint8Array */ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; fluid.registerNamespace("flock.audio.encode"); flock.audio.interleave = function (bufDesc) { var numFrames = bufDesc.format.numSampleFrames, chans = bufDesc.data.channels, numChans = bufDesc.format.numChannels, numSamps = numFrames * numChans, out = new Float32Array(numSamps), outIdx = 0, frame, chan; for (frame = 0; frame < numFrames; frame++) { for (chan = 0; chan < numChans; chan++) { out[outIdx] = chans[chan][frame]; outIdx++; } } return out; }; flock.audio.encode = function (bufDesc, type, format) { type = type || "wav"; if (type.toLowerCase() !== "wav") { flock.fail("Flocking currently only supports encoding WAVE files."); } return flock.audio.encode.wav(bufDesc, format); }; flock.audio.encode.writeFloat32Array = function (offset, dv, buf) { for (var i = 0; i < buf.length; i++) { dv.setFloat32(offset, buf[i], true); offset += 4; } return dv; }; flock.audio.encode.setString = function (dv, offset, str){ for (var i = 0; i < str.length; i++){ dv.setUint8(offset + i, str.charCodeAt(i)); } }; flock.audio.encode.setBytes = function (dv, offset, bytes) { for (var i = 0; i < bytes.length; i++) { dv.setUint8(offset + i, bytes[i]); } }; flock.audio.encode.writeAsPCM = function (formatSpec, offset, dv, buf) { if (formatSpec.setter === "setFloat32" && buf instanceof Float32Array) { return flock.audio.encode.writeFloat32Array(offset, dv, buf); } for (var i = 0; i < buf.length; i++) { // Clamp to within bounds. var s = Math.min(1.0, buf[i]); s = Math.max(-1.0, s); // Scale to the otuput number format. s = s < 0 ? s * formatSpec.scaleNeg : s * formatSpec.scalePos; // Write the sample to the DataView. dv[formatSpec.setter](offset, s, true); offset += formatSpec.width; } return dv; }; flock.audio.pcm = { int16: { scalePos: 32767, scaleNeg: 32768, setter: "setInt16", width: 2 }, int32: { scalePos: 2147483647, scaleNeg: 2147483648, setter: "setInt32", width: 4 }, float32: { scalePos: 1, scaleNeg: 1, setter: "setFloat32", width: 4 } }; flock.audio.encode.wav = function (bufDesc, format) { format = format || flock.audio.pcm.int16; var formatSpec = typeof format === "string" ? flock.audio.pcm[format] : format; if (!formatSpec) { flock.fail("Flocking does not support encoding " + format + " format PCM wave files."); } var interleaved = flock.audio.interleave(bufDesc), numChans = bufDesc.format.numChannels, sampleRate = bufDesc.format.sampleRate, isPCM = formatSpec.setter !== "setFloat32", riffHeaderSize = 8, formatHeaderSize = 12, formatBodySize = 16, formatTag = 1, dataHeaderSize = 8, dataBodySize = interleaved.length * formatSpec.width, dataChunkSize = dataHeaderSize + dataBodySize, bitsPerSample = 8 * formatSpec.width; if (numChans > 2 || !isPCM) { var factHeaderSize = 8, factBodySize = 4, factChunkSize = factHeaderSize + factBodySize; formatBodySize += factChunkSize; if (numChans > 2) { formatBodySize += 24; formatTag = 0xFFFE; // Extensible. } else { formatBodySize += 2; formatTag = 3; // Two-channel IEEE float. } } var formatChunkSize = formatHeaderSize + formatBodySize, riffBodySize = formatChunkSize + dataChunkSize, numBytes = riffHeaderSize + riffBodySize, out = new ArrayBuffer(numBytes), dv = new DataView(out); // RIFF chunk header. flock.audio.encode.setString(dv, 0, "RIFF"); // ckID dv.setUint32(4, riffBodySize, true); // cksize // Format Header flock.audio.encode.setString(dv, 8, "WAVE"); // WAVEID flock.audio.encode.setString(dv, 12, "fmt "); // ckID dv.setUint32(16, formatBodySize, true); // cksize, length of the format chunk. // Format Body dv.setUint16(20, formatTag, true); // wFormatTag dv.setUint16(22, numChans, true); // nChannels dv.setUint32(24, sampleRate, true); // nSamplesPerSec dv.setUint32(28, sampleRate * 4, true); // nAvgBytesPerSec (sample rate * block align) dv.setUint16(32, numChans * formatSpec.width, true); //nBlockAlign (channel count * bytes per sample) dv.setUint16(34, bitsPerSample, true); // wBitsPerSample var offset = 36; if (formatTag === 3) { // IEEE Float. Write out a fact chunk. dv.setUint16(offset, 0, true); // cbSize: size of the extension offset += 2; offset = flock.audio.encode.wav.writeFactChunk(dv, offset, bufDesc.format.numSampleFrames); } else if (formatTag === 0xFFFE) { // Extensible format (i.e. > 2 channels). // Write out additional format fields and fact chunk. dv.setUint16(offset, 22, true); // cbSize: size of the extension offset += 2; // Additional format fields. offset = flock.audio.encode.wav.additionalFormat(offset, dv, bitsPerSample, isPCM); // Fact chunk. offset = flock.audio.encode.wav.writeFactChunk(dv, offset, bufDesc.format.numSampleFrames); } flock.audio.encode.wav.writeDataChunk(formatSpec, offset, dv, interleaved, dataBodySize); return dv.buffer; }; flock.audio.encode.wav.subformats = { pcm: new Uint8Array([1, 0, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113]), float: new Uint8Array([3, 0, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113]) }; flock.audio.encode.wav.additionalFormat = function (offset, dv, bitsPerSample, isPCM) { dv.setUint16(offset, bitsPerSample, true); // wValidBitsPerSample offset += 2; dv.setUint32(offset, 0x80000000, true); // dwChannelMask, hardcoded to SPEAKER_RESERVED offset += 4; // Subformat GUID. var subformat = flock.audio.encode.wav.subformats[isPCM ? "pcm" : "float"]; flock.audio.encode.setBytes(dv, offset, subformat); offset += 16; return offset; }; flock.audio.encode.wav.writeFactChunk = function (dv, offset, numSampleFrames) { flock.audio.encode.setString(dv, offset, "fact"); // ckID offset += 4; dv.setUint32(offset, 4, true); //cksize offset += 4; dv.setUint32(offset, numSampleFrames, true); // dwSampleLength offset += 4; return offset; }; flock.audio.encode.wav.writeDataChunk = function (formatSpec, offset, dv, interleaved, numSampleBytes) { // Data chunk Header flock.audio.encode.setString(dv, offset, "data"); offset += 4; dv.setUint32(offset, numSampleBytes, true); // Length of the datahunk. offset += 4; flock.audio.encode.writeAsPCM(formatSpec, offset, dv, interleaved); }; }()); ;/* * Flocking Scheduler * http://github.com/colinbdclark/flocking * * Copyright 2013-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, self*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; // TODO: This duplicates code in flocking-core and should be factored differently. flock.shim = { URL: typeof window !== "undefined" ? window.URL || window.webkitURL || window.msURL : undefined }; flock.worker = function (code) { var type = typeof code, url, blob; if (type === "function") { code = "(" + code.toString() + ")();"; } else if (type !== "string") { throw new Error("A flock.worker must be initialized with a String or a Function."); } if (window.Blob) { blob = new Blob([code], { type: "text/javascript" }); url = flock.shim.URL.createObjectURL(blob); } else { url = "data:text/javascript;base64," + window.btoa(code); } return new Worker(url); }; fluid.registerNamespace("flock.scheduler"); /********** * Clocks * **********/ fluid.defaults("flock.scheduler.clock", { gradeNames: ["fluid.eventedComponent", "autoInit"], events: { tick: null } }); fluid.defaults("flock.scheduler.intervalClock", { gradeNames: ["flock.scheduler.clock", "autoInit"], members: { scheduled: {} }, invokers: { schedule: { funcName: "flock.scheduler.intervalClock.schedule", args: [ "{arguments}.0", // The inverval to clear. "{that}.scheduled", "{that}.events.tick.fire", "{that}.events.onClear.fire" ] }, clear: { funcName: "flock.scheduler.intervalClock.clear", args:[ "{arguments}.0", // The inverval to clear. "{that}.scheduled", "{that}.events.onClear.fire" ] }, clearAll: { funcName: "flock.scheduler.intervalClock.clearAll", args: ["{that}.scheduled", "{that}.events.onClear.fire"] }, end: "{that}.clearAll" } }); flock.scheduler.intervalClock.schedule = function (interval, scheduled, onTick) { var id = setInterval(function () { onTick(interval); }, interval); scheduled[interval] = id; }; flock.scheduler.intervalClock.clear = function (interval, scheduled) { var id = scheduled[interval]; clearInterval(id); delete scheduled[interval]; }; flock.scheduler.intervalClock.clearAll = function (scheduled, onClear) { for (var interval in scheduled) { flock.scheduler.intervalClock.clear(interval, scheduled, onClear); } }; fluid.defaults("flock.scheduler.scheduleClock", { gradeNames: ["flock.scheduler.clock", "autoInit"], members: { scheduled: [] }, invokers: { schedule: { funcName: "flock.scheduler.scheduleClock.schedule", args: [ "{arguments}.0", "{that}.scheduled", "{that}.events" ] }, clear: { funcName: "flock.scheduler.scheduleClock.clear", args: [ "{arguments}.0", "{arguments}.1", "{that}.scheduled", "{that}.events.onClear.fire" ] }, clearAll: { funcName: "flock.scheduler.scheduleClock.clearAll", args: [ "{that}.scheduled", "{that}.events.onClear.fire" ] }, end: "{that}.clearAll" } }); flock.scheduler.scheduleClock.schedule = function (timeFromNow, scheduled, events) { var id; id = setTimeout(function () { clearTimeout(id); events.tick.fire(timeFromNow); }, timeFromNow); scheduled.push(id); }; flock.scheduler.scheduleClock.clear = function (id, idx, scheduled) { idx = idx === undefined ? scheduled.indexOf(id) : idx; if (idx > -1) { scheduled.splice(idx, 1); clearTimeout(id); } }; flock.scheduler.scheduleClock.clearAll = function (scheduled) { for (var i = 0; i < scheduled.length; i++) { var id = scheduled[i]; clearTimeout(id); } scheduled.length = 0; }; fluid.defaults("flock.scheduler.webWorkerClock", { gradeNames: ["fluid.eventedComponent", "autoInit"], members: { worker: { expander: { funcName: "flock.worker", args: "@expand:fluid.getGlobalValue(flock.scheduler.webWorkerClock.workerImpl)" } } }, invokers: { postToWorker: { funcName: "flock.scheduler.webWorkerClock.postToWorker", args: [ "{arguments}.0", // Message name. "{arguments}.1", // Value. "{that}.options.messages", "{that}.worker" ] }, schedule: "{that}.postToWorker(schedule, {arguments}.0)", clear: "{that}.postToWorker(clear, {arguments}.0)", clearAll: "{that}.postToWorker(clearAll)", end: "{that}.postToWorker(end)" }, events: { tick: null }, listeners: { onCreate: { funcName: "flock.scheduler.webWorkerClock.init", args: ["{that}"] } }, startMsg: { msg: "start", value: "{that}.options.clockType" }, messages: { schedule: { msg: "schedule" }, clear: { msg: "clear" }, clearAll: { msg: "clearAll" }, end: { msg: "end" } } }); flock.scheduler.webWorkerClock.init = function (that) { that.worker.addEventListener("message", function (e) { that.events.tick.fire(e.data.value); }, false); that.worker.postMessage(that.options.startMsg); }; flock.scheduler.webWorkerClock.postToWorker = function (msgName, value, messages, worker) { var msg = messages[msgName]; if (value !== undefined) { msg.value = value; } worker.postMessage(msg); }; // This code is only intended to run from within a Worker, via flock.worker. flock.scheduler.webWorkerClock.workerImpl = function () { "use strict"; // jshint ignore:line var flock = flock || {}; flock.worker = flock.worker || {}; flock.worker.clock = function () { var that = {}; that.tick = function (interval) { self.postMessage({ msg: "tick", value: interval }); }; return that; }; flock.worker.intervalClock = function () { var that = flock.worker.clock(); that.scheduled = {}; // TODO: Copy-pasted from flock.scheduler.intervalClock. that.schedule = function (interval) { var id = setInterval(function () { that.tick(interval); }, interval); that.scheduled[interval] = id; }; // TODO: Copy-pasted from flock.scheduler.intervalClock. that.clear = function (interval) { var id = that.scheduled[interval]; clearInterval(id); delete that.scheduled[interval]; }; // TODO: Copy-pasted from flock.scheduler.intervalClock. that.clearAll = function () { for (var interval in that.scheduled) { that.clear(interval); } }; return that; }; flock.worker.scheduleClock = function () { var that = flock.worker.clock(); that.scheduled = []; // TODO: Copy-pasted from flock.scheduler.scheduleClock. that.schedule = function (timeFromNow) { var id; id = setTimeout(function () { that.clear(id); that.tick(timeFromNow); }, timeFromNow); that.scheduled.push(id); }; // TODO: Copy-pasted from flock.scheduler.scheduleClock. that.clear = function (id, idx) { idx = idx === undefined ? that.scheduled.indexOf(id) : idx; if (idx > -1) { that.scheduled.splice(idx, 1); } clearTimeout(id); }; // TODO: Copy-pasted from flock.scheduler.scheduleClock. that.clearAll = function () { for (var i = 0; i < that.scheduled.length; i++) { var id = that.scheduled[i]; clearTimeout(id); } that.scheduled.length = 0; }; return that; }; self.addEventListener("message", function (e) { if (e.data.msg === "start") { flock.clock = flock.worker[e.data.value](); } else if (e.data.msg === "end") { if (flock.clock) { flock.clock.clearAll(); self.close(); } } else if (flock.clock) { flock.clock[e.data.msg](e.data.value); } }, false); }; fluid.defaults("flock.scheduler.webWorkerIntervalClock", { gradeNames: ["flock.scheduler.webWorkerClock", "autoInit"], clockType: "intervalClock" }); fluid.defaults("flock.scheduler.webWorkerScheduleClock", { gradeNames: ["flock.scheduler.webWorkerClock", "autoInit"], clockType: "scheduleClock" }); /************** * Schedulers * **************/ fluid.defaults("flock.scheduler", { gradeNames: ["fluid.standardComponent", "autoInit"], events: { onScheduled: null, onFinished: null, onClearAll: null }, listeners: { onClearAll: [ "{that}.clock.clearAll()" ] } }); flock.scheduler.addListener = function (listener, listeners, onAdded) { listeners.push(listener); onAdded(listener); return listener; }; flock.scheduler.removeListener = function (listener, listeners, onRemoved) { if (!listener) { return; } var idx = listeners.indexOf(listener); if (idx > -1) { listeners.splice(idx, 1); onRemoved(listener); } else if (listener.wrappedListener) { flock.scheduler.removeListener(listener.wrappedListener, listeners, onRemoved); } }; fluid.defaults("flock.scheduler.repeat", { gradeNames: ["flock.scheduler", "autoInit"], members: { listeners: {} }, components: { clock: { type: "flock.scheduler.webWorkerIntervalClock" } }, invokers: { schedule: { funcName: "flock.scheduler.repeat.schedule", args: [ "{arguments}.0", // The interval to schedule. "{arguments}.1", // The listener. "{timeConverter}", "{synthContext}", "{that}.listeners", "{that}.events.onScheduled.fire" ] }, clear: "{that}.events.onFinished.fire", clearAll: { funcName: "flock.scheduler.repeat.clearAll", args: [ "{that}.listeners", "{that}.events.onFinished.fire", "{that}.events.onClearAll.fire" ] }, clearInterval: { funcName: "flock.scheduler.repeat.clearInterval", args: ["{arguments}.0", "{that}.listeners", "{that}.events.onFinished.fire"] } }, listeners: { onScheduled: [ { funcName: "flock.scheduler.addListener", args: [ "{arguments}.1", // The listener. { expander: { funcName: "flock.scheduler.repeat.intervalListeners", args: ["{arguments}.0", "{that}.listeners"] } }, "{that}.clock.events.tick.addListener" ] }, { func: "{that}.clock.schedule", args: ["{arguments}.0"] } ], onFinished: { funcName: "flock.scheduler.removeListener", args: [ "{arguments}.1", // The listener. { expander: { funcName: "flock.scheduler.repeat.intervalListeners", args: ["{arguments}.0", "{that}.listeners"] } }, "{that}.clock.events.tick.removeListener" ] } } }); flock.scheduler.repeat.intervalListeners = function (interval, listeners) { return listeners[interval]; }; flock.scheduler.repeat.schedule = function (interval, listener, timeConverter, synthContext, listeners, onScheduled) { interval = timeConverter.value(interval); listener = flock.scheduler.async.prepareListener(listener, synthContext); var wrapper = flock.scheduler.repeat.wrapValueListener(interval, listener); flock.scheduler.repeat.addInterval(interval, listeners); onScheduled(interval, wrapper); return wrapper; }; flock.scheduler.repeat.wrapValueListener = function (value, listener) { var wrapper = function (time) { if (time === value) { listener(time); } }; wrapper.wrappedListener = listener; return wrapper; }; flock.scheduler.repeat.addInterval = function (interval, listeners) { var listenersForInterval = listeners[interval]; if (!listenersForInterval) { listenersForInterval = listeners[interval] = []; } }; flock.scheduler.repeat.clearAll = function (listeners, onFinished, onClearAll) { for (var interval in listeners) { flock.scheduler.repeat.clearInterval(interval, listeners, onFinished); } onClearAll(); }; flock.scheduler.repeat.clearInterval = function (interval, listeners, onFinished) { var listenersForInterval = listeners[interval]; if (!listenersForInterval) { return; } for (var i = 0; i < listenersForInterval.length; i++) { var listener = listenersForInterval[i]; onFinished(interval, listener); } }; fluid.defaults("flock.scheduler.once", { gradeNames: ["flock.scheduler", "autoInit"], members: { listeners: [] }, components: { clock: { type: "flock.scheduler.webWorkerScheduleClock" } }, invokers: { schedule: { funcName: "flock.scheduler.once.schedule", args: [ "{arguments}.0", // The scheduled time. "{arguments}.1", // The listener. "{timeConverter}", "{synthContext}", "{that}.clear", "{that}.events.onScheduled.fire" ] }, clear: "{that}.events.onFinished.fire", clearAll: { funcName: "flock.scheduler.once.clearAll", args: [ "{that}.listeners", "{that}.events.onFinished.fire", "{that}.events.onClearAll.fire" ] } }, listeners: { onScheduled: [ { funcName: "flock.scheduler.addListener", args: [ "{arguments}.1", // The listener. "{that}.listeners", // All registered listeners. "{that}.clock.events.tick.addListener" ] }, { func: "{that}.clock.schedule", args: ["{arguments}.0"] } ], onFinished: { funcName: "flock.scheduler.removeListener", args: [ "{arguments}.0", // The listener. "{that}.listeners", // All registered listeners. "{that}.clock.events.tick.removeListener" ] } } }); flock.scheduler.once.wrapValueListener = function (value, listener, removeFn) { var wrapper = function (time) { if (time === value) { listener(time); removeFn(wrapper); } }; wrapper.wrappedListener = listener; return wrapper; }; flock.scheduler.once.schedule = function (time, listener, timeConverter, synthContext, removeFn, onScheduled) { time = timeConverter.value(time); listener = flock.scheduler.async.prepareListener(listener, synthContext); var wrapper = flock.scheduler.once.wrapValueListener(time, listener, removeFn); onScheduled(time, wrapper); return wrapper; }; flock.scheduler.once.clearAll = function (listeners, onFinished, onClearAll) { for (var i = 0; i < listeners.length; i++) { onFinished(listeners[i]); } onClearAll(); }; fluid.defaults("flock.scheduler.async", { gradeNames: ["fluid.standardComponent", "autoInit"], subSchedulerOptions: { components: { timeConverter: "{async}.timeConverter" }, listeners: { "{async}.events.onClear": "{that}.clear()", "{async}.events.onClearAll": "{that}.clearAll()", "{async}.events.onEnd": "{that}.clock.end()" } }, distributeOptions: { source: "{that}.options.subSchedulerOptions", removeSource: true, target: "{that flock.scheduler}.options" }, components: { timeConverter: { type: "flock.convert.seconds" }, onceScheduler: { type: "flock.scheduler.once" }, repeatScheduler: { type: "flock.scheduler.repeat" }, // This is user-specified. // Typically a flock.band instance or a synth itself, // but can be anything that has a set of named synths. synthContext: undefined }, invokers: { /** * Schedules a listener to be invoked repeatedly at the specified interval. * * @param {Number} interval the interval to schedule * @param {Function} listener the listener to invoke */ repeat: { func: "{repeatScheduler}.schedule", args: ["{arguments}.0", "{arguments}.1"] }, /** * Schedules a listener to be invoked once at a future time. * * @param {Number} time the time (relative to now) when the listener should be invoked * @param {Function} listener the listener to invoke */ once: { func: "{onceScheduler}.schedule", args: ["{arguments}.0", "{arguments}.1"] }, /** * Schedules a series of "once" events. * * @param {Array} times an array of times to schedule * @param {Object} changeSpec the change spec that should be applied */ sequence: { funcName: "flock.scheduler.async.sequence", args: [ "{arguments}.0", // Array of times to schedule. "{arguments}.1", // The changeSpec to schedule. "{that}.once" ] }, /** * Schedules a score. * * @param {Array} score an array of score object */ schedule: { funcName: "flock.scheduler.async.schedule", args: ["{arguments}.0", "{that}"] }, /** * Deprecated. * * Clears a previously-registered listener. * * Note that this function is relatively ineffecient, and * a direct call to the clear() method of either the repeatScheduler * or the onceScheduler is more effective. * * @param {Function} listener the listener to clear */ clear: "{that}.events.onClear.fire", /** * Clears all listeners for all scheduled and repeating events. */ clearAll: "{that}.events.onClearAll.fire", /** * Clears all registered listeners and stops this scheduler's * clocks. */ end: "{that}.events.onEnd.fire" }, events: { onClear: null, onClearAll: null, onEnd: null }, listeners: { onCreate: "{that}.schedule({that}.options.score)", onEnd: "{that}.clearAll", onDestroy: "{that}.end()" } }); flock.scheduler.async.sequence = function (times, changeSpec, onceFn) { var listeners = []; for (var i = 0; i < times.length; i++) { var listener = onceFn(times[i], changeSpec); listeners.push(listener); } return listeners; }; // TODO: This function is implemented suspiciously. flock.scheduler.async.schedule = function (schedules, that) { if (!schedules) { return; } schedules = flock.isIterable(schedules) ? schedules : [schedules]; for (var i = 0; i < schedules.length; i++) { var schedule = schedules[i]; flock.invoke(that, schedule.interval, [schedule.time, schedule.change]); } }; flock.scheduler.async.prepareListener = function (changeSpec, synthContext) { return typeof changeSpec === "function" ? changeSpec : flock.scheduler.async.evaluateChangeSpec(changeSpec, synthContext); }; flock.scheduler.async.getTargetSynth = function (changeSpec, synthContext) { var synthPath = changeSpec.synth; if (!changeSpec.synth) { return synthContext; } if (typeof synthPath !== "string") { return synthPath; } var synth = synthContext ? fluid.get(synthContext, synthPath) : flock.environment.namedNodes[synthPath]; return synth || flock.environment.namedNodes[synthPath]; }; flock.scheduler.async.makeSynthUpdater = function (synths, changeSpec, staticChanges, synthContext) { return function () { for (var path in synths) { var synth = synths[path]; staticChanges[path] = synth.value(); } var targetSynth = flock.scheduler.async.getTargetSynth(changeSpec, synthContext); if (!targetSynth) { flock.fail("A target synth named " + changeSpec.synth + " could not be found in either the specified synthContext or the flock.environment."); } else { targetSynth.set(staticChanges); } }; }; flock.scheduler.async.evaluateChangeSpec = function (changeSpec, synthContext) { var synths = {}, staticChanges = {}; // Find all synthDefs and create demand rate synths for them. for (var path in changeSpec.values) { var change = changeSpec.values[path]; if (change.synthDef) { synths[path] = flock.synth.value(change); } else { staticChanges[path] = change; } } return flock.scheduler.async.makeSynthUpdater(synths, changeSpec, staticChanges, synthContext); }; fluid.defaults("flock.scheduler.async.tempo", { gradeNames: ["flock.scheduler.async", "autoInit"], bpm: 60, components: { timeConverter: { type: "flock.convert.beats", options: { bpm: "{tempo}.options.bpm" } } } }); /******************* * Time Conversion * *******************/ fluid.registerNamespace("flock.convert"); fluid.defaults("flock.convert.ms", { gradeNames: ["fluid.eventedComponent", "autoInit"], invokers: { value: "fluid.identity({arguments}.0)" } }); fluid.defaults("flock.convert.seconds", { gradeNames: ["fluid.eventedComponent", "autoInit"], invokers: { value: "flock.convert.seconds.toMillis({arguments}.0)" } }); flock.convert.seconds.toMillis = function (secs) { return secs * 1000; }; fluid.defaults("flock.convert.beats", { gradeNames: ["fluid.eventedComponent", "autoInit"], bpm: 60, invokers: { value: "flock.convert.beats.toMillis({arguments}.0, {that}.options.bpm)" } }); flock.convert.beats.toMillis = function (beats, bpm) { return bpm <= 0 ? 0 : (beats / bpm) * 60000; }; }()); ;/* * Flocking WebAudio Strategy * http://github.com/colinbdclark/flocking * * Copyright 2013-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, MediaStreamTrack, jQuery*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; fluid.registerNamespace("flock.webAudio"); flock.webAudio.createNode = function (context, nodeSpec) { nodeSpec.args = nodeSpec.args ? fluid.makeArray(nodeSpec.args) : undefined; var creatorName = "create" + nodeSpec.node, nodeStrIdx = creatorName.indexOf("Node"); // Trim off "Node" if it is present. if (nodeStrIdx > -1) { creatorName = creatorName.substring(0, nodeStrIdx); } var node = context[creatorName].apply(context, nodeSpec.args); flock.webAudio.initNodeParams(context, node, nodeSpec); flock.webAudio.initNodeProperties(node, nodeSpec); flock.webAudio.initNodeInputs(node, nodeSpec); return node; }; flock.webAudio.setAudioParamValue = function (context, param, value, atTime) { atTime = atTime || 0.0; var scheduledTime = context.currentTime + atTime; param.setValueAtTime(value, scheduledTime); }; // TODO: Add support for other types of AudioParams. flock.webAudio.initNodeParams = function (context, node, nodeSpec) { var params = nodeSpec.params; if (!node || !params) { return; } for (var paramName in params) { var param = node[paramName], value = params[paramName]; flock.webAudio.setAudioParamValue(context, param, value); } return node; }; flock.webAudio.safariPropertyProhibitions = [ "channelCount", "channelCountMode" ]; flock.webAudio.shouldSetProperty = function (propName) { return flock.platform.browser.safari ? flock.webAudio.safariPropertyProhibitions.indexOf(propName) < 0 : true; }; flock.webAudio.initNodeProperties = function (node, nodeSpec) { var props = nodeSpec.props; if (!props) { return; } for (var propName in props) { var value = props[propName]; if (flock.webAudio.shouldSetProperty(propName)) { node[propName] = value; } } return node; }; flock.webAudio.connectInput = function (node, inputNum, input, outputNum) { input.connect(node, outputNum, inputNum); }; // TODO: Add the ability to specify the output channel of the connection. // TODO: Unify this with AudioParams so they all just look like "inputs". flock.webAudio.initNodeInputs = function (node, nodeSpec) { var inputs = nodeSpec.inputs; for (var inputName in inputs) { var inputNodes = inputs[inputName], inputNum = parseInt(inputName, 10); inputNodes = fluid.makeArray(inputNodes); for (var i = 0; i < inputNodes.length; i++) { var input = inputNodes[i]; flock.webAudio.connectInput(node, inputNum, input); } } }; fluid.defaults("flock.webAudio.audioSystem", { gradeNames: ["flock.audioSystem", "autoInit"], channelRange: { min: "@expand:flock.webAudio.audioSystem.calcMinChannels()", max: "@expand:flock.webAudio.audioSystem.calcMaxChannels({that}.context.destination)" }, members: { context: "@expand:flock.webAudio.audioSystem.createContext()" }, model: { rates: { audio: "{that}.context.sampleRate" } }, listeners: { onCreate: [ "flock.webAudio.audioSystem.registerContextSingleton({that})", "flock.webAudio.audioSystem.configureDestination({that}.context, {that}.model.chans)" ] } }); flock.webAudio.audioSystem.createContext = function () { var singleton = fluid.staticEnvironment.audioSystem; return singleton ? singleton.context : new flock.shim.AudioContext(); }; flock.webAudio.audioSystem.registerContextSingleton = function (that) { fluid.staticEnvironment.audioSystem = that; }; flock.webAudio.audioSystem.calcMaxChannels = function (destination) { return flock.platform.browser.safari ? destination.channelCount : destination.maxChannelCount; }; flock.webAudio.audioSystem.calcMinChannels = function () { return flock.platform.browser.safari ? 2 : 1; }; flock.webAudio.audioSystem.configureDestination = function (context, chans) { // Safari will throw an InvalidStateError DOM Exception 11 when // attempting to set channelCount on the audioContext's destination. // TODO: Remove this conditional when Safari adds support for multiple channels. if (!flock.platform.browser.safari) { context.destination.channelCount = chans; context.destination.channelCountMode = "explicit"; context.destination.channelInterpretation = "discrete"; } }; fluid.defaults("flock.webAudio.node", { gradeNames: ["fluid.standardRelayComponent", "autoInit"], members: { node: "@expand:flock.webAudio.createNode({audioSystem}.context, {that}.options.nodeSpec)" }, nodeSpec: { args: [], params: {}, properties: {} } }); fluid.defaults("flock.webAudio.gain", { gradeNames: ["flock.webAudio.node", "autoInit"], members: { node: "@expand:flock.webAudio.createNode({audioSystem}.context, {that}.options.nodeSpec)" }, nodeSpec: { node: "Gain" } }); fluid.defaults("flock.webAudio.scriptProcessor", { gradeNames: ["flock.webAudio.node", "autoInit"], nodeSpec: { node: "ScriptProcessor", args: [ "{audioSystem}.model.bufferSize", "{audioSystem}.model.numInputBuses", "{audioSystem}.model.chans" ], params: {}, properties: { channelCountMode: "explicit" } } }); fluid.defaults("flock.webAudio.channelMerger", { gradeNames: ["flock.webAudio.node", "autoInit"], nodeSpec: { node: "ChannelMerger", args: ["{audioSystem}.model.numInputBuses"], properties: { channelCountMode: "discrete" } } }); // TODO: Remove this when Chrome implements navigator.getMediaDevices(). fluid.registerNamespace("flock.webAudio.chrome"); flock.webAudio.chrome.getSources = function (callback) { return MediaStreamTrack.getSources(function (infoSpecs) { var normalized = fluid.transform(infoSpecs, function (infoSpec) { infoSpec.deviceId = infoSpec.id; return infoSpec; }); callback(normalized); }); }; flock.webAudio.mediaStreamFailure = function () { flock.fail("Media Capture and Streams are not supported on this browser."); }; var webAudioShims = { AudioContext: window.AudioContext || window.webkitAudioContext, getUserMediaImpl: navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || flock.webAudio.mediaStreamFailure, getUserMedia: function () { flock.shim.getUserMediaImpl.apply(navigator, arguments); }, getMediaDevicesImpl: navigator.getMediaDevices ? navigator.getMediaDevices : typeof window.MediaStreamTrack !== "undefined" ? flock.webAudio.chrome.getSources : flock.webAudio.mediaStreamFailure, getMediaDevice: function () { flock.shim.getMediaDevicesImpl.apply(navigator, arguments); } }; jQuery.extend(flock.shim, webAudioShims); /** * Web Audio API Audio Strategy */ fluid.defaults("flock.audioStrategy.web", { gradeNames: ["flock.audioStrategy", "autoInit"], model: { isGenerating: false, shouldInitIOS: flock.platform.isIOS }, invokers: { start: "{that}.events.onStart.fire()", stop: "{that}.events.onStop.fire()", saveBuffer: "flock.audioStrategy.web.saveBuffer({arguments}.0)" }, components: { nativeNodeManager: { type: "flock.webAudio.nativeNodeManager" }, inputDeviceManager: { type: "flock.webAudio.inputDeviceManager" } }, listeners: { onStart: [ { func: "{that}.applier.change", args: ["isGenerating", true] } ], onStop: [ { func: "{that}.applier.change", args: ["isGenerating", false] } ] } }); flock.audioStrategy.web.bindWriter = function (jsNode, nodeEvaluator, nativeNodeManager, model, audioSettings) { jsNode.model = model; jsNode.evaluator = nodeEvaluator; jsNode.audioSettings = audioSettings; jsNode.inputNodes = nativeNodeManager.inputNodes; jsNode.onaudioprocess = flock.audioStrategy.web.writeSamples; }; /** * Writes samples to the audio strategy's ScriptProcessorNode. * * This function must be bound as a listener to the node's * onaudioprocess event. It expects to be called in the context * of a "this" instance containing the following properties: * - model: the strategy's model object * - inputNodes: a list of native input nodes to be read into input buses * - nodeEvaluator: a nodeEvaluator instance * - audioSettings: the enviornment's audio settings */ flock.audioStrategy.web.writeSamples = function (e) { var numInputNodes = this.inputNodes.length, evaluator = this.evaluator, nodes = evaluator.nodes, s = this.audioSettings, inBufs = e.inputBuffer, outBufs = e.outputBuffer, numBlocks = s.numBlocks, buses = evaluator.buses, numBuses = s.numBuses, blockSize = s.blockSize, chans = s.chans, inChans = inBufs.numberOfChannels, chan, i, samp; // If there are no nodes providing samples, write out silence. if (evaluator.nodes.length < 1) { for (chan = 0; chan < chans; chan++) { flock.generate.silence(outBufs.getChannelData(chan)); } return; } // TODO: Make a formal distinction between input buses, // output buses, and interconnect buses in the environment! for (i = 0; i < numBlocks; i++) { var offset = i * blockSize; flock.nodeEvaluator.clearBuses(numBuses, blockSize, buses); // Read this ScriptProcessorNode's input buffers // into the environment. if (numInputNodes > 0) { for (chan = 0; chan < inChans; chan++) { var inBuf = inBufs.getChannelData(chan), inBusNumber = chans + chan, // Input buses are located after output buses. targetBuf = buses[inBusNumber]; for (samp = 0; samp < blockSize; samp++) { targetBuf[samp] = inBuf[samp + offset]; } } } flock.nodeEvaluator.gen(nodes); // Output the environment's signal // to this ScriptProcessorNode's output channels. for (chan = 0; chan < chans; chan++) { var sourceBuf = buses[chan], outBuf = outBufs.getChannelData(chan); // And output each sample. for (samp = 0; samp < blockSize; samp++) { outBuf[samp + offset] = sourceBuf[samp]; } } } }; flock.audioStrategy.web.iOSStart = function (model, applier, ctx, jsNode) { // Work around a bug in iOS Safari where it now requires a noteOn() // message to be invoked before sound will work at all. Just connecting a // ScriptProcessorNode inside a user event handler isn't sufficient. if (model.shouldInitIOS) { var s = ctx.createBufferSource(); s.connect(jsNode); s.start(0); s.stop(0); s.disconnect(0); applier.change("shouldInitIOS", false); } }; flock.audioStrategy.web.saveBuffer = function (o) { try { var encoded = flock.audio.encode.wav(o.buffer, o.format), blob = new Blob([encoded], { type: "audio/wav" }); flock.audioStrategy.web.download(o.path, blob); if (o.success) { o.success(encoded); } return encoded; } catch (e) { if (!o.error) { flock.fail("There was an error while trying to download the buffer named " + o.buffer.id + ". Error: " + e); } else { o.error(e); } } }; flock.audioStrategy.web.download = function (fileName, blob) { var dataURL = flock.shim.URL.createObjectURL(blob), a = window.document.createElement("a"), click = document.createEvent("Event"); // TODO: This approach currently only works in Chrome. // Although Firefox apparently supports it, this method of // programmatically clicking the link doesn't seem to have an // effect in it. // http://caniuse.com/#feat=download a.href = dataURL; a.download = fileName; click.initEvent("click", true, true); a.dispatchEvent(click); }; /** * Manages a collection of input nodes and an output node, * with a JS node in between. * * Note: this component is slated for removal when Web Audio * "islands" are implemented. */ fluid.defaults("flock.webAudio.nativeNodeManager", { gradeNames: ["fluid.standardRelayComponent", "autoInit"], members: { outputNode: undefined, inputNodes: [] }, components: { scriptProcessor: { createOnEvent: "onCreateScriptProcessor", type: "flock.webAudio.scriptProcessor", options: { nodeSpec: { inputs: { "0": "{inputMerger}" } }, listeners: { onCreate: [ // TODO: Where should this really go? { funcName: "flock.audioStrategy.web.bindWriter", args: [ "{that}.node", "{nodeEvaluator}", "{nativeNodeManager}", "{audioStrategy}.model", "{audioSystem}.model" ] } ] } } }, merger: { type: "flock.webAudio.channelMerger" } }, invokers: { connect: "{that}.events.onConnect.fire", disconnect: "{that}.events.onDisconnect.fire", createNode: { funcName: "flock.webAudio.createNode", args: [ "{audioSystem}.context", "{arguments}.0" // The nodeSpec ] }, createInputNode: { funcName: "flock.webAudio.nativeNodeManager.createInputNode", args: [ "{that}", "{arguments}.0", // The nodeSpec. "{arguments}.1", // {optional} The input bus number to insert it at. ] }, createMediaStreamInput: { funcName: "flock.webAudio.nativeNodeManager.createInputNode", dynamic: true, args: [ "{that}", { node: "MediaStreamSource", args: ["{arguments}.0"] // The MediaStream }, "{arguments}.1" // {optional} The input bus number to insert it at. ] }, createMediaElementInput: { funcName: "flock.webAudio.nativeNodeManager.createInputNode", dynamic: true, args: [ "{that}", { node: "MediaElementSource", args: ["{arguments}.0"] // The HTMLMediaElement }, "{arguments}.1" // {optional} The input bus number to insert it at. ] }, createOutputNode: { funcName: "flock.webAudio.nativeNodeManager.createOutputNode", args: [ "{that}", "{arguments}.0" // The nodeSpec ] }, insertInput: { funcName: "flock.webAudio.nativeNodeManager.insertInput", args: [ "{that}", "{audioSystem}.model", "{enviro}", "{arguments}.0", // The node to insert. "{arguments}.1" // {optional} The bus number to insert it at. ] }, removeInput: { funcName: "flock.webAudio.nativeNodeManager.removeInput", args: ["{arguments}.0", "{that}.inputNodes"] }, removeAllInputs: { funcName: "flock.webAudio.nativeNodeManager.removeAllInputs", args: "{that}.inputNodes" }, insertOutput: { funcName: "flock.webAudio.nativeNodeManager.insertOutput", args: ["{that}", "{arguments}.0"] }, removeOutput: { funcName: "flock.webAudio.nativeNodeManager.removeOutput", dynamic: true, args: ["{scriptProcessor}.node"] } }, events: { onCreateScriptProcessor: null, // TODO: Naming! onStart: "{audioStrategy}.events.onStart", onConnect: null, onStop: "{audioStrategy}.events.onStop", onDisconnect: null, onReset: "{audioStrategy}.events.onReset" }, listeners: { onCreate: [ "{that}.events.onCreateScriptProcessor.fire()", { func: "{that}.insertOutput", args: "{scriptProcessor}.node" } ], onStart: [ "{nativeNodeManager}.connect()", { // TODO: Replace this with some progressive enhancement action. // TODO: Where should this really go? funcName: "flock.audioStrategy.web.iOSStart", args: [ "{audioStrategy}.model", "{audioStrategy}.applier", "{audioSystem}.context", "{scriptProcessor}.node" ] } ], onConnect: [ { "this": "{merger}.node", method: "connect", args: ["{scriptProcessor}.node"] }, { "this": "{that}.outputNode", method: "connect", args: ["{audioSystem}.context.destination"] }, { funcName: "flock.webAudio.nativeNodeManager.connectOutput", args: ["{scriptProcessor}.node", "{that}.outputNode"] } ], onStop: [ "{nativeNodeManager}.disconnect()" ], onDisconnect: [ { "this": "{merger}.node", method: "disconnect", args: [0] }, { "this": "{scriptProcessor}.node", method: "disconnect", args: [0] }, { "this": "{that}.outputNode", method: "disconnect", args: [0] } ], onReset: [ "{that}.removeAllInputs", "{that}.events.onCreateScriptProcessor.fire()" ] } }); flock.webAudio.nativeNodeManager.createInputNode = function (that, nodeSpec, busNum) { var node = that.createNode(nodeSpec); return that.insertInput(node, busNum); }; flock.webAudio.nativeNodeManager.createOutputNode = function (that, nodeSpec) { var node = that.createNode(nodeSpec); return that.insertOutput(node); }; flock.webAudio.nativeNodeManager.connectOutput = function (jsNode, outputNode) { if (jsNode !== outputNode) { jsNode.connect(outputNode); } }; flock.webAudio.nativeNodeManager.removeAllInputs = function (inputNodes) { for (var i = 0; i < inputNodes.length; i++) { var node = inputNodes[i]; node.disconnect(0); } inputNodes.length = 0; }; flock.webAudio.nativeNodeManager.insertInput = function (that, audioSettings, enviro, node, busNum) { var maxInputs = audioSettings.numInputBuses; if (that.inputNodes.length >= maxInputs) { flock.fail("There are too many input nodes connected to Flocking. " + "The maximum number of input buses is currently set to " + maxInputs + ". " + "Either remove an existing input node or increase Flockings numInputBuses option."); return; } busNum = busNum === undefined ? enviro.busManager.acquireNextBus("input") : busNum; var idx = busNum - audioSettings.chans; that.inputNodes.push(node); node.connect(that.merger.node, 0, idx); return busNum; }; flock.webAudio.nativeNodeManager.removeInput = function (node, inputNodes) { var idx = inputNodes.indexOf(node); if (idx > -1) { inputNodes.splice(idx, 1); } node.disconnect(0); }; flock.webAudio.nativeNodeManager.insertOutput = function (that, node) { if (that.outputNode) { that.outputNode.disconnect(0); } that.outputNode = node; return node; }; flock.webAudio.nativeNodeManager.removeOutput = function (jsNode) { // Replace the current output node with the jsNode. flock.webAudio.nativeNodeManager.insertOutput(jsNode); }; /** * Manages audio input devices using the Web Audio API. */ // Add a means for disconnecting audio input nodes. fluid.defaults("flock.webAudio.inputDeviceManager", { gradeNames: ["fluid.eventedComponent", "autoInit"], invokers: { /** * Opens the specified audio device. * If no device is specified, the default device is opened. * * @param {Object} deviceSpec a device spec containing, optionally, an 'id' or 'label' parameter */ openAudioDevice: { funcName: "flock.webAudio.inputDeviceManager.openAudioDevice", args: [ "{arguments}.0", "{that}.openAudioDeviceWithId", "{that}.openFirstAudioDeviceWithLabel", "{that}.openAudioDeviceWithConstraints" ] }, /** * Opens an audio device with the specified WebRTC constraints. * If no constraints are specified, the default audio device is opened. * * @param {Object} constraints a WebRTC-compatible constraints object */ openAudioDeviceWithConstraints: { funcName: "flock.webAudio.inputDeviceManager.openAudioDeviceWithConstraints", args: [ "{audioSystem}.context", "{enviro}", "{nativeNodeManager}.createMediaStreamInput", "{arguments}.0" ] }, /** * Opens an audio device with the specified WebRTC device id. * * @param {string} id a device identifier */ openAudioDeviceWithId: { funcName: "flock.webAudio.inputDeviceManager.openAudioDeviceWithId", args: ["{arguments}.0", "{that}.openAudioDeviceWithConstraints"] }, /** * Opens the first audio device found with the specified label. * The label must be an exact, case-insensitive match. * * @param {string} label a device label */ openFirstAudioDeviceWithLabel: { funcName: "flock.webAudio.inputDeviceManager.openFirstAudioDeviceWithLabel", args: ["{arguments}.0", "{that}.openAudioDeviceWithId"] } } }); flock.webAudio.inputDeviceManager.openAudioDevice = function (sourceSpec, idOpener, labelOpener, specOpener) { if (sourceSpec) { if (sourceSpec.id) { return idOpener(sourceSpec.id); } else if (sourceSpec.label) { return labelOpener(sourceSpec.label); } } return specOpener(); }; flock.webAudio.inputDeviceManager.openAudioDeviceWithId = function (id, deviceOpener) { var options = { audio: { optional: [ { sourceId: id } ] } }; deviceOpener(options); }; flock.webAudio.inputDeviceManager.openFirstAudioDeviceWithLabel = function (label, deviceOpener) { if (!label) { return; } // TODO: Can't access device labels until the user agrees // to allow access to the current device. flock.shim.getMediaDevices(function (deviceInfoSpecs) { var matches = deviceInfoSpecs.filter(function (device) { if (device.label.toLowerCase() === label.toLowerCase()) { return true; } }); if (matches.length > 0) { deviceOpener(matches[0].deviceId); } else { fluid.log(fluid.logLevel.IMPORTANT, "An audio device named '" + label + "' could not be found."); } }); }; flock.webAudio.inputDeviceManager.openAudioDeviceWithConstraints = function (context, enviro, openMediaStream, options) { options = options || { audio: true }; // Acquire an input bus ahead of time so we can synchronously // notify the client where its output will be. var busNum = enviro.busManager.acquireNextBus("input"); function error (err) { fluid.log(fluid.logLevel.IMPORTANT, "An error occurred while trying to access the user's microphone. " + err); } function success (mediaStream) { openMediaStream(mediaStream, busNum); } flock.shim.getUserMedia(options, success, error); return busNum; }; fluid.defaults("flock.webAudio.outputFader", { gradeNames: ["fluid.eventedComponent", "autoInit"], fadeDuration: 0.5, gainSpec: { node: "Gain", params: { gain: 0.0 }, properties: { channelCount: "{audioSystem}.model.chans", channelCountMode: "explicit" } }, members: { gainNode: "@expand:flock.webAudio.outputFader.createGainNode({enviro}, {that}.options.gainSpec)", context: "{audioSystem}.context" }, invokers: { fadeIn: { funcName: "flock.webAudio.outputFader.fadeIn", args: [ "{that}.context", "{that}.gainNode", "{arguments}.0", // Target amplitude "{that}.options.fadeDuration" ] }, fadeTo: { funcName: "flock.webAudio.outputFader.fadeTo", args: [ "{that}.context", "{that}.gainNode", "{arguments}.0", // Target amplitude "{that}.options.fadeDuration" ] } } }); flock.webAudio.outputFader.createGainNode = function (enviro, gainSpec) { var gainNode = enviro.audioStrategy.nativeNodeManager.createOutputNode(gainSpec); return gainNode; }; flock.webAudio.outputFader.fade = function (context, gainNode, start, end, duration) { duration = duration || 0.0; var now = context.currentTime, endTime = now + duration; // Set the current value now, then ramp to the target. flock.webAudio.setAudioParamValue(context, gainNode.gain, start); gainNode.gain.linearRampToValueAtTime(end, endTime); }; flock.webAudio.outputFader.fadeTo = function (context, gainNode, end, duration) { flock.webAudio.outputFader.fade(context, gainNode, gainNode.gain.value, end, duration); }; flock.webAudio.outputFader.fadeIn = function (context, gainNode, end, duration) { flock.webAudio.outputFader.fade(context, gainNode, 0, end, duration); }; fluid.demands("flock.audioSystem.platform", "flock.platform.webAudio", { funcName: "flock.webAudio.audioSystem" }); fluid.demands("flock.audioStrategy.platform", "flock.platform.webAudio", { funcName: "flock.audioStrategy.web" }); }()); ;/* * Flocking MIDI * http://github.com/colinbdclark/flocking * * Copyright 2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require, Promise, console*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; fluid.registerNamespace("flock.midi"); flock.midi.requestAccess = function (sysex, onAccessGranted, onError) { if (!navigator.requestMIDIAccess) { var msg = "The Web MIDI API is not available. You may need to enable it in your browser's settings."; fluid.log(fluid.logLevel.WARN, msg); onError(msg); return; } var p = navigator.requestMIDIAccess({ sysex: sysex }); p.then(onAccessGranted, onError); }; flock.midi.getPorts = function (access) { var ports = {}, portCollector = typeof access.inputs === "function" ? flock.midi.collectPortsLegacy : flock.midi.collectPorts; portCollector("inputs", access, ports); portCollector("outputs", access, ports); return ports; }; flock.midi.requestPorts = function (success, error) { function wrappedSuccess (access) { var ports = flock.midi.getPorts(access); success(ports); } flock.midi.requestAccess(false, wrappedSuccess, error); }; flock.midi.createPortViews = function (portsArray) { return fluid.transform(portsArray, function (port) { return { id: port.id, name: port.name, manufacturer: port.manufacturer, state: port.state, connection: port.connection }; }); }; flock.midi.prettyPrintPorts = function (ports) { return fluid.prettyPrintJSON({ inputs: flock.midi.createPortViews(ports.inputs), outputs: flock.midi.createPortViews(ports.outputs) }); }; flock.midi.logPorts = function () { function success (ports) { var printed = flock.midi.prettyPrintPorts(ports); console.log(printed); } function error (err) { console.log(err); } flock.midi.requestPorts(success, error); }; flock.midi.collectPorts = function (type, access, ports) { var portsForType = ports[type] = ports[type] || [], iterator = access[type].values(); // TODO: Switch to ES6 for..of syntax when it's safe to do so // across all supported Flocking environments // (i.e. when Node.js and eventually IE support it). var next = iterator.next(); while (!next.done) { portsForType.push(next.value); next = iterator.next(); } return ports; }; // TODO: Remove this when the new Web MIDI API makes it // into the Chrome release channel. flock.midi.collectPortsLegacy = function (type, access, ports) { if (access[type]) { ports[type] = access[type](); } return ports; }; flock.midi.read = function (data) { var status = data[0], type = status >> 4, chan = status & 0xf, fn; switch (type) { case 8: fn = flock.midi.read.noteOff; break; case 9: fn = data[2] > 0 ? flock.midi.read.noteOn : flock.midi.read.noteOff; break; case 10: fn = flock.midi.read.polyAftertouch; break; case 11: fn = flock.midi.read.controlChange; break; case 12: fn = flock.midi.read.programChange; break; case 13: fn = flock.midi.read.channelAftertouch; break; case 14: fn = flock.midi.read.pitchbend; break; case 15: fn = flock.midi.read.sysex; break; default: throw new Error("Recieved an unrecognized MIDI message: " + data); } return fn(chan, data); }; flock.midi.read.note = function (type, chan, data) { return { type: type, chan: chan, note: data[1], velocity: data[2] }; }; flock.midi.read.noteOn = function (chan, data) { return flock.midi.read.note("noteOn", chan, data); }; flock.midi.read.noteOff = function (chan, data) { return flock.midi.read.note("noteOff", chan, data); }; flock.midi.read.polyAftertouch = function (chan, data) { return { type: "aftertouch", chan: chan, note: data[1], pressure: data[2] }; }; flock.midi.read.controlChange = function (chan, data) { return { type: "control", chan: chan, number: data[1], value: data[2] }; }; flock.midi.read.programChange = function (chan, data) { return { type: "program", chan: chan, program: data[1] }; }; flock.midi.read.channelAftertouch = function (chan, data) { return { type: "aftertouch", chan: chan, pressure: data[1] }; }; flock.midi.read.pitchbend = function (chan, data) { return { type: "pitchbend", chan: chan, value: (data[1] << 7) | data[2] }; }; flock.midi.read.sysex = function (chan, data) { return { type: "system", chan: chan, data: data.subarray(1) }; }; /** * Represents the overall Web MIDI system, * including references to all the available MIDI ports * and the MIDIAccess object. */ // TODO: This should be a model component! fluid.defaults("flock.midi.system", { gradeNames: ["fluid.eventedComponent", "autoInit"], sysex: false, members: { access: undefined, ports: undefined }, invokers: { requestAccess: { funcName: "flock.midi.requestAccess", args: [ "{that}.options.sysex", "{that}.events.onAccessGranted.fire", "{that}.events.onAccessError.fire" ] }, refreshPorts: { funcName: "flock.midi.system.refreshPorts", args: ["{that}", "{that}.access", "{that}.events.onPortsAvailable.fire"] } }, events: { onAccessGranted: null, onAccessError: null, onReady: null, onPortsAvailable: null }, listeners: { onCreate: { func: "{that}.requestAccess" }, onAccessGranted: [ "flock.midi.system.setAccess({that}, {arguments}.0)", "{that}.refreshPorts()", "{that}.events.onReady.fire({that}.ports)" ], onAccessError: { funcName: "fluid.log", args: [fluid.logLevel.WARN, "MIDI Access Error: ", "{arguments}.0"] } } }); flock.midi.system.setAccess = function (that, access) { that.access = access; }; flock.midi.system.refreshPorts = function (that, access, onPortsAvailable) { that.ports = flock.midi.getPorts(access); onPortsAvailable(that.ports); }; /** * An abstract grade that the defines the event names * for receiving MIDI messages */ fluid.defaults("flock.midi.receiver", { gradeNames: ["fluid.eventedComponent"], events: { raw: null, message: null, note: null, noteOn: null, noteOff: null, control: null, program: null, aftertouch: null, pitchbend: null } }); /* * A MIDI Connection represents a connection between an arbitrary set of * input and output ports across one or more MIDI devices connected to the system. */ // TODO: Handle port disconnection events. fluid.defaults("flock.midi.connection", { gradeNames: ["flock.midi.receiver", "autoInit"], openImmediately: false, sysex: false, distributeOptions: { source: "{that}.options.sysex", target: "{that > system}.options.sysex" }, // Supported PortSpec formats: // - Number: the index of the input and output port to use (this is the default) // - { manufacturer: "akai", name: "LPD8"} // - { input: Number, output: Number} // - { input: { manufacturer: "akai", name: "LPD8"}, output: {manufacturer: "korg", name: "output"}} ports: 0, invokers: { send: { func: "{that}.events.onSendMessage.fire" }, open: { funcName: "flock.midi.connection.bind", args: [ "{system}.ports", "{that}.options.ports", "{that}.events.onReady.fire", "{that}.events.raw.fire", "{that}.events.onSendMessage" ] }, close: { funcName: "flock.midi.connection.close", args: [ "{system}.ports", "{that}.events.raw.fire" ] } }, components: { system: { type: "flock.midi.system", options: { events: { onReady: "{connection}.events.onPortsAvailable" } } } }, events: { onPortsAvailable: null, onReady: null, onError: null, onSendMessage: null }, listeners: { onPortsAvailable: { funcName: "flock.midi.connection.autoOpen", args: [ "{connection}.options.openImmediately", "{connection}.open" ] }, onError: { funcName: "fluid.log", args: [fluid.logLevel.WARN, "{arguments}.0"] }, raw: { funcName: "flock.midi.connection.fireEvent", args: ["{arguments}.0", "{that}.events"] }, onDestroy: [ "{that}.close()" ] } }); flock.midi.connection.autoOpen = function (openImmediately, openFn) { if (openImmediately) { openFn(); } }; flock.midi.findPorts = function (ports, portSpecs) { portSpecs = fluid.makeArray(portSpecs); var matches = []; fluid.each(portSpecs, function (portSpec) { var portFinder = flock.midi.findPorts.portFinder(portSpec), matchesForSpec = portFinder(ports); matches = matches.concat(matchesForSpec); }); return matches; }; flock.midi.findPorts.portFinder = function (portSpec) { if (typeof portSpec === "number") { return flock.midi.findPorts.byIndex(portSpec); } if (typeof portSpec === "string") { portSpec = { name: portSpec }; } var matcher = portSpec.id ? flock.midi.findPorts.idMatcher(portSpec.id) : portSpec.manufacturer && portSpec.name ? flock.midi.findPorts.bothMatcher(portSpec.manufacturer, portSpec.name) : portSpec.manufacturer ? flock.midi.findPorts.manufacturerMatcher(portSpec.manufacturer) : flock.midi.findPorts.nameMatcher(portSpec.name); return function (ports) { return ports.filter(matcher); }; }; flock.midi.findPorts.byIndex = function (idx) { return function (ports) { var port = ports[idx]; return port ? [port] : []; }; }; flock.midi.findPorts.lowerCaseContainsMatcher = function (matchSpec) { return function (obj) { var isMatch; for (var prop in matchSpec) { var objVal = obj[prop]; var matchVal = matchSpec[prop]; isMatch = (matchVal === "*") ? true : objVal && (objVal.toLowerCase().indexOf(matchVal.toLowerCase()) > -1); if (!isMatch) { break; } } return isMatch; }; }; flock.midi.findPorts.idMatcher = function (id) { return function (port) { return port.id === id; }; }; flock.midi.findPorts.bothMatcher = function (manu, name) { return flock.midi.findPorts.lowerCaseContainsMatcher({ manufacturer: manu, name: name }); }; flock.midi.findPorts.manufacturerMatcher = function (manu) { return flock.midi.findPorts.lowerCaseContainsMatcher({ manufacturer: manu }); }; flock.midi.findPorts.nameMatcher = function (name) { return flock.midi.findPorts.lowerCaseContainsMatcher({ name: name }); }; flock.midi.findPorts.eachPortOfType = function (port, type, fn) { var ports = fluid.makeArray(port); fluid.each(ports, function (port) { if (port.type === type) { fn(port); } }); }; flock.midi.connection.openPort = function (port, openPromises) { // Remove this conditional when Chrome 43 has been released. if (port.open) { var p = port.open(); openPromises.push(p); } return openPromises; }; flock.midi.connection.listen = function (port, onRaw, openPromises) { flock.midi.findPorts.eachPortOfType(port, "input", function (port) { flock.midi.connection.openPort(port, openPromises); port.addEventListener("midimessage", onRaw, false); }); return openPromises; }; flock.midi.connection.stopListening = function (port, onRaw) { flock.midi.findPorts.eachPortOfType(port, "input", function (port) { port.close(); port.removeEventListener("midimessage", onRaw, false); }); }; flock.midi.connection.bindSender = function (port, onSendMessage, openPromises) { var ports = fluid.makeArray(port); fluid.each(ports, function (port) { flock.midi.connection.openPort(port, openPromises); onSendMessage.addListener(port.send.bind(port)); }); return openPromises; }; flock.midi.connection.fireReady = function (openPromises, onReady) { if (!openPromises || openPromises.length < 1) { return; } Promise.all(openPromises).then(onReady); }; flock.midi.connection.bind = function (ports, portSpec, onReady, onRaw, onSendMessage) { portSpec = flock.midi.connection.expandPortSpec(portSpec); var input = flock.midi.findPorts(ports.inputs, portSpec.input), output = flock.midi.findPorts(ports.outputs, portSpec.output), openPromises = []; if (input && input.length > 0) { flock.midi.connection.listen(input, onRaw, openPromises); } else if (portSpec.input !== undefined) { flock.midi.connection.logNoMatchedPorts("input", portSpec); } if (output && output.length > 0) { flock.midi.connection.bindSender(output, onSendMessage, openPromises); } else if (portSpec.output !== undefined) { flock.midi.connection.logNoMatchedPorts("output", portSpec); } flock.midi.connection.fireReady(openPromises, onReady); }; flock.midi.connection.close = function (ports, onRaw) { flock.midi.connection.stopListening(ports.inputs, onRaw); // TODO: Come up with some scheme for unbinding port senders // since they use Function.bind(). }; flock.midi.connection.logNoMatchedPorts = function (type, portSpec) { fluid.log(fluid.logLevel.WARN, "No matching " + type + " ports were found for port specification: ", portSpec[type]); }; flock.midi.connection.expandPortSpec = function (portSpec) { if (portSpec.input !== undefined || portSpec.output !== undefined) { return portSpec; } var expanded = { input: {}, output: {} }; if (typeof portSpec === "number") { expanded.input = expanded.output = portSpec; } else { flock.midi.connection.expandPortSpecProperty("manufacturer", portSpec, expanded); flock.midi.connection.expandPortSpecProperty("name", portSpec, expanded); } return expanded; }; flock.midi.connection.expandPortSpecProperty = function (propName, portSpec, expanded) { expanded.input[propName] = expanded.output[propName] = portSpec[propName]; return expanded; }; flock.midi.connection.fireEvent = function (midiEvent, events) { var model = flock.midi.read(midiEvent.data), eventForType = model.type ? events[model.type] : undefined; events.message.fire(model); // TODO: Remove this special-casing of noteOn/noteOff events into note events. if (model.type === "noteOn" || model.type === "noteOff") { events.note.fire(model); } if (eventForType) { eventForType.fire(model); } }; fluid.defaults("flock.midi.controller", { gradeNames: ["fluid.eventedComponent", "autoInit"], members: { controlMap: "@expand:flock.midi.controller.optimizeControlMap({that}.options.controlMap)", noteMap: "{that}.options.noteMap" }, controlMap: {}, // Control and note maps noteMap: {}, // need to be specified by the user. components: { synthContext: { // Also user-specified. Typically a flock.band instance, type: "flock.band" // but can be anything that has a set of named synths, }, // including a synth itself. connection: { type: "flock.midi.connection", options: { ports: { input: "*" // Connect to the first available input port. }, openImmediately: true, // Immediately upon instantiating the connection. listeners: { control: { func: "{controller}.mapControl" }, note: { func: "{controller}.mapNote" } } } } }, invokers: { mapControl: { funcName: "flock.midi.controller.mapControl", args: ["{arguments}.0", "{that}.synthContext", "{that}.controlMap"] }, mapNote: { funcName: "flock.midi.controller.mapNote", args: ["{arguments}.0", "{that}.synthContext", "{that}.noteMap"] } } }); flock.midi.controller.optimizeControlMap = function (controlMap) { var controlMapArray = new Array(127); fluid.each(controlMap, function (mapSpec, controlNum) { var idx = Number(controlNum); controlMapArray[idx] = mapSpec; }); return controlMapArray; }; flock.midi.controller.expandControlMapSpec = function (valueUGenID, mapSpec) { mapSpec.transform.id = valueUGenID; // TODO: The key "valuePath" is confusing; // it actually points to the location in the // transform synth where the value will be set. mapSpec.valuePath = mapSpec.valuePath || "value"; if (!mapSpec.transform.ugen) { mapSpec.transform.ugen = "flock.ugen.value"; } return mapSpec; }; flock.midi.controller.makeValueSynth = function (value, id, mapSpec) { mapSpec = flock.midi.controller.expandControlMapSpec(id, mapSpec); var transform = mapSpec.transform, valuePath = mapSpec.valuePath; flock.set(transform, valuePath, value); // Instantiate the new value synth. var valueSynth = flock.synth.value({ synthDef: transform }); // Update the value path so we can quickly update the synth's input value. mapSpec.valuePath = id + "." + valuePath; return valueSynth; }; flock.midi.controller.transformValue = function (value, mapSpec) { var transform = mapSpec.transform, type = typeof transform; if (type === "function") { return transform(value); } // TODO: Add support for string-based transforms // that bind to globally-defined synths // (e.g. "flock.synth.midiFreq" or "flock.synth.midiAmp") // TODO: Factor this into a separate function. if (!mapSpec.transformSynth) { // We have a raw synthDef. // Instantiate a value synth to transform incoming control values. // TODO: In order to support multiple inputs (e.g. a multi-arg OSC message), // this special path needs to be scoped to the argument name. In the case of MIDI, // this would be the CC number. In the case of OSC, it would be a combination of // OSC message address and argument index. mapSpec.transformSynth = flock.midi.controller.makeValueSynth( value, "flock-midi-controller-in", mapSpec); } else { // TODO: When the new node architecture is in in place, we can directly connect this // synth to the target synth at instantiation time. // TODO: Add support for arrays of values, such as multi-arg OSC messages. mapSpec.transformSynth.set(mapSpec.valuePath, value); } return mapSpec.transformSynth.value(); }; flock.midi.controller.setMappedValue = function (value, map, synthContext) { if (!map) { return; } value = map.transform ? flock.midi.controller.transformValue(value, map) : value; var synth = synthContext[map.synth] || synthContext; synth.set(map.input, value); }; flock.midi.controller.mapControl = function (midiMsg, synthContext, controlMap) { var map = controlMap[midiMsg.number], value = midiMsg.value; flock.midi.controller.setMappedValue(value, map, synthContext); }; // TODO: Add support for defining listener filters or subsets // of all midi notes (e.g. for controllers like the Quneo). flock.midi.controller.mapNote = function (midiMsg, synthContext, noteMap) { var keyMap = noteMap.note, key = midiMsg.note, velMap = noteMap.velocity, vel = midiMsg.velocity; if (keyMap) { flock.midi.controller.setMappedValue(key, keyMap, synthContext); } if (velMap) { flock.midi.controller.setMappedValue(vel, velMap, synthContext); } }; }()); ;/* * Flocking Core Unit Generators * http://github.com/colinbdclark/flocking * * Copyright 2011-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; var $ = fluid.registerNamespace("jQuery"); flock.isUGen = function (obj) { return obj && obj.tags && obj.tags.indexOf("flock.ugen") > -1; }; // TODO: Check API; write unit tests. flock.aliasUGen = function (sourcePath, aliasName, inputDefaults, defaultOptions) { var root = flock.get(sourcePath); flock.set(root, aliasName, function (inputs, output, options) { options = $.extend(true, {}, defaultOptions, options); return root(inputs, output, options); }); fluid.defaults(sourcePath + "." + aliasName, inputDefaults); }; // TODO: Check API; write unit tests. flock.aliasUGens = function (sourcePath, aliasesSpec) { var aliasName, settings; for (aliasName in aliasesSpec) { settings = aliasesSpec[aliasName]; flock.aliasUGen(sourcePath, aliasName, {inputs: settings.inputDefaults}, settings.options); } }; flock.krMul = function (numSamps, output, mulInput) { var mul = mulInput.output[0], i; for (i = 0; i < numSamps; i++) { output[i] = output[i] * mul; } }; flock.mul = function (numSamps, output, mulInput) { var mul = mulInput.output, i; for (i = 0; i < numSamps; i++) { output[i] = output[i] * mul[i]; } }; flock.krAdd = function (numSamps, output, mulInput, addInput) { var add = addInput.output[0], i; for (i = 0; i < numSamps; i++) { output[i] = output[i] + add; } }; flock.add = function (numSamps, output, mulInput, addInput) { var add = addInput.output, i; for (i = 0; i < numSamps; i++) { output[i] = output[i] + add[i]; } }; flock.krMulAdd = function (numSamps, output, mulInput, addInput) { var mul = mulInput.output[0], add = addInput.output, i; for (i = 0; i < numSamps; i++) { output[i] = output[i] * mul + add[i]; } }; flock.mulKrAdd = function (numSamps, output, mulInput, addInput) { var mul = mulInput.output, add = addInput.output[0], i; for (i = 0; i < numSamps; i++) { output[i] = output[i] * mul[i] + add; } }; flock.krMulKrAdd = function (numSamps, output, mulInput, addInput) { var mul = mulInput.output[0], add = addInput.output[0], i; for (i = 0; i < numSamps; i++) { output[i] = output[i] * mul + add; } }; flock.mulAdd = function (numSamps, output, mulInput, addInput) { var mul = mulInput.output, add = addInput.output, i; for (i = 0; i < numSamps; i++) { output[i] = output[i] * mul[i] + add[i]; } }; flock.onMulAddInputChanged = function (that) { var mul = that.inputs.mul, add = that.inputs.add, fn; // If we have no mul or add inputs, bail immediately. if (!mul && !add) { that.mulAdd = flock.noOp; return; } if (!mul) { // Only add. fn = add.rate !== flock.rates.AUDIO ? flock.krAdd : flock.add; } else if (!add) { // Only mul. fn = mul.rate !== flock.rates.AUDIO ? flock.krMul : flock.mul; } else { // Both mul and add. fn = mul.rate !== flock.rates.AUDIO ? (add.rate !== flock.rates.AUDIO ? flock.krMulKrAdd : flock.krMulAdd) : (add.rate !== flock.rates.AUDIO ? flock.mulKrAdd : flock.mulAdd); } that.mulAdd = function (numSamps) { fn(numSamps, that.output, mul, add); }; }; flock.ugen = function (inputs, output, options) { options = options || {}; var that = { rate: options.rate || flock.rates.AUDIO, inputs: inputs, output: output, options: options, model: options.model || { unscaledValue: 0.0, value: 0.0 }, multiInputs: {}, tags: ["flock.ugen"] }; that.lastOutputIdx = that.output.length - 1; that.get = function (path) { return flock.input.get(that.inputs, path); }; /** * Sets the value of the input at the specified path. * * @param {String} path the inputs's path relative to this ugen * @param {Number || UGenDef} val a scalar value (for Value ugens) or a UGenDef object * @return {UGen} the newly-created UGen that was set at the specified path */ that.set = function (path, val) { return flock.input.set(that.inputs, path, val, that, function (ugenDef) { if (ugenDef === null || ugenDef === undefined) { return; } return flock.parse.ugenDef(ugenDef, { audioSettings: that.options.audioSettings, buses: that.options.buses, buffers: that.options.buffers }); }); }; /** * Gets or sets the named unit generator input. * * @param {String} path the input path * @param {UGenDef} val [optional] a scalar value, ugenDef, or array of ugenDefs that will be assigned to the specified input name * @return {Number|UGen} a scalar value in the case of a value ugen, otherwise the ugen itself */ that.input = function (path, val) { return !path ? undefined : typeof (path) === "string" ? arguments.length < 2 ? that.get(path) : that.set(path, val) : flock.isIterable(path) ? that.get(path) : that.set(path, val); }; // TODO: Move this into a grade. that.calculateStrides = function () { var m = that.model, strideNames = that.options.strideInputs, inputs = that.inputs, i, name, input; m.strides = m.strides || {}; if (!strideNames) { return; } for (i = 0; i < strideNames.length; i++) { name = strideNames[i]; input = inputs[name]; if (input) { m.strides[name] = input.rate === flock.rates.AUDIO ? 1 : 0; } else { fluid.log(fluid.logLevel.WARN, "An invalid input ('" + name + "') was found on a unit generator: " + that); } } }; that.collectMultiInputs = function () { var multiInputNames = that.options.multiInputNames, multiInputs = that.multiInputs, i, inputName, inputChannelCache, input; for (i = 0; i < multiInputNames.length; i++) { inputName = multiInputNames[i]; inputChannelCache = multiInputs[inputName]; if (!inputChannelCache) { inputChannelCache = multiInputs[inputName] = []; } else { // Clear the current array of buffers. inputChannelCache.length = 0; } input = that.inputs[inputName]; flock.ugen.collectMultiInputs(input, inputChannelCache); } }; // Base onInputChanged() implementation. that.onInputChanged = function (inputName) { var multiInputNames = that.options.multiInputNames; flock.onMulAddInputChanged(that); if (that.options.strideInputs) { that.calculateStrides(); } if (multiInputNames && (!inputName || multiInputNames.indexOf(inputName))) { that.collectMultiInputs(); } }; that.init = function () { var tags = fluid.makeArray(that.options.tags), m = that.model, o = that.options, i, s, valueDef; for (i = 0; i < tags.length; i++) { that.tags.push(tags[i]); } s = o.audioSettings = o.audioSettings || flock.environment.audioSystem.model; m.sampleRate = o.sampleRate || s.rates[that.rate]; m.nyquistRate = m.sampleRate; m.blockSize = that.rate === flock.rates.AUDIO ? s.blockSize : 1; m.sampleDur = 1.0 / m.sampleRate; // Assigns an interpolator function to the UGen. // This is inactive by default, but can be used in custom gen() functions. that.interpolate = flock.interpolate.none; if (o.interpolation) { var fn = flock.interpolate[o.interpolation]; if (!fn) { fluid.log(fluid.logLevel.IMPORTANT, "An invalid interpolation type of '" + o.interpolation + "' was specified. Defaulting to none."); } else { that.interpolate = fn; } } if (that.rate === flock.rates.DEMAND && that.inputs.freq) { valueDef = flock.parse.ugenDefForConstantValue(1.0); that.inputs.freq = flock.parse.ugenDef(valueDef); } }; that.init(); return that; }; // The term "multi input" is a bit ambiguous, // but it provides a very light (and possibly poor) abstraction for two different cases: // 1. inputs that consist of an array of multiple unit generators // 2. inputs that consist of a single unit generator that has multiple ouput channels // In either case, each channel of each input unit generator will be gathered up into // an array of "proxy ugen" objects and keyed by the input name, making easy to iterate // over sources of input quickly. // A proxy ugen consists of a simple object conforming to this contract: // {rate: <rate of parent ugen>, output: <Float32Array>} flock.ugen.collectMultiInputs = function (inputs, inputChannelCache) { if (!flock.isIterable(inputs)) { inputs = inputs = fluid.makeArray(inputs); } for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; flock.ugen.collectChannelsForInput(input, inputChannelCache); } return inputChannelCache; }; flock.ugen.collectChannelsForInput = function (input, inputChannelCache) { var isMulti = flock.hasTag(input, "flock.ugen.multiChannelOutput"), channels = isMulti ? input.output : [input.output], i; for (i = 0; i < channels.length; i++) { inputChannelCache.push({ rate: input.rate, output: channels[i] }); } return inputChannelCache; }; flock.ugen.lastOutputValue = function (numSamps, out) { return out[numSamps - 1]; }; /** * Mixes buffer-related functionality into a unit generator. */ flock.ugen.buffer = function (that) { that.onBufferInputChanged = function (inputName) { var m = that.model, inputs = that.inputs; if (m.bufDef !== inputs.buffer || inputName === "buffer") { m.bufDef = inputs.buffer; flock.parse.bufferForDef(m.bufDef, that, flock.environment); // TODO: Shared enviro reference. } }; that.setBuffer = function (bufDesc) { that.buffer = bufDesc; if (that.onBufferReady) { that.onBufferReady(bufDesc); } }; that.initBuffer = function () { // Start with a zeroed buffer, since the buffer input may be loaded asynchronously. that.buffer = that.model.bufDef = flock.bufferDesc({ format: { sampleRate: that.options.audioSettings.rates.audio }, data: { channels: [new Float32Array(that.output.length)] } }); }; }; flock.ugen.value = function (inputs, output, options) { var that = flock.ugen(inputs, output, options); that.value = function () { return that.model.value; }; that.dynamicGen = function (numSamps) { var out = that.output, m = that.model; for (var i = 0; i < numSamps; i++) { out[i] = m.unscaledValue; } that.mulAdd(numSamps); m.value = flock.ugen.lastOutputValue(numSamps, out); }; that.onInputChanged = function () { var inputs = that.inputs, m = that.model; m.value = m.unscaledValue = inputs.value; if (that.rate !== "constant") { that.gen = that.dynamicGen; } else { that.gen = undefined; } flock.onMulAddInputChanged(that); that.dynamicGen(1); }; that.onInputChanged(); return that; }; fluid.defaults("flock.ugen.value", { rate: "control", inputs: { value: 1.0, mul: null, add: null }, ugenOptions: { model: { unscaledValue: 1.0, value: 1.0 }, tags: ["flock.ugen.valueType"] } }); flock.ugen.silence = function (inputs, output, options) { var that = flock.ugen(inputs, output, options); that.onInputChanged = function () { for (var i = 0; i < that.output.length; i++) { that.output[i] = 0.0; } }; that.onInputChanged(); return that; }; fluid.defaults("flock.ugen.silence", { rate: "constant" }); flock.ugen.passThrough = function (inputs, output, options) { var that = flock.ugen(inputs, output, options); that.gen = function (numSamps) { var m = that.model, source = that.inputs.source.output, out = that.output, i, val; for (i = 0; i < source.length; i++) { out[i] = val = source[i]; } for (; i < numSamps; i++) { out[i] = val = 0.0; } m.unscaledValue = val; that.mulAdd(numSamps); m.value = flock.ugen.lastOutputValue(numSamps, out); }; that.onInputChanged(); return that; }; fluid.defaults("flock.ugen.passThrough", { rate: "audio", inputs: { source: null, mul: null, add: null } }); flock.ugen.out = function (inputs, output, options) { var that = flock.ugen(inputs, output, options); // TODO: Implement a "straight out" gen function for cases where the number // of sources matches the number of output buses (i.e. where no expansion is necessary). // TODO: This function is marked as unoptimized by the Chrome profiler. that.gen = function (numSamps) { var m = that.model, sources = that.multiInputs.sources, buses = that.options.buses, bufStart = that.inputs.bus.output[0], expand = that.inputs.expand.output[0], numSources, numOutputBuses, i, j, source, rate, bus, inc, outIdx; numSources = sources.length; numOutputBuses = Math.max(expand, numSources); if (numSources < 1) { return; } for (i = 0; i < numOutputBuses; i++) { source = sources[i % numSources]; rate = source.rate; bus = buses[bufStart + i]; inc = rate === flock.rates.AUDIO ? 1 : 0; outIdx = 0; for (j = 0; j < numSamps; j++, outIdx += inc) { // TODO: Support control rate interpolation. // TODO: Don't attempt to write to buses beyond the available number. // Provide an error at onInputChanged time if the unit generator is configured // with more sources than available buffers. bus[j] = bus[j] + source.output[outIdx]; } } // TODO: Consider how we should handle "value" when the number // of input channels for "sources" can be variable. // In the meantime, we just output the last source's last sample. m.value = m.unscaledValue = source.output[outIdx]; that.mulAdd(numSamps); // TODO: Does this even work? }; that.init = function () { that.sourceBuffers = []; that.onInputChanged(); }; that.init(); return that; }; fluid.defaults("flock.ugen.out", { rate: "audio", inputs: { sources: null, bus: 0, expand: 2 }, ugenOptions: { tags: ["flock.ugen.outputType"], multiInputNames: ["sources"] } }); // Note: this unit generator currently only outputs values at control rate. // TODO: Unit tests. flock.ugen.valueOut = function (inputs, output, options) { var that = flock.ugen(inputs, output, options); that.arraySourceGen = function () { var m = that.model, sources = that.inputs.sources, i; for (i = 0; i < sources.length; i++) { m.value[i] = sources[i].output[0]; } }; that.ugenSourceGen = function () { that.model.value = that.model.unscaledValue = that.inputs.sources.output[0]; }; that.onInputChanged = function () { var m = that.model, sources = that.inputs.sources; if (flock.isIterable(sources)) { that.gen = that.arraySourceGen; m.value = new Float32Array(sources.length); m.unscaledValue = m.value; } else { that.gen = that.ugenSourceGen; } }; that.onInputChanged(); return that; }; fluid.defaults("flock.ugen.valueOut", { rate: "control", inputs: { sources: null }, ugenOptions: { model: { unscaledValue: null, value: null }, tags: ["flock.ugen.outputType", "flock.ugen.valueType"] } }); // TODO: fix naming. // TODO: Make this a proper multiinput ugen. flock.ugen["in"] = function (inputs, output, options) { var that = flock.ugen(inputs, output, options); that.singleBusGen = function (numSamps) { var m = that.model, out = that.output; flock.ugen.in.readBus(numSamps, out, that.inputs.bus, that.options.buses); m.unscaledValue = flock.ugen.lastOutputValue(numSamps, out); that.mulAdd(numSamps); m.value = flock.ugen.lastOutputValue(numSamps, out); }; that.multiBusGen = function (numSamps) { var m = that.model, busesInput = that.inputs.bus, enviroBuses = that.options.buses, out = that.output, i, j, busIdx, val; for (i = 0; i < numSamps; i++) { val = 0; // Clear previous output values before summing a new set. for (j = 0; j < busesInput.length; j++) { busIdx = busesInput[j].output[0] | 0; val += enviroBuses[busIdx][i]; } out[i] = val; } m.unscaledValue = val; that.mulAdd(numSamps); m.value = flock.ugen.lastOutputValue(numSamps, out); }; that.onInputChanged = function () { that.gen = flock.isIterable(that.inputs.bus) ? that.multiBusGen : that.singleBusGen; flock.onMulAddInputChanged(that); }; that.onInputChanged(); return that; }; flock.ugen.in.readBus = function (numSamps, out, busInput, buses) { var busNum = busInput.output[0] | 0, bus = buses[busNum], i; for (i = 0; i < numSamps; i++) { out[i] = bus[i]; } }; fluid.defaults("flock.ugen.in", { rate: "audio", inputs: { bus: 0, mul: null, add: null } }); flock.ugen.audioIn = function (inputs, output, options) { var that = flock.ugen(inputs, output, options); that.gen = function (numSamps) { var m = that.model, out = that.output, bus = that.bus, i, val; for (i = 0; i < numSamps; i++) { out[i] = val = bus[i]; } m.unscaledValue = val; that.mulAdd(numSamps); m.value = flock.ugen.lastOutputValue(numSamps, out); }; that.onInputChanged = function () { flock.onMulAddInputChanged(that); }; that.init = function () { // TODO: Direct reference to the shared environment. var busNum = flock.environment.audioStrategy.inputDeviceManager.openAudioDevice(options); that.bus = that.options.buses[busNum]; that.onInputChanged(); }; that.init(); return that; }; fluid.defaults("flock.ugen.audioIn", { rate: "audio", inputs: { mul: null, add: null } }); }()); ; window.fluid = fluid; return flock; }));
export var castShadowUniforms = { lightViewProjectionMatrix: { value: new THREE.Matrix4() } };
//es5 console.log("hello".indexOf("h") === 0); console.log("hello".indexOf("o") === ("hello".length - 1)); console.log("hello".indexOf("l") !== -1); //es6
require.config({ baseUrl: "/base/src/", deps: ["specRunner"] });
/** * The PlaceService class manages places in the application. * * A place is just the current state of the application which can be * represented as an Object or a URL. For example, the place associated with: * * http://localhost:5000/map/6/2/17/ALL/terrain/loss * * Can also be represented like this: * * zoom - 6 * lat - 2 * lng - 17 * iso - ALL * maptype - terrain * baselayers - loss * * The PlaceService class handles the following use cases: * * 1) New route updates views * * The Router receives a new URL and all application views need to be updated * with the state encoded in the URL. * * Here the router publishes the "Place/update" event passing in the route * name and route parameters. The PlaceService handles the event by * standardizing the route parameters and publishing them in a "Place/go" * event. Any presenters listening to the event receives the updated * application state and can update their views. * * 2) Updated view updates URL * * A View state changes (e.g., a new map zoom) and the URL needs to be * updated, not only with its new state, but from the state of all views in * the application that provide state for URLs. * * Here presenters publishe the "Place/register" event passing in a * reference to themselves. The PlaceService subscribes to the * "Place/register" event so that it can keep references to all presenters * that provide state. Then the view publishes the "Place/update" event * passing in a "go" parameter. If "go" is false, the PlaceService will * update the URL. Otherwise it will publish the "Place/go" event which will * notify all subscribed presenters. * * @return {PlaceService} The PlaceService class */ define([ 'underscore', 'mps', 'uri', 'map/presenters/PresenterClass', 'map/services/LayerSpecService' ], function (_, mps, UriTemplate, PresenterClass, layerSpecService) { 'use strict'; var urlDefaultsParams = { baselayers: 'loss,forestgain', zoom: 3, lat: 15, lng: 27, maptype: 'grayscale', iso: 'ALL' }; var PlaceService = PresenterClass.extend({ _uriTemplate: '{name}{/zoom}{/lat}{/lng}{/iso}{/maptype}{/baselayers}{/sublayers}{?geojson,wdpaid,begin,end,threshold,dont_analyze,hresolution}', /** * Create new PlaceService with supplied Backbone.Router. * * @param {Backbond.Router} router Instance of Backbone.Router */ init: function(router) { this.router = router; this._presenters = []; this._name = null; this._presenters.push(layerSpecService); // this makes the test fail this._super(); }, /** * Subscribe to application events. */ _subscriptions: [{ 'Place/register': function(presenter) { this._presenters = _.union(this._presenters, [presenter]); } }, { 'Place/update': function() { this._updatePlace(); } }], /** * Init by the router to set the name * and publish the first place. * * @param {String} name Place name * @param {Object} params Url params */ initPlace: function(name, params) { this._name = name; this._newPlace(params); }, /** * Silently updates the url from the presenter params. */ _updatePlace: function() { var route, params; params = this._destandardizeParams( this._getPresenterParams(this._presenters)); route = this._getRoute(params); this.router.navigateTo(route, {silent: true}); }, /** * Handles a new place. * * @param {Object} params The place parameters */ _newPlace: function(params) { var where, place = {}; place.params = this._standardizeParams(params); where = _.union(place.params.baselayers, place.params.sublayers); layerSpecService.toggle( where, _.bind(function(layerSpec) { place.layerSpec = layerSpec; mps.publish('Place/go', [place]); }, this) ); }, /** * Return route URL for supplied route name and route params. * * @param {Object} params The route params * @return {string} The route URL */ _getRoute: function(param) { var url = new UriTemplate(this._uriTemplate).fillFromObject(param); return decodeURIComponent(url); }, /** * Return standardized representation of supplied params object. * * @param {Object} params The params to standardize * @return {Object} The standardized params. */ _standardizeParams: function(params) { var p = _.extendNonNull({}, urlDefaultsParams, params); p.name = this._name; p.baselayers = _.map(p.baselayers.split(','), function(slug) { return {slug: slug}; }); p.sublayers = p.sublayers ? _.map(p.sublayers.split(','), function(id) { return {id: _.toNumber(id)}; }) : []; p.zoom = _.toNumber(p.zoom); p.lat = _.toNumber(p.lat); p.lng = _.toNumber(p.lng); p.iso = _.object(['country', 'region'], p.iso.split('-')); p.begin = p.begin ? p.begin.format('YYYY-MM-DD') : null; p.end = p.end ? p.end.format('YYYY-MM-DD') : null; p.geojson = p.geojson ? JSON.parse(decodeURIComponent(p.geojson)) : null; p.wdpaid = p.wdpaid ? _.toNumber(p.wdpaid) : null; p.threshold = p.threshold ? _.toNumber(p.threshold) : null; p.subscribe_alerts = (p.subscribe_alerts === 'subscribe') ? true : null; p.referral = p.referral; p.hresolution = p.hresolution; return p; }, /** * Return formated URL representation of supplied params object based on * a route name. * * @param {Object} params Place to standardize * @return {Object} Params ready for URL */ _destandardizeParams: function(params) { var p = _.extendNonNull({}, urlDefaultsParams, params); var baselayers = _.pluck(p.baselayers, 'slug'); p.name = this._name; p.baselayers = (baselayers.length > 0) ? baselayers : 'none'; p.sublayers = p.sublayers ? p.sublayers.join(',') : null; p.zoom = String(p.zoom); p.lat = p.lat.toFixed(2); p.lng = p.lng.toFixed(2); p.iso = _.compact(_.values(p.iso)).join('-') || 'ALL'; p.begin = p.begin ? p.begin.format('YYYY-MM-DD') : null; p.end = p.end ? p.end.format('YYYY-MM-DD') : null; p.geojson = p.geojson ? encodeURIComponent(p.geojson) : null; p.wdpaid = p.wdpaid ? String(p.wdpaid) : null; p.threshold = p.threshold ? String(p.threshold) : null; p.hresolution = p.hresolution; return p; }, /** * Return param object representing state from all registered presenters * that implement getPlaceParams(). * * @param {Array} presenters The registered presenters * @return {Object} Params representing state from all presenters */ _getPresenterParams: function(presenters) { var p = {}; _.each(presenters, function(presenter) { _.extend(p, presenter.getPlaceParams()); }, this); return p; } }); return PlaceService; });
(function() { 'use strict'; angular .module('<%= scriptAppName %>') .service('<%= cameledName %>', <%= cameledName %>); /* @ngInject */ function <%= cameledName %>() { this.api01 = method; function method() { } } })();
import React from "react"; import { observer, Observer } from "mobx-react"; import styled from "styled-components"; import { Helmet } from "react-helmet"; import LevelPlay from "./LevelPlay"; import LevelMenu from "./LevelMenu"; import LevelEditor from "./LevelEditor"; import { AppDiv } from "./Style"; import State from "./State"; import { getGameStore } from "../stores"; const defaultStore = getGameStore(); const creditSiteLink = "http://www.onlinespiele-sammlung.de/sokoban/sokobangames/skinner"; const Banner = styled.section` display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; background: darkorchid; color: #eee; padding: 0 0.2345rem; height: ${props => props.height}; box-shadow: 1.11px 1.11px 1.11px 1.11px #aaa; text-shadow: -1px -1px 0 #333, 1px -1px 0 #333, -1px 1px 0 #333, 1px 1px 0 #333; & nav { width: 620px; max-width: 100vw; padding: 0 6.54321px; display: flex; justify-content: space-between; align-items: center; font-size: 2.1212rem; } & .icon { font-weight: bold; cursor: pointer; font-size: 3.14159rem; } & h1 { font-size: 3.1415rem; font-weight: normal; } & a { text-decoration: none; color: paleturquoise; } `; const Help = styled.div` position: relative; cursor: pointer; min-width: 2rem; & .hint { text-shadow: none; position: absolute; right: 0; z-index: 9999; padding: 12.345px; width: 432px; max-width: 90vw; text-align: left; font-size: 1.3579rem; color: #333; background: #fafafa; box-shadow: 1.11px 1.11px 1.11px 1.11px #aaa; } `; const helpEl = ( <State init={me => { me.state = { show: false }; me.toggle = () => me.setState({ show: !me.state.show }); }} > {me => ( <Help onClick={me.toggle} title="Editor Help"> ? {me.state.show && <div className="hint" onClick={me.toggle}> Select a square by tapping it, or move it with arrow keys. <br /> <br /> Tap the square again to toggle through items, or use the buttons to place them at the square. <br /> <br /> You can zoom in for easier editing. </div>} </Help> )} </State> ); // TODO: banner should really just be moved into corresponding pages const BannerSwitch = ({ store }) => { const confirmAndGoBack = () => { const confirmed = confirm("Leave without saving?"); if (confirmed) { store.editorStore.goBack(); } }; switch (store.state.currentView) { case "MENU": return ( <Banner height="6.78em"> <h1 className="title">Sokoban</h1> <a href={creditSiteLink} rel="noopener noreferrer" target="_blank"> Featuring Levels Designed by David W. Skinner </a> <div>By Ron ChanOu</div> <div> Full website coming soon! Source viewable {" "} <a href="https://www.github.com/rchanou/website">here</a> </div> </Banner> ); case "PLAY": return ( <Banner> <nav> <div className="icon title" onClick={store.levelPlayStore.goBack} title="Return to Puzzle Menu" > ⌂ </div> <div className="title"> Moves: <Observer> {() => store.levelPlayStore.state.moveCount} </Observer> </div> <div title="Edit Puzzle" className="icon title" onClick={store.levelPlayStore.gotoEditor} > ✎ </div> </nav> </Banner> ); case "EDITOR": return ( <Banner> <nav style={{ width: 720 }}> <div className="icon" onClick={confirmAndGoBack} title="Return to Previous Page" > ⇐ </div> <div>Editor</div> {helpEl} </nav> </Banner> ); default: } }; const Game = observer(({ store = defaultStore }) => { let ViewToRender, storeToUse; switch (store.state.currentView) { case "MENU": ViewToRender = LevelMenu; storeToUse = store.menuStore; break; case "PLAY": ViewToRender = LevelPlay; storeToUse = store.levelPlayStore; break; case "EDITOR": ViewToRender = LevelEditor; storeToUse = store.editorStore; break; default: ViewToRender = LevelPlay; storeToUse = store.levelPlayStore; } return ( <AppDiv> <Helmet> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> </Helmet> <BannerSwitch store={store} /> <ViewToRender store={storeToUse} /> </AppDiv> ); }); export default Game;
/** * * Popup * */ import React, { Children } from 'react'; import { StyledPopup, PopupContent, PopupBackDrop, PopupBtn, } from './styles'; export class Popup extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { visible: false, }; this.changeVisible = this.changeVisible.bind(this); this.hide = this.hide.bind(this); } changeVisible() { this.setState({ visible: !this.state.visible }); } hide() { this.setState({ visible: false }); } render() { let content; if (this.props.isControlled) { content = this.props.isVisible && ( <div> <PopupBackDrop onClick={this.props.handleClickOnBackdrop} /> <PopupContent onClick={(event) => event.stopPropagation()}> {Children.toArray(this.props.children)} </PopupContent> </div> ); } else { content = ( <div> <PopupBtn onClick={this.changeVisible} style={this.props.btnStyles}>{this.props.btnSign}</PopupBtn> {this.state.visible && <div> <PopupBackDrop onClick={this.hide} /> <PopupContent> {Children.toArray(this.props.children)} </PopupContent> </div> } </div> ); } return ( <StyledPopup> {content} </StyledPopup> ); } } Popup.propTypes = { isControlled: React.PropTypes.bool, isVisible: React.PropTypes.bool, btnSign: React.PropTypes.string, btnStyles: React.PropTypes.object, handleClickOnBackdrop: React.PropTypes.func, children: React.PropTypes.object, }; Popup.defaultProps = { isControlled: false, isVisible: false, btnSign: 'Popup button', btnStyles: {}, handleClickOnBackdrop: () => {}, }; export default Popup;
import * as firebase from 'firebase' export default { state: { loadedCustomProject: [] }, mutations: { setLoadedCustomProject (state, payload) { state.loadedCustomProject = payload }, updateCustomProject (state, payload) { state.loadedCustomProject.widgetTitle = payload.widgetTitle state.loadedCustomProject.description = payload.description state.loadedCustomProject.img = payload.img state.loadedCustomProject.prePriceText = payload.prePriceText state.loadedCustomProject.price = payload.price } }, actions: { loadCustomProject ({commit}) { commit('setLoading', true) firebase.database().ref('customProject').once('value') .then((data) => { const content = data.val() commit('setLoadedCustomProject', content) commit('setLoading', false) }) .catch( (error) => { console.log(error) commit('setLoading', false) } ) }, updateCustomProject ({ commit }, payload) { const updateObj = {} updateObj.widgetTitle = payload.widgetTitle updateObj.description = payload.description updateObj.img = payload.img updateObj.prePriceText = payload.prePriceText updateObj.price = payload.price firebase.database().ref('customProject').update(updateObj) .then(() => { commit('updateCustomProject', payload) }) .catch((error) => { console.log(error) }) } }, getters: { loadedCustomProject (state) { return state.loadedCustomProject } } }
const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const webpackConfig = require('./webpack.config'); const path = require('path'); const express = require('express'); const parser = require('body-parser'); const route = require('./server/routes/'); const swaggerSpec = require('./server/routes/swaggerRoutes'); require('dotenv').config(); const app = express(); if (process.env.NODE_ENV !== 'test') { const compiler = webpack(webpackConfig); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } app.use(express.static(path.join(__dirname, 'client/'))); app.get('/app/*', (req, res) => { res.sendFile(`${__dirname}/client/index.html`); }); const port = process.env.PORT || 4000; app.use(parser.urlencoded({ extended: true })); app.use(parser.json()); app.use('/', route.userRouter); app.use('/', route.roleRouter); app.use('/', route.documentRouter); app.get('/doc', (req, res) => { res.status(200) .sendFile(path.join(__dirname, 'server/Swagger', 'index.html')); }); app.get('/swagger.json', (req, res) => { res.setHeader('Content-Type', 'application/json'); res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With'); res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS'); res.json(swaggerSpec); }); app.use(express.static(path.join(__dirname, 'server/Swagger'))); app.listen(port, () => { console.log(`Server started on ${port}`); }); module.exports = app;
/*jslint node: true */ /*jslint esversion: 6 */ var os = require('os'); var pageviewCounter = 0, pageviewCounters = [], sysMemory = new Array(45), sysCPU = new Array(45), saveSysLoadtimer; /** * Convert seconds into a days hh:nn:ss format * @param {integer} seconds * @return {string} */ function secondsToTimeString(seconds) { var days = Math.floor(seconds / 3600 / 24); var hours = Math.floor((seconds - (days * 24 * 3600)) / 3600); var minutes = Math.floor((seconds - (days * 24 * 3600) - (hours * 3600)) / 60); var sec = seconds - (days * 24 * 3600) - (hours * 3600) - (minutes * 60); sec = Math.round(sec); if (hours < 10) {hours = '0'+hours;} if (minutes < 10) {minutes = '0'+minutes;} if (sec < 10) {sec = '0'+sec;} return days + 'd ' + hours+':'+minutes+':'+sec; } /** * Take a set of values and create an SVG chart * @param {array} points * @param {object} options - options for this function, maxVal: for the Y axis, xLabel:, yLabel:, yMarkerSuffix: units tp show after marker values * @return {string} */ function memChart(points, options) { /// points must have most recent value first /// xmin etc are all pixels for chart size, maxVal is the scale so the max mamory var out, xmin = 40, xmax = 400, ymin = 30, ymax = 300, yaxis, _points; try { options = options || {}; options.maxVal = options.maxVal || 150; options.xLabel = options.xLabel || ''; options.yLabel = options.yLabel || ''; options.yMarkerSuffix = options.yMarkerSuffix || ''; yaxis = new Array(options.maxVal/10); _points = points.map(function(point, pointNum) { pointx = xmax - pointNum * (xmax-xmin)/points.length; pointy = ymax - ymin - (point * (ymax-ymin)/options.maxVal); // pointy = 300 - (80/120 * (300-20)); if (pointy) { return String(pointx) + ',' + String(Math.round(pointy)); } }).filter(function(point) { if (point && point.indexOf('NaN') === -1) { return true; } }); /// Build the labels for the Y axis for (var i = 0; i < (options.maxVal / 10) + 1; i++) { if (options.maxVal > 190 && i%2 !== 0) { continue; } /// +4 on the next line is to allow mark to be in the middle of the number yaxis[i] = '<text x="39" y="'+ String(Math.round(ymax -ymin + 5 - ((10*i) * (ymax-ymin))/options.maxVal)) + '">'+ i*10 + options.yMarkerSuffix + '</text>'; } out = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="chart" aria-labelledby="title" role="img"> <title id="title">A line chart showing server stats</title> <g class="grid x-grid" id="xGrid"> <line x1="40" x2="40" y1="5" y2="280"></line> </g> <g class="grid y-grid" id="yGrid"> <line x1="40" x2="400" y1="280" y2="280"></line> </g> <g class="labels x-labels"> <text x="40" y="292">-15</text> <text x="160" y="292">-10</text> <text x="280" y="292">-5</text> <text x="390" y="292">-0</text> <text x="200" y="299" class="label-x">`; out += options.xLabel; out += `</text> </g> <g class="labels y-labels">`; out += yaxis.join('\n'); out += '<text x="-140" y="10" class="label-y">'; out += options.yLabel; out += `</text> </g> <polyline fill="none" stroke="#0074d9" stroke-width="2" points="`; out += _points.join('\n'); out += ` " /> </svg>`; } catch(err) { console.log('express-sysinfo error'); console.log(err); out = 'Chart error'; } return out; } function chartCss() { var out = `<style> .chart { background: white; height: 300px; width: 400px; /*padding: 20px 20px 20px 0;*/ } .chart .labels.x-labels { text-anchor: middle; } .chart .labels.y-labels { text-anchor: end; } .chart .grid { stroke: #ccc; stroke-dasharray: 0; stroke-width: 1; } .labels { font-size: 12px; } .label-y { font-weight: bold; transform: rotate(270deg); transform-origin: right top 0; float: left; } .label-x { font-weight: bold; } table { border-collapse: collapse; border-spacing: 0; } table tbody { display: table-row-group; } table tr { display: table-row; } table tr:nth-child(odd) td { background-color: #F6F6F6; } table thead { display: table-header-group; } table td, th { display: table-cell; border: 1px solid #CCC; padding: 2px 10px; text-align: left; } </style> `; return out; } /** * Turn the info object into basic HTML * @param {object} info - info object from sysInfo function * @param {object} options - options passed in from the calling app * @return {string} */ function outTable(info, options) { var out; try { out = '<!DOCTYPE html>\n<html>\n<head>\n<title>Server info</title>\n'; out += chartCss(); out += '</head>\n<body>\n<table>\n<thead>\n<tr><th>Measure name</th><th>Value</th></tr>\n</thead>\n<tbody>\n'; out += '<tr><td>OS hostname</td><td>'; out += info.osHostname; out += '</td></tr>\n<tr><td>OS free memory</td><td>'; out += info.osFreemem; out += ' mb</td></tr>\n<tr><td>OS total memory</td><td>'; out += info.osTotalmem; out += ' mb</td></tr>\n<tr><td>OS uptime</td><td>'; out += info.osUptime; if (os.platform() !== 'win32') { out += '</td></tr>\n<tr><td>OS load average 1 min</td><td>'; out += info.osLoadav1; out += '</td></tr>\n<tr><td>OS load average 5 min</td><td>'; out += info.osLoadav5; out += '</td></tr>\n<tr><td>OS load average 15 min</td><td>'; out += info.osLoadav15; } out += '</td></tr>\n<tr><td>Process memory usage resident set size</td><td>'; out += info.procMemoryusageRss; out += ' mb</td></tr>\n<tr><td>Process memory usage heap total</td><td>'; out += info.procMemoryusageHeaptotal; out += ' mb</td></tr>\n<tr><td>Process memory usage heap used</td><td>'; out += info.procMemoryusageHeapused; out += ' mb</td></tr>\n<tr><td>Process Node version</td><td>'; out += info.procVersionsNode; out += '</td></tr>\n<tr><td>Process V8 version</td><td>'; out += info.procVersionsV8; out += '</td></tr>\n<tr><td>Process OpenSSL version</td><td>'; out += info.procVersionsOpenssl; out += '</td></tr>\n<tr><td>Process uptime</td><td>'; out += info.procUptime; if (info.procPageviewsSec) { out += '</td></tr>\n<tr><td>Current page views/second</td><td>'; out += info.procPageviewsSec; out += '</td></tr>\n<tr><td>Average pageviews/second 15 mins</td><td>'; out += info.procPageviewsSec15; out += '</td></tr>\n<tr><td>Average pageviews/second 60 mins</td><td>'; out += info.procPageviewsSec60; } out += '</td></tr>\n</tbody>\n</table>\n'; out += '<p>Process memory usage in the past 15 minutes</p>\n'; out += memChart(sysMemory, { maxVal: options.maxMemoryToDisplay, xLabel:'Minutes', yLabel: 'Process memory (RSS)', yMarkerSuffix: 'mb' }); if (os.platform() !== 'win32') { out += '<p>CPU usage in the past 15 minutes</p>\n'; out += memChart(sysCPU, { maxVal: 100, xLabel:'Minutes', yLabel: 'CPU', yMarkerSuffix: '%' }); } out += '</body>\n</html>'; } catch (err) { console.log('express-sysinfo error'); console.log(err); out = 'Chart error'; } return out; } /** * Save the current resident set memory size and CPU load into an array */ function saveSysLoad() { try { var len = sysMemory.length-1; while (len) { sysMemory[len] = sysMemory[len-1]; len--; } sysMemory[0] = Math.round(process.memoryUsage().rss/1024/1024); /// CPU if (os.platform() !== 'win32') { len = sysCPU.length-1; while (len) { sysCPU[len] = sysCPU[len-1]; len--; } sysCPU[0] = os.loadavg()[0]; } } catch (err) { console.log('express-sysinfo error'); console.log(err); } } /** * Clears the page view counter and stores the result * @param {integer} imterval - time between clearing counter in milliseconds */ function cleardown(interval) { // Array manipulation as suggested by https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ setInterval(function() { var len = pageviewCounters.length; while (len) { pageviewCounters[len] = pageviewCounters[len-1]; len--; } pageviewCounters[0] = pageviewCounter; pageviewCounter = 0; if (pageviewCounters.length > 60*3600*1000/interval) { pageviewCounters.length = 60*3600*1000/interval; } }, interval); } /** * Get a function which matches the standard Express handler. The inner function gets system information and sends it out on the response * @param {object} options - map of available options. cleardownInterval, returnFormat, viewerUrl, viewOnly, countOnly * */ function sysInfo (options) { options = options || {}; options.cleardownInterval = options.cleardownInterval || 3000; options.returnFormat = options.returnFormat || 'HTML'; options.viewerUrl = options.viewerUrl || '/sysinfo'; options.maxMemoryToDisplay = options.maxMemoryToDisplay || 150; if (options.cleardownInterval > 15*60*1000) { console.log('cleardownInterval can\'t be more than 15 minutes.'); options.cleardownInterval = 15*60*1000; } if (options.viewOnly !== true) { cleardown(options.cleardownInterval); } if (saveSysLoadtimer === undefined) { setTimeout(saveSysLoad, 200); // run once after the app has loaded, rather arbitrary 200ms saveSysLoadtimer = setInterval(saveSysLoad, 20*1000); // Every 20 seconds. If this changes the array size should be cahnged too (declared at the top.) } return function (req, res, next) { try { /// Show the info if (req.url === options.viewerUrl && req.method === 'GET' && options.countOnly !== true) { var procPageviews = 0, procPageviewsSec = 0, procPageviewsSec1 = 0, procPageviewsSec5 = 0, procPageviewsSec15 = 0, procPageviewsSec60 = 0; for(var i = 0, l = pageviewCounters.length; i < l; i++) { procPageviews+= pageviewCounters[i]; if (i <= Math.round(15 / (options.cleardownInterval/1000))) { // 15 second average procPageviewsSec = procPageviews / 15; } if (i <= Math.round(60 / (options.cleardownInterval/1000))) { //1 minute average procPageviewsSec1 = procPageviews / 60; } if (i <= Math.round(5*60 / (options.cleardownInterval/1000))) { //5 minute average procPageviewsSec5 = procPageviews / 300; } if (i <= Math.round(15*60 / (options.cleardownInterval/1000))) { //15 minute average procPageviewsSec15 = procPageviews / 900; } if (i <= Math.round(3600 / (options.cleardownInterval/1000))) { //60 minute average procPageviewsSec60 = procPageviews / 3600; } } var info = { osHostname: os.hostname(), osFreemem: Math.round(os.freemem()/1024/1024), osTotalmem: Math.round(os.totalmem()/1024/1024), osLoadav1: os.loadavg()[0], osLoadav5: os.loadavg()[1], osLoadav15: os.loadavg()[2], osUptime: secondsToTimeString(os.uptime()), procMemoryusageRss: Math.round(process.memoryUsage().rss/1024/1024), procMemoryusageHeaptotal: Math.round(process.memoryUsage().heapTotal/1024/1024), procMemoryusageHeapused: Math.round(process.memoryUsage().heapUsed/1024/1024), procVersionsNode: process.versions.node, procVersionsV8: process.versions.v8, procVersionsOpenssl: process.versions.openssl, procUptime: secondsToTimeString(process.uptime()), }; if (pageviewCounters.length > 0) { info.procPageviewsSec = procPageviewsSec.toFixed(1); info.procPageviewsSec1 = procPageviewsSec1.toFixed(1); info.procPageviewsSec5 = procPageviewsSec5.toFixed(1); info.procPageviewsSec15 = procPageviewsSec15.toFixed(1); info.procPageviewsSec60 = procPageviewsSec60.toFixed(1); } if (options.returnFormat === 'HTML') { res.send(outTable(info, options)); res.end(); } else if (options.returnFormat === 'JSON') { res.send(info); res.end(); } else { res.render(options.returnFormat, info); } } else if (options.viewOnly !== true) { /// Log a page view pageviewCounter++; next(); } else { console.log('sysInfo settings mismatch.'); next(); } } catch (err) { return next(err); } }; } module.exports = sysInfo;
var fire = require("../../../../../index.js") var Expression = fire.Expression function expressionModule2() { } expressionModule2.prototype = new Expression() expressionModule2.prototype.execute = function() { this._blockContext._resultCallback("Hello World expressionModule2") } var fireModule = fire.igniteModule(module, require) fireModule.exportExpression({ name: "expressionModule2", implementation: expressionModule2 })
const arr10000 = new Array(10000).fill(0); const arr100 = new Array(100).fill(0); const arr10 = new Array(10).fill(0); module.exports = [ { input: [arr100], output: undefined } ];
/** * @class CM_Layout_Abstract * @extends CM_View_Abstract */ var CM_Layout_Abstract = CM_View_Abstract.extend({ /** @type String */ _class: 'CM_Layout_Abstract', /** @type jQuery|Null */ _$pagePlaceholder: null, /** @type jqXHR|Null */ _pageRequest: null, /** * @returns {CM_View_Abstract|null} */ findPage: function() { return this.findChild('CM_Page_Abstract'); }, /** * @returns {CM_View_Abstract} */ getPage: function() { var page = this.findPage(); if (!page) { cm.error.triggerThrow('Layout doesn\'t have a page'); } return page; }, /** * @param {String} path */ loadPage: function(path) { cm.event.trigger('navigate', path); if (!this._$pagePlaceholder) { this._$pagePlaceholder = $('<div class="router-placeholder" />'); this.getPage().replaceWithHtml(this._$pagePlaceholder); this._onPageTeardown(); } else { this._$pagePlaceholder.removeClass('error').html(''); } var timeoutLoading = this.setTimeout(function() { this._$pagePlaceholder.html('<div class="spinner spinner-expanded" />'); }, 750); if (this._pageRequest) { this._pageRequest.abort(); } this._pageRequest = this.ajaxModal('loadPage', {path: path}, { success: function(response) { if (response.redirectExternal) { cm.router.route(response.redirectExternal); return; } var layout = this; this._injectView(response, function(response) { var reload = (layout.getClass() != response.layoutClass); if (reload) { window.location.replace(response.url); return; } layout._$pagePlaceholder.replaceWith(this.$el); layout._$pagePlaceholder = null; var fragment = response.url.substr(cm.getUrl().length); if (path === fragment + window.location.hash) { fragment = path; } window.history.replaceState(null, null, fragment); layout._onPageSetup(this, response.title, response.url, response.menuEntryHashList, response.jsTracking); }); }, error: function(msg, type, isPublic) { this._$pagePlaceholder.addClass('error').html('<pre>' + msg + '</pre>'); this._onPageError(); return false; }, complete: function() { window.clearTimeout(timeoutLoading); } }); }, /** * @param {jQuery} $el */ scrollTo: function($el) { var pageOffsetTop = 0; var page = cm.findView('CM_Page_Abstract'); if (page) { pageOffsetTop = page.$el.offset().top; } $(document).scrollTop($el.offset().top - pageOffsetTop); }, _onPageTeardown: function() { $(document).scrollTop(0); $('.floatbox-layer').floatIn(); }, /** * @param {CM_Page_Abstract} page * @param {String} title * @param {String} url * @param {String[]} menuEntryHashList * @param {String} [jsTracking] */ _onPageSetup: function(page, title, url, menuEntryHashList, jsTracking) { cm.window.title.setText(title); $('[data-menu-entry-hash]').removeClass('active'); var menuEntrySelectors = _.map(menuEntryHashList, function(menuEntryHash) { return '[data-menu-entry-hash=' + menuEntryHash + ']'; }); $(menuEntrySelectors.join(',')).addClass('active'); if (jsTracking) { new Function(jsTracking).call(this); } if (window.location.hash) { var hash = window.location.hash.substring(1); var $anchor = $('#' + hash).add('[name=' + hash + ']'); if ($anchor.length) { this.scrollTo($anchor); } } }, _onPageError: function() { $('[data-menu-entry-hash]').removeClass('active'); } });
(function() { // jsonのキー名。 var ID_KEY = 'id'; var NAME_KEY = 'name'; var app = angular.module('pageSelectorApp', [ 'pageSelectorControllers' ]); var controllers = angular.module('pageSelectorControllers', []); controllers.controller('pageListCtrl', ['$scope', '$http', function($scope, $http) { var editor = window.top.tinymce.EditorManager.activeEditor; var params = editor.windowManager.getParams(); $scope.pages = []; $http.get(params['requestUrl']).success(function(data) { console.log(data); $scope.pages = data; }); $scope.select = function(index) { var page = $scope.pages[index]; var url = "caterpillar://" + page[ID_KEY] var name = page[NAME_KEY]; var callback = params['callback']; callback(url, {text: name, title: name}); editor.windowManager.close(); } }]); })();
var INLINE_LINK = /(\S+)(?:\s+([\s\S]+))?/; var path = require('canonical-path'); var where = require('lodash-node/modern/collections/where'); module.exports = { name: 'link', description: 'Process inline link tags (of the form {@link some/uri Some Title}), replacing them with HTML anchors', handlerFactory: function(docs) { return function handleLinkTags(doc, tagName, tagDescription) { // Parse out the uri and title return tagDescription.replace(INLINE_LINK, function(match, uri, title) { var linkInfo; if (uri.match(/^http(s)?:\/\//)) { // Don't validate external links linkInfo = { href: uri }; } else { linkInfo = where(docs, {codeName: uri}); if (linkInfo.length < 1) { throw new Error('Invalid link: ' + uri); } else if (linkInfo.length > 1) { throw new Error('Ambiguous link: ' + uri); } linkInfo = linkInfo[0]; } return '<a href="' + linkInfo.href + '">' + (title || linkInfo.codeName || uri) + '</a>'; }); }; } };
Search.setIndex({envversion:42,terms:{content:0,index:0,modul:0,search:0,page:0},objtypes:{},objnames:{},filenames:["index"],titles:["Welcome to Foreign Guides&#8217;s documentation!"],objects:{},titleterms:{guid:0,welcom:0,indic:0,foreign:0,tabl:0,document:0}})
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Contact.css'; function Contact({ title }) { return ( <div className={s.root}> <div className={s.container}> <h1>{title} asdf</h1> <p> </p> </div> </div> ); } Contact.propTypes = { title: PropTypes.string.isRequired }; export default withStyles(s)(Contact);
/*! * Image (upload) dialog plugin for Editor.md * * @file image-dialog.js * @author pandao * @version 1.3.4 * @updateTime 2015-06-09 * {@link https://github.com/pandao/editor.md} * @license MIT */ (function() { var factory = function(exports) { var pluginName = 'image-dialog'; exports.fn.imageDialog = function() { var _this = this; var cm = this.cm; var lang = this.lang; var editor = this.editor; var settings = this.settings; var cursor = cm.getCursor(); var selection = cm.getSelection(); var imageLang = lang.dialog.image; var classPrefix = this.classPrefix; var iframeName = classPrefix + 'image-iframe'; var dialogName = classPrefix + pluginName, dialog; cm.focus(); var loading = function(show) { var _loading = dialog.find('.' + classPrefix + 'dialog-mask'); _loading[show ? 'show' : 'hide'](); }; if (editor.find('.' + dialogName).length < 1) { var guid = new Date().getTime(); var action = settings.imageUploadURL + (settings.imageUploadURL.indexOf('?') >= 0 ? '&' : '?') + 'guid=' + guid; if (settings.crossDomainUpload) { action += '&callback=' + settings.uploadCallbackURL + '&dialog_id=editormd-image-dialog-' + guid; } var dialogContent = (settings.imageUpload ? '<form action="' + action + '" target="' + iframeName + '" method="post" enctype="multipart/form-data" class="' + classPrefix + 'form">' : '<div class="' + classPrefix + 'form">') + (settings.imageUpload ? '<iframe name="' + iframeName + '" id="' + iframeName + '" guid="' + guid + '"></iframe>' : '') + '<label>' + imageLang.url + '</label>' + '<input type="text" data-url />' + (function() { return settings.imageUpload ? '<div class="' + classPrefix + 'file-input">' + '<input type="file" name="' + classPrefix + 'image-file" accept="image/*" />' + '<input type="submit" value="' + imageLang.uploadButton + '" />' + '</div>' : ''; })() + '<br/>' + '<label>' + imageLang.alt + '</label>' + '<input type="text" value="' + selection + '" data-alt />' + '<br/>' + '<label>' + imageLang.link + '</label>' + '<input type="text" value="http://" data-link />' + '<br/>' + (settings.imageUpload ? '</form>' : '</div>'); //var imageFooterHTML = "<button class=\"" + classPrefix + "btn " + classPrefix + "image-manager-btn\" style=\"float:left;\">" + imageLang.managerButton + "</button>"; dialog = this.createDialog({ title: imageLang.title, width: settings.imageUpload ? 465 : 380, height: 254, name: dialogName, content: dialogContent, mask: settings.dialogShowMask, drag: settings.dialogDraggable, lockScreen: settings.dialogLockScreen, maskStyle: { opacity: settings.dialogMaskOpacity, backgroundColor: settings.dialogMaskBgColor, }, buttons: { enter: [ lang.buttons.enter, function() { var url = this.find('[data-url]').val(); var alt = this.find('[data-alt]').val(); var link = this.find('[data-link]').val(); if (url === '') { alert(imageLang.imageURLEmpty); return false; } var altAttr = alt !== '' ? ' "' + alt + '"' : ''; if (link === '' || link === 'http://') { cm.replaceSelection( '![' + alt + '](' + url + altAttr + ')' ); } else { cm.replaceSelection( '[![' + alt + '](' + url + altAttr + ')](' + link + altAttr + ')' ); } if (alt === '') { cm.setCursor(cursor.line, cursor.ch + 2); } this.hide() .lockScreen(false) .hideMask(); return false; }, ], cancel: [ lang.buttons.cancel, function() { this.hide() .lockScreen(false) .hideMask(); return false; }, ], }, }); dialog.attr('id', classPrefix + 'image-dialog-' + guid); if (!settings.imageUpload) { return; } var fileInput = dialog.find( '[name="' + classPrefix + 'image-file"]' ); fileInput.bind('change', function() { var fileName = fileInput.val(); var isImage = new RegExp( '(\\.(' + settings.imageFormats.join('|') + '))$' ); // /(\.(webp|jpg|jpeg|gif|bmp|png))$/ if (fileName === '') { alert(imageLang.uploadFileEmpty); return false; } if (!isImage.test(fileName)) { alert( imageLang.formatNotAllowed + settings.imageFormats.join(', ') ); return false; } loading(true); var submitHandler = function() { var uploadIframe = document.getElementById(iframeName); uploadIframe.onload = function() { loading(false); var body = (uploadIframe.contentWindow ? uploadIframe.contentWindow : uploadIframe.contentDocument ).document.body; var json = body.innerText ? body.innerText : body.textContent ? body.textContent : null; json = typeof JSON.parse !== 'undefined' ? JSON.parse(json) : eval('(' + json + ')'); if (json.success === 1) { dialog.find('[data-url]').val(json.url); } else { alert(json.message); } return false; }; }; dialog .find('[type="submit"]') .bind('click', submitHandler) .trigger('click'); }); } dialog = editor.find('.' + dialogName); dialog.find('[type="text"]').val(''); dialog.find('[type="file"]').val(''); dialog.find('[data-link]').val('http://'); this.dialogShowMask(dialog); this.dialogLockScreen(); dialog.show(); }; }; // CommonJS/Node.js if ( typeof require === 'function' && typeof exports === 'object' && typeof module === 'object' ) { module.exports = factory; } else if (typeof define === 'function') { // AMD/CMD/Sea.js if (define.amd) { // for Require.js define(['editormd'], function(editormd) { factory(editormd); }); } else { // for Sea.js define(function(require) { var editormd = require('./../../editormd'); factory(editormd); }); } } else { factory(window.editormd); } })();
import { $TD, $TDX } from "../api/bridge.js"; import { $ } from "../api/jquery.js"; import { replaceFunction } from "../api/patch.js"; import { TD } from "../api/td.js"; import { checkPropertyExists, ensurePropertyExists } from "../api/utils.js"; import { getColumnName } from "./globals/get_column_name.js"; import { checkUserNftStatus, getTweetUserId } from "./globals/user_nft_status.js"; /** * Event callback for a new tweet. * @returns {function(column: TD_Column, tweet: ChirpBase)} */ const onNewTweet = (function() { const recentMessages = new Set(); const recentTweets = new Set(); let recentTweetTimer = null; const resetRecentTweets = () => { recentTweetTimer = null; recentTweets.clear(); }; const startRecentTweetTimer = () => { if (recentTweetTimer) { window.clearTimeout(recentTweetTimer); } recentTweetTimer = window.setTimeout(resetRecentTweets, 20000); }; const checkTweetCache = (set, id) => { if (set.has(id)) { return true; } if (set.size > 50) { set.clear(); } set.add(id); return false; }; const isSensitive = (tweet) => { const main = tweet.getMainTweet && tweet.getMainTweet(); if (main?.possiblySensitive) { return true; // TODO these don't show media badges when hiding sensitive media } const related = tweet.getRelatedTweet && tweet.getRelatedTweet(); if (related?.possiblySensitive) { return true; } // noinspection RedundantIfStatementJS if (tweet.quotedTweet?.possiblySensitive) { return true; } return false; }; const fixMedia = function(html, media) { return html.find("a[data-media-entity-id='" + media.mediaId + "'], .media-item").first().removeClass("is-zoomable").css("background-image", "url(\"" + media.small() + "\")"); }; /** * @param {TD_Column} column * @param {ChirpBase} tweet */ const showTweetNotification = function(column, tweet) { if (column.model.getHasNotification()) { const sensitive = isSensitive(tweet); const previews = $TDX.notificationMediaPreviews && (!sensitive || TD.settings.getDisplaySensitiveMedia()); // TODO new cards don't have either previews or links const html = $(tweet.render({ withFooter: false, withTweetActions: false, withMediaPreview: true, isMediaPreviewOff: !previews, isMediaPreviewSmall: previews, isMediaPreviewLarge: false, isMediaPreviewCompact: false, isMediaPreviewInQuoted: previews, thumbSizeClass: "media-size-medium", mediaPreviewSize: "medium" })); html.find("time[data-time] a").text(""); // remove time since tweet was sent, since it will be recalculated anyway html.find("footer").last().remove(); // apparently withTweetActions breaks for certain tweets, nice html.find(".js-quote-detail").removeClass("is-actionable margin-b--8"); // prevent quoted tweets from changing the cursor and reduce bottom margin if (previews) { html.find(".reverse-image-search").remove(); const container = html.find(".js-media"); for (const media of tweet.getMedia()) { fixMedia(container, media); } if (tweet.quotedTweet) { for (const media of tweet.quotedTweet.getMedia()) { fixMedia(container, media).addClass("media-size-medium"); } } } else if (tweet instanceof TD.services.TwitterActionOnTweet) { html.find(".js-media").remove(); } html.find("a[data-full-url]").each(function() { // bypass t.co on all links and fix tooltips this.href = this.getAttribute("data-full-url"); this.removeAttribute("title"); }); html.find("a[href='#']").each(function() { // remove <a> tags around links that don't lead anywhere (such as account names the tweet replied to) this.outerHTML = this.innerHTML; }); html.find("p.link-complex-target").filter(function() { return $(this).text() === "Show this thread"; }).first().each(function() { this.id = "tduck-show-thread"; const moveBefore = html.find(".tweet-body > .js-media, .tweet-body > .js-media-preview-container, .quoted-tweet"); if (moveBefore) { $(this).css("margin-top", "5px").removeClass("margin-b--5").parent("span").detach().insertBefore(moveBefore); } }); if (tweet.quotedTweet) { html.find("p.txt-mute").filter(function() { return $(this).text() === "Show this thread"; }).first().remove(); } const type = tweet.getChirpType(); if (type === "follow") { html.find(".js-user-actions-menu").parent().remove(); html.find(".account-bio").removeClass("padding-t--5").css("padding-top", "2px"); } else if ((type.startsWith("favorite") || type.startsWith("retweet")) && tweet.isAboutYou()) { html.children().first().addClass("td-notification-padded"); } else if (type.includes("list_member")) { html.children().first().addClass("td-notification-padded td-notification-padded-alt"); html.find(".activity-header").css("margin-top", "2px"); html.find(".avatar").first().css("margin-bottom", "0"); } if (sensitive) { html.find(".media-badge").each(function() { $(this)[0].lastChild.textContent += " (possibly sensitive)"; }); } const source = tweet.getRelatedTweet(); const duration = source ? (source.text.length + (source.quotedTweet?.text.length ?? 0)) : tweet.text.length; const chirpId = source ? source.id : ""; const tweetUrl = source ? source.getChirpURL() : ""; const quoteUrl = source && source.quotedTweet ? source.quotedTweet.getChirpURL() : ""; $TD.onTweetPopup(column.model.privateState.apiid, chirpId, getColumnName(column), html.html(), duration, tweetUrl, quoteUrl); } if (column.model.getHasSound()) { $TD.onTweetSound(); } }; /** * @param {TD_Column} column * @param {ChirpBase} tweet */ return function(column, tweet) { if (tweet instanceof TD.services.TwitterConversation || tweet instanceof TD.services.TwitterConversationMessageEvent) { if (checkTweetCache(recentMessages, tweet.id)) { return; } } else { if (checkTweetCache(recentTweets, tweet.id)) { return; } } startRecentTweetTimer(); if (!$TDX.hideTweetsByNftUsers) { showTweetNotification(column, tweet); } else { checkUserNftStatus(getTweetUserId(tweet), function(nft) { if (!nft) { showTweetNotification(column, tweet); } }); } }; })(); /** * Fixes DM notifications not showing if the conversation is open. * @this {TD_Column} * @param {{ chirps: ChirpBase[], poller: { feed: { managed: boolean } } }} e */ function handleNotificationEvent(e) { if (this.model?.state?.type === "privateMe" && !this.notificationsDisabled && e.poller.feed.managed) { const unread = []; for (const chirp of e.chirps) { if (Array.isArray(chirp.messages)) { Array.prototype.push.apply(unread, chirp.messages.filter(message => message.read === false)); } } if (unread.length > 0) { if (checkPropertyExists(TD, "util", "chirpReverseColumnSort")) { unread.sort(TD.util.chirpReverseColumnSort); } for (const message of unread) { onNewTweet(this, message); } // TODO sound notifications are borked as well // TODO figure out what to do with missed notifications at startup } } } /** * Adds support for desktop notifications. */ export default function() { ensurePropertyExists(TD, "controller", "notifications"); TD.controller.notifications.hasNotifications = function() { return true; }; TD.controller.notifications.isPermissionGranted = function() { return true; }; $["subscribe"]("/notifications/new", function(obj) { for (let index = obj.items.length - 1; index >= 0; index--) { onNewTweet(obj.column, obj.items[index]); } }); if (checkPropertyExists(TD, "vo", "Column", "prototype")) { replaceFunction(TD.vo.Column.prototype, "mergeMissingChirps", function(func, args) { handleNotificationEvent.call(this, args[0]); return func.apply(this, args); }); } };
Ext.define('Signout.store.Students', { extend : 'Ext.data.Store', storeId: 'studentsstore', model : 'Signout.model.Student' });
'use strict'; const easeIn = p => Math.pow(p, 3); const easeOut = p => Math.pow(p - 1, 3) + 1; const easeInOut = p => p < 1/2 ? 4 * easeIn(p) : 0.5 * (easeOut(2*p - 1) + 1); const ease = (currentTime, deltaTime) => easeInOut(currentTime / deltaTime); function scroll(y) { window.scroll(window.scrollX, y); } module.exports = function smoothScroll(endScroll, deltaTime) { const timeStep = 10; const startScroll = window.scrollY; const deltaScroll = endScroll - startScroll; let currentTime = 0; function animate() { currentTime += timeStep; if (currentTime >= deltaTime) { scroll(endScroll); clearInterval(interval); } else scroll(startScroll + ease(currentTime, deltaTime) * deltaScroll); } const interval = setInterval(animate, timeStep); }
Entity = Class.extend({ init: function() { }, update: function() { } });
tinyMCE.addI18n('en.formula',{ desc : 'This is a formula editor.' });
/** * @module Hyperlapse */ /** * * @class HyperlapsePoint * @constructor * @param {google.maps.LatLng} location * @param {Number} pano_id * @param {Object} params */ var HyperlapsePoint = function(location, pano_id, params ) { var self = this; var prams = params || {}; /** * @attribute location * @type {google.maps.LatLng} */ this.location = location; /** * @attribute pano_id * @type {Number} */ this.pano_id = pano_id; /** * @attribute heading * @default 0 * @type {Number} */ this.heading = prams.heading || 0; /** * @attribute pitch * @default 0 * @type {Number} */ this.pitch = prams.pitch || 0; /** * @attribute elevation * @default 0 * @type {Number} */ this.elevation = prams.elevation || 0; /** * @attribute image * @type {Image} */ this.image = prams.image || null; /** * @attribute copyright * @default "© 2013 Google" * @type {String} */ this.copyright = prams.copyright || "© 2013 Google"; /** * @attribute image_date * @type {String} */ this.image_date = prams.image_date || ""; }; module.exports = HyperlapsePoint;
'use strict'; var camelcase = require('camelcase'); var getFileExtension = require('./getFileExtension'); module.exports = function getAssetKind(options, asset) { var ext = getFileExtension(asset); return camelcase(ext); };
var SubmitB = React.createClass({displayName: "SubmitB", getInitialState: function(){ return{value: '', text: false, para: ''}; }, handleClick : function(e){ this.setState({value: this.refs['a'].state.text, text: this.refs['b'].state.text, para: this.refs['c'].state.value}, function () { console.log(this.state.value); console.log(this.state.text); console.log(this.state.para); }); }, render : function(){ var value = this.state.value; var text = this.state.text; var para = this.state.para; return ( React.createElement("div", null, React.createElement(TextImage, {ref: "b", value: text}), React.createElement(TextV, {ref: "c", value: para}), React.createElement(FontSize, {ref: "a", value: value}), React.createElement("button", {onClick: this.handleClick, id: "button"}, "Submit") ) ); } }); var Imagepos = React.createClass({displayName: "Imagepos", getInitialState: function(){ return {position: [], clicks: 0}; }, handleChange: function(event){ var OFFSET_X = 450; var OFFSET_Y = 60; var pos_x = event.clientX?(event.clientX):event.pageX; var pos_y = event.clientY?(event.clientY):event.pageY; if(this.state.clicks < 2){ this.setState({clicks: this.state.clicks + 1 , position: [this.state.position[0], this.state.position[1], pos_x-OFFSET_X, pos_y-OFFSET_Y]}, function(){ console.log(this.state.position); }); } else{ document.getElementById("pointer_div").onclick = function() { return false; } ; } }, render:function(){ return( React.createElement("form", {name: "pointform", method: "post"}, React.createElement("div", {id: "pointer_div", onClick: this.handleChange}, React.createElement("img", {src: "test.png", id: "cross"}) ) ) ); } }); var TextV = React.createClass({displayName: "TextV", getInitialState: function(){ return {value: this.props.value}; }, handleChange : function(e){ this.setState({value: e.target.value}); }, render: function () { var value = this.state.value; return(React.createElement("div", {className: "form-group", id: "textV"}, React.createElement("label", {className: "col-sm-1 control-label"}, "Text"), React.createElement("div", {className: "col-sm-4"}, React.createElement("textarea", {className: "form-control", rows: "10", id: "focusedInput", onChange: this.handleChange, type: "text", value: this.state.value}) ) ) ); } }); var TextImage = React.createClass({displayName: "TextImage", getInitialState: function(){ return {text: this.props.value}; }, itsText: function(e){ this.setState({text: true}); }, itsImage: function(e){ this.setState({text: false}); }, render: function(){ return( React.createElement("div", {className: "radio", id: "TextOrImage"}, React.createElement("label", null, React.createElement("input", {type: "radio", name: "optradio", onChange: this.itsText}), "Text"), React.createElement("label", null, React.createElement("input", {type: "radio", name: "optradio", onChange: this.itsImage}), "Image") ) ); } }); var FontSize = React.createClass({displayName: "FontSize", getInitialState: function(){ return {text: this.props.value}; }, handleChange : function(e){ this.setState({text: e.target.value}); }, render: function () { return(React.createElement("div", {className: "form-group", id: "fontSize"}, React.createElement("label", {className: "col-sm-1 control-label"}, "FontSize"), React.createElement("div", {className: "col-sm-1"}, React.createElement("textarea", {className: "form-control", rows: "1", id: "focusedInput", onChange: this.handleChange, type: "text", value: this.text}) ) ) ); } }); React.render(React.createElement(Imagepos, null) , document.getElementById('fontSize'));
function introController ($scope) { $scope.menuOptions = [ { option: 'Jogue agora', href: '/client', clas: 'glyphicon glyphicon-flash' }, { option: 'Campeonato', href: '/campeonato', clas: 'glyphicon glyphicon-gift' }, { option: 'Sala Privada', href: '/sala', clas: 'glyphicon glyphicon-lock' }, { option: 'Seu perfil', href: '/perfil', clas: 'glyphicon glyphicon-user' }, { option: 'Servidor', href: '/table', style: 'visibility: hidden' }, ]; var activeOption; $scope.toggleActive = function (optionName) { activeOption = optionName; } $scope.isActive = function(optionName){ return optionName == activeOption; } }
'use strict' var app = angular.module('demo', ['ngConexo']); app.constant('USER_NATURE', { anonymous: 'anonymous', primeiroAcesso: 4, segurado: 5 }); app.controller('DemoCtrl', ['$cxAuth', '$cxRequest', '$scope', function ($cxAuth, $cxRequest, $scope) { $scope.message = $cxAuth.getUser(); $scope.login = function() { $scope.message = ''; var credentials = { username: '07031922720', password: '0' }; $cxAuth.login(credentials).then( function(response) { $scope.message = response }, function(err) { $scope.message = err; } ); }; $scope.logout = function() { $scope.message = ''; $cxAuth.logout().then( function(response) { $scope.message = 'logout successful' }, function(err) { $scope.message = 'logout unsuccesful'; } ); }; $scope.listPolicies = function() { $scope.message = ''; var req = $cxRequest.newRequest(2655, 'RM_CONSULTA_CONTRATOS'); //req.data.SYSMSG.CPF_CNPJ = '07031922720'; req.send().then( function (response) { console.log(response); $scope.message = response; }, function (err) { $scope.message = err; } ); }; } ]); app.config(function($cxRequestProvider) { $cxRequestProvider.setUrl('http://192.168.0.32/cxIsapi/cxIsapiClient.dll/gatewayJSON'); $cxRequestProvider.setServer('localhost'); $cxRequestProvider.setSysCode(63); $cxRequestProvider.setPort(5370); $cxRequestProvider.setChannel('BANSEG'); $cxRequestProvider.setTimeout(1500000); }); app.run(function($cxRequest, $cxAuth) { $cxRequest.registerOnTimeoutError( function () { $cxAuth.cleanAuth(); console.log('teste'); } ); $cxRequest.registerOnConnectionError( function () { $cxAuth.cleanAuth(); console.log('teste'); } ); } );
App.TodoListRoute = Ember.Route.extend({ model: function () { return this.store.find('todoList'); }, });
module.exports = { access_token: process.env.GOOGLE_ACCESS_TOKEN, refresh_token: process.env.GOOGLE_REFRESH_TOKEN, token_type: 'Bearer', expiry_date: process.env.GOOGLE_TOKEN_EXPIRY_DATE, };
var path = require('path'); var moment = require('moment'); var meta = require(process.cwd() + '/package.json'); module.exports = function(archiveName) { if('version' in meta) { archiveName = archiveName + '_' + meta.version; } return archiveName + '_' + moment().format('YYYYMMDDHHmmss') + '.zip'; };
import Route from '@ember/routing/route'; export default class Example4Route extends Route {}
// @flow import {snakeCase} from 'lodash'; /** * @private * Uppercase and snakecase the given string. * @param {string} type The string to be formatted. * @return {string} A formatted version of 'type'. */ function anaconda(type) { return snakeCase(type).toUpperCase(); } /** * @private * @example * // Returns `EXAMPLE/SOME_ACTION`. * formatType('example', 'someAction'); * @example * Creates a formatted type. * @param {string} name The `name` of the parent ReduxModule. * @param {string} actionName The name of the key the type will be stored under. * @return {string} The formatted type. */ export default function formatType(name: string, actionName: string) { return `${anaconda(name)}/${anaconda(actionName)}`; }
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"\u00e6_Attachments____________\u00c2",attachmentDetails:"\u00e6_Attachment details___________________\u00c2",add:"\u00e6_Add_______\u00c2",update:"\u00e6_Update_____________\u00c2",cancel:"\u00e6_Cancel_____________\u00c2",noTitle:"\u00e6_Untitled_________________\u00c2","delete":"\u00e6_Delete_____________\u00c2",selectFile:"\u00e6_Select file____________\u00c2",changeFile:"\u00e6_Change file____________\u00c2",noAttachments:"\u00e6_No attachments_______________\u00c2",addErrorMessage:"\u00e6_Error adding the attachment. Please try again________________________\u00c2.", deleteErrorMessage:"\u00e6_Error deleting the attachment. Please try again_________________________\u00c2.",updateErrorMessage:"\u00e6_Error updating the attachment. Please try again_________________________\u00c2."});
/*! jQuery UI - v1.10.1 - 2013-03-14 * http://jqueryui.com * Includes: jquery.ui.datepicker-uk.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.uk={closeText:"Закрити",prevText:"&#x3C;",nextText:"&#x3E;",currentText:"Сьогодні",monthNames:["Січень","Лютий","Березень","Квітень","Травень","Червень","Липень","Серпень","Вересень","Жовтень","Листопад","Грудень"],monthNamesShort:["Січ","Лют","Бер","Кві","Тра","Чер","Лип","Сер","Вер","Жов","Лис","Гру"],dayNames:["неділя","понеділок","вівторок","середа","четвер","п’ятниця","субота"],dayNamesShort:["нед","пнд","вів","срд","чтв","птн","сбт"],dayNamesMin:["Нд","Пн","Вт","Ср","Чт","Пт","Сб"],weekHeader:"Тиж",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.uk)});
import App from 'component/app' window.App = App || {}
(function() { var width = 600, height = 600; // Width and height of simulation in pixels. Each pixel is 10km by 10km var cellSize = 6; // Size of a cell in pixels. var yCellCount = Math.floor(height/cellSize); // Number of cells in the up-down direction. var xCellCount = Math.floor(width/cellSize); // Number of cells in the left-right direction. var context = $("#canvas").get(0).getContext("2d"); context.canvas.width = width; context.canvas.height = height; function makeBlankGrid() { // First, we make a new array of rows. Then we set those rows. var grid = new Array(yCellCount); for (var i = 0; i < yCellCount; i++) { grid[i] = new Array(xCellCount); for (var j = 0; j < grid[i].length; j++) { grid[i][j] = 20; } } return grid; }; function neighbours(x,y,grid) { var n = grid[x][y]; n += grid[x%xCellCount][(xCellCount+y-1)%yCellCount]; n += grid[x%xCellCount][(y+1)%yCellCount]; n += grid[(x+1)%xCellCount][y%yCellCount]; n += grid[(xCellCount+x-1)%xCellCount][y%yCellCount]; return n; } function randomMove(){ return Math.floor(3*Math.random()-1) } var grid = makeBlankGrid(); var humans = []; var paused = false; var new_point = true; var population = 0; var year = 0; var kill_rate = 20; var death_chance = []; var birth_chance = []; for (var i = 0; i < 20; i++) { death_chance[i] = i*1/120; birth_chance[i] = i*1/120+(20-i)/20*0.02; } for (var i = 20; i < 40; i++) { death_chance[i] = i*1/120+(20-i)/20*0.02; birth_chance[i] = i*1/120; } death_chance[40] = 1; birth_chance[40] = 0; birth_chance[0] = 0; death_chance[0] = 0; birth_chance[1] = 0; function drawGrid(grid) { context.fillStyle = "rgb(255, 255, 255)"; for (var y = 0; y < yCellCount; y++) { for (var x = 0; x < xCellCount; x++) { val = Math.min(grid[x][y],22); if (val != 0){ context.fillStyle = "hsl("+Math.round(120/22*val)+",100%,"+(50-2*Math.abs(val-10))+"%)"; } else { context.fillStyle = "black" } context.fillRect(x*cellSize, y*cellSize, cellSize, cellSize); } } }; function drawPoints(humans) { for(var i = 0; i<humans.length; i++){ context.beginPath(); context.arc(humans[i][0]*cellSize,humans[i][1]*cellSize,3,0,2*Math.PI); context.fillStyle = "red"; context.fill(); context.stroke(); } }; function mainLoop() { context.fillStyle = "rgb(0, 0, 0)"; context.fillRect(0, 0, width, height); //Update sliders kill_rate = $("#kill").val()/100; $("#killrate").html(kill_rate+""); human_num = $("#human").val(); $("#humandisplay").html(human_num+""); while (human_num>humans.length){ humans.push([Math.round(xCellCount*Math.random()),Math.round(yCellCount*Math.random())]); } while (human_num<humans.length){ humans.shift(); } //Update counters. $("#popdisplay").html(population+""); $("#year").html(Math.round(year/12)+""); // Run simulation step. if (!paused) { var new_grid = makeBlankGrid(); population = 0; year += 1; for (var y = 0; y < yCellCount; y++) { for (var x = 0; x < xCellCount; x++) { //diffusion if (year%6 == 0){ new_amount = Math.floor((neighbours(x,y,grid)+5*Math.random())/5); } else { new_amount = grid[x][y]; } //birth and death if (Math.random()<birth_chance[new_amount]){ new_amount += 1; } if (Math.random()<death_chance[new_amount]){ new_amount += -1; } new_grid[x][y] = new_amount; population += new_amount; } } grid = new_grid; for (var i = 0; i < humans.length; i++){ new_x = (humans[i][0] + randomMove()+xCellCount)%xCellCount; new_y = (humans[i][1] + randomMove()+xCellCount)%xCellCount; humans[i] = [new_x,new_y]; if (Math.random()<kill_rate && grid[new_x][new_y]>0){ grid[new_x][new_y] += -1; } } //if (year%12 == 0){ // if (population>0){ // console.log(population); // } //} } drawGrid(grid); drawPoints(humans); setTimeout(mainLoop, 0); // Run, run, as fast as you can! }; mainLoop(); }).call();
import Application from 'ember-bootstrap-docs/app'; import config from 'ember-bootstrap-docs/config/environment'; import * as QUnit from 'qunit'; import { setApplication } from '@ember/test-helpers'; import { setup } from 'qunit-dom'; import { start } from 'ember-qunit'; setApplication(Application.create(config.APP)); setup(QUnit.assert); start();
import Themeable from './themeable' export default { mixins: [Themeable], data () { return { errorBucket: [], focused: false, tabFocused: false, lazyValue: this.value } }, props: { appendIcon: String, appendIconCb: Function, disabled: Boolean, error: Boolean, errorMessages: { type: [String, Array], default: () => [] }, hint: String, hideDetails: Boolean, label: String, persistentHint: Boolean, placeholder: String, prependIcon: String, prependIconCb: Function, required: Boolean, rules: { type: Array, default: () => [] }, tabindex: { default: 0 }, value: { required: false } }, computed: { hasError () { return this.validations.length || this.error }, inputGroupClasses () { return Object.assign({ 'input-group': true, 'input-group--focused': this.focused, 'input-group--dirty': this.isDirty, 'input-group--tab-focused': this.tabFocused, 'input-group--disabled': this.disabled, 'input-group--error': this.hasError, 'input-group--append-icon': this.appendIcon, 'input-group--prepend-icon': this.prependIcon, 'input-group--required': this.required, 'input-group--hide-details': this.hideDetails, 'input-group--placeholder': !!this.placeholder, 'theme--dark': this.dark, 'theme--light': this.light }, this.classes) }, isDirty () { return this.inputValue }, modifiers () { const modifiers = { lazy: false, number: false, trim: false } if (!this.$vnode.data.directives) { return modifiers } const model = this.$vnode.data.directives.find(i => i.name === 'model') if (!model) { return modifiers } return Object.assign(modifiers, model.modifiers) }, validations () { return (!Array.isArray(this.errorMessages) ? [this.errorMessages] : this.errorMessages).concat(this.errorBucket) } }, watch: { rules () { this.validate() } }, mounted () { this.validate() }, methods: { genLabel () { return this.$createElement('label', { attrs: { for: this.$attrs.id } }, this.$slots.label || this.label) }, genMessages () { let messages = [] if ((this.hint && this.focused || this.hint && this.persistentHint) && this.validations.length === 0 ) { messages = [this.genHint()] } else if (this.validations.length) { messages = this.validations.map(i => this.genError(i)) } return this.$createElement( 'transition-group', { 'class': 'input-group__messages', props: { tag: 'div', name: 'slide-y-transition' } }, messages ) }, genHint () { return this.$createElement('div', { 'class': 'input-group__hint', key: this.hint, domProps: { innerHTML: this.hint } }) }, genError (error) { return this.$createElement( 'div', { 'class': 'input-group__error', key: error }, error ) }, genIcon (type) { const icon = this[`${type}Icon`] const cb = this[`${type}IconCb`] const hasCallback = typeof cb === 'function' return this.$createElement( 'v-icon', { 'class': { [`input-group__${type}-icon`]: true, 'input-group__icon-cb': hasCallback }, on: { click: e => { hasCallback && cb(e) } } }, icon ) }, genInputGroup (input, data = {}) { const children = [] const wrapperChildren = [] const detailsChildren = [] data = Object.assign({}, { 'class': this.inputGroupClasses, attrs: { tabindex: this.tabindex }, on: { blur: () => (this.tabFocused = false), click: () => (this.tabFocused = false), keyup: e => { if ([9, 16].includes(e.keyCode)) { this.tabFocused = true } }, keydown: e => { if (!this.toggle) return if ([13, 32].includes(e.keyCode)) { e.preventDefault() this.toggle() } } } }, data) if (this.$slots.label || this.label) { children.push(this.genLabel()) } wrapperChildren.push(input) if (this.prependIcon) { wrapperChildren.unshift(this.genIcon('prepend')) } if (this.appendIcon) { wrapperChildren.push(this.genIcon('append')) } children.push( this.$createElement('div', { 'class': 'input-group__input' }, wrapperChildren) ) detailsChildren.push(this.genMessages()) this.counter && detailsChildren.push(this.genCounter()) children.push( this.$createElement('div', { 'class': 'input-group__details' }, detailsChildren) ) return this.$createElement('div', data, children) }, validate () { this.errorBucket = [] this.rules.forEach(rule => { const valid = typeof rule === 'function' ? rule(this.value) : rule if (valid !== true) { this.errorBucket.push(valid) } }) } } }
const writeFile = require('./write-file'); module.exports = function (opts) { const file = `root = true charset = utf-8 indent_style = space indent_size = 4 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true`; writeFile({ directory: opts.directory, fileName: '.editorconfig', data: file, codeType: 'none', success () { opts.success(); }, error () { opts.error(); } }); };
var Seatbid = require('../../lib/openrtb2_3/seatbid').object; var SeatbidBuilder = require('../../lib/openrtb2_3/seatbid').builder; var RtbObject = require('../../lib/rtbObject'); describe("The Seatbid object should", function() { it("be an instance of RtbObject", function() { var seatbid = new Seatbid(); seatbid.should.be.an.instanceof(RtbObject); }); });
import React, { Component, PropTypes } from 'react'; import s from './ScreenshotPage.scss'; import withStyles from '../../decorators/withStyles'; import cx from 'classnames'; import Steam from '../../api/steam'; import Header from '../Header'; import Colors from '../../api/colors'; import Palette from '../Palette'; import FontAwesome from 'react-fontawesome'; import SteamApps from '../../stores/steamApps'; import parsePath from 'history/lib/parsePath'; import Location from '../../core/Location'; @withStyles(s) class ScreenshotPage extends Component { static propTypes = { steamID: PropTypes.string, username: PropTypes.string, screenshotID: PropTypes.string.isRequired, gameID: PropTypes.number, nextScreenshotIDs: PropTypes.string, }; static contextTypes = { onSetTitle: PropTypes.func.isRequired, }; constructor(props, context) { super(props, context); this.state = { screenshot: undefined, title: 'Screenshot ' + props.screenshotID, colors: undefined, loadingRandomScreenshot: false, }; } componentWillMount() { this.context.onSetTitle(this.state.title); } componentDidMount() { Steam.getScreenshot(this.props.screenshotID). then(this.onScreenshotLoaded.bind(this)). catch(this.onScreenshotLoadError.bind(this)); } onScreenshotLoaded(screenshot) { this.setState({ screenshot }, () => { this.updateTitle(); }); Colors.getColors(screenshot.mediumUrl). then(this.onColorsLoaded.bind(this)). catch(this.onColorsLoadError.bind(this)); } onScreenshotLoadError(response) { console.error('failed to load Steam screenshot', response); } onColorsLoaded(colors) { this.setState({ colors }); } onColorsLoadError(response) { console.error('failed to load colors from image', response); } onRandomScreenshotLoaded(screenshot) { const path = '/screenshot/' + screenshot.id; Location.push({ ...(parsePath(path)), }); } onRandomScreenshotLoadError(error) { console.error('failed to load random screenshot', error); this.setState({ loadingRandomScreenshot: false }); } updateTitle() { const description = this.state.screenshot.description; if (typeof description === 'string' && description.length > 0) { this.setState({ title: description }); } } loadRandomScreenshot(event) { const button = event.target; button.blur(); this.setState({ loadingRandomScreenshot: true }); Steam.getRandomScreenshot(). then(this.onRandomScreenshotLoaded.bind(this)). catch(this.onRandomScreenshotLoadError.bind(this)); } loadNextScreenshot(event) { const button = event.target; button.blur(); let url = ''; const ids = this.props.nextScreenshotIDs.split(','); const id = ids[0]; if (typeof this.props.username === 'string') { url = '/player/' + this.props.username + '/' + this.props.steamID + '/' + id; } else if (typeof this.props.gameID !== 'undefined') { url = '/game/' + this.props.gameID + '/' + id; } else { url = '/screenshot/' + id; } if (ids.length > 1) { url += '?next=' + ids.slice(1).join(','); } Location.push({ ...(parsePath(url)), }); } render() { const alt = 'Screenshot ' + this.props.screenshotID; const isScreenshotLoaded = typeof this.state.screenshot === 'object'; let date = ''; if (isScreenshotLoaded && this.state.screenshot.date) { date = this.state.screenshot.date.toLocaleDateString(); } let backUrl = undefined; let backIcon = undefined; let backTitle = undefined; if (typeof this.props.username === 'string') { backUrl = '/player/' + this.props.username + '/' + this.props.steamID; backIcon = 'user'; backTitle = this.props.username; } else if (typeof this.props.gameID !== 'undefined') { backUrl = '/game/' + this.props.gameID; backIcon = 'steam'; backTitle = SteamApps.getName(this.props.gameID); } else if (isScreenshotLoaded) { if (typeof this.state.screenshot.appid === 'number' && typeof this.state.screenshot.gameName === 'string') { backUrl = '/game/' + this.state.screenshot.appid; backIcon = 'steam'; backTitle = this.state.screenshot.gameName; } } const areColorsLoaded = typeof this.state.colors === 'object'; return ( <div className={s.container}> <div className={s.row}> <div className={s.left}> <Header title={this.state.title} previousUrl={backUrl} previousTitle={backTitle} previousIcon={backIcon} /> </div> <div className={s.right}> {typeof this.props.nextScreenshotIDs === 'undefined' ? ( <button type="button" className={s.screenshotNavButton} onClick={this.loadRandomScreenshot.bind(this)} disabled={this.state.loadingRandomScreenshot} > Random screenshot &rarr; </button> ) : ( <button type="button" className={s.screenshotNavButton} onClick={this.loadNextScreenshot.bind(this)} > Next screenshot &rarr; </button> )} {this.state.loadingRandomScreenshot ? ( <FontAwesome name="spinner" spin className={s.spinner} /> ) : ''} </div> </div> {isScreenshotLoaded ? ( <div className={s.details}> <div className={s.left}> <a href={this.state.screenshot.fullSizeUrl} target="_blank" className={s.screenshotLink} > <img src={this.state.screenshot.mediumUrl} alt={alt} className={s.screenshot} /> </a> <a href={this.state.screenshot.url} target="_blank" className={s.detailsUrl} > <FontAwesome name="info" className={cx(s.icon, s.detailsIcon)} /> View details </a> <a href={this.state.screenshot.fullSizeUrl} target="_blank" className={s.fullSizeLink} > <FontAwesome name="search-plus" className={cx(s.icon, s.fullSizeIcon)} /> View full size </a> <a className={s.authorLink} href={this.state.screenshot.userUrl} target="_blank" > <FontAwesome name="steam" className={cx(s.icon, s.profileIcon)} /> {typeof this.props.username === 'string' ? ( <span>View {this.props.username}'s profile</span> ) : ( <span>View user profile</span> )} </a> <ul className={s.metadata}> <li>{date}</li> <li> {this.state.screenshot.width} &times; {this.state.screenshot.height} </li> <li>{this.state.screenshot.fileSize}</li> </ul> </div> <div className={s.right}> {areColorsLoaded ? ( <Palette colors={this.state.colors} /> ) : ( <p className={s.colorsMessage}>Loading colors...</p> )} </div> </div> ) : ( <p className={s.message}>Loading screenshot...</p> )} </div> ); } } export default ScreenshotPage;
var canvas; var gl; var numVertices = 6; var texSize = 256; var numChecks = 64; //var flag = true; var near = 0.3; var far = 3.0; var fovy = 45.0; // Field-of-view in Y direction angle (in degrees) var aspect = 1.0; // Viewport aspect ratio var texture1, texture2, texture3, texture4; // Create a checkerboard pattern using floats var image1 = new Uint8Array(4*texSize*texSize); for ( var i = 0; i < texSize; i++ ) { for ( var j = 0; j <texSize; j++ ) { var patchx = Math.floor(i/(texSize/numChecks)); var patchy = Math.floor(j/(texSize/numChecks)); if(patchx%2 ^ patchy%2) c = 255; else c = 0; //c = 255*(((i & 0x8) == 0) ^ ((j & 0x8) == 0)) image1[4*i*texSize+4*j] = c; image1[4*i*texSize+4*j+1] = c; image1[4*i*texSize+4*j+2] = c; image1[4*i*texSize+4*j+3] = 255; } } var pointsArray = []; var colorsArray = []; var texCoordsArray = []; var texCoord = [ vec2(0, 0), vec2(0, 1), vec2(1, 1), vec2(1, 0) ]; var zmin = 1.0; var zmax = 50.0; var vertices = [ vec4( -5.5, 0.0, zmax, 1.0 ), vec4( -5.5, 0.0, zmin, 1.0 ), vec4( 5.5, 0.0, zmin, 1.0 ), vec4( 5.5, 0.0, zmax, 1.0 ), ]; var modelViewMatrix, projectionMatrix; var modelViewMatrixLoc, projectionMatrixLoc; var eye = vec3(0.0, 10.0, 0.0); var at = vec3(0.0, 0.0, (zmax+zmin)/4); const up = vec3(0.0, 1.0, 0.0); var vertexColors = [ vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 1.0, 1.0, 1.0 ), // white vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green vec4( 0.0, 0.0, 1.0, 1.0 ), // blue vec4( 1.0, 0.0, 1.0, 1.0 ), // magenta vec4( 0.0, 1.0, 1.0, 1.0 ) // cyan ]; window.onload = init; function configureTexture(image) { texture1 = gl.createTexture(); gl.bindTexture( gl.TEXTURE_2D, texture1 ); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize, texSize, 0, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.generateMipmap( gl.TEXTURE_2D ); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); }; function quad(a, b, c, d) { pointsArray.push(vertices[a]); colorsArray.push(vertexColors[a]); texCoordsArray.push(texCoord[0]); pointsArray.push(vertices[b]); colorsArray.push(vertexColors[a]); texCoordsArray.push(texCoord[1]); pointsArray.push(vertices[c]); colorsArray.push(vertexColors[a]); texCoordsArray.push(texCoord[2]); pointsArray.push(vertices[a]); colorsArray.push(vertexColors[a]); texCoordsArray.push(texCoord[0]); pointsArray.push(vertices[c]); colorsArray.push(vertexColors[a]); texCoordsArray.push(texCoord[2]); pointsArray.push(vertices[d]); colorsArray.push(vertexColors[a]); texCoordsArray.push(texCoord[3]); } function init() { canvas = document.getElementById( "gl-canvas" ); gl = WebGLUtils.setupWebGL( canvas ); if ( !gl ) { alert( "WebGL isn't available" ); } gl.viewport( 0, 0, canvas.width, canvas.height ); gl.clearColor( 0.5, 0.5, 0.5, 1.0 ); // // Load shaders and initialize attribute buffers // var program = initShaders( gl, "vertex-shader", "fragment-shader" ); gl.useProgram( program ); quad( 1, 0, 3, 2 ); var cBuffer = gl.createBuffer(); gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer); gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW ); var vColor = gl.getAttribLocation( program, "vColor" ); gl.vertexAttribPointer(vColor, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vColor); var vBuffer = gl.createBuffer(); gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer); gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW); var vPosition = gl.getAttribLocation( program, "vPosition" ); gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition); var tBuffer = gl.createBuffer(); gl.bindBuffer( gl.ARRAY_BUFFER, tBuffer); gl.bufferData( gl.ARRAY_BUFFER, flatten(texCoordsArray), gl.STATIC_DRAW ); var vTexCoord = gl.getAttribLocation( program, "vTexCoord"); gl.vertexAttribPointer(vTexCoord, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vTexCoord); configureTexture(image1); modelViewMatrixLoc = gl.getUniformLocation( program, "modelViewMatrix" ); projectionMatrixLoc = gl.getUniformLocation( program, "projectionMatrix" ); // sliders for viewing parameters document.getElementById("zFarSlider").onchange = function(event) { far = event.target.value; }; document.getElementById("zNearSlider").onchange = function(event) { near = event.target.value; }; document.getElementById("aspectSlider").onchange = function(event) { aspect = event.target.value; }; document.getElementById("fovSlider").onchange = function(event) { fovy = event.target.value; }; document.getElementById("Texture Style").onclick = function( event) { //switch(event.srcElement.index) { switch(event.target.index) { case 0: gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); break; case 1: gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR ); break; case 2: gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST ); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); break; case 3: gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR ); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR ); break; }; }; render(); } var render = function() { gl.clear( gl.COLOR_BUFFER_BIT); modelViewMatrix = lookAt(eye, at , up); projectionMatrix = perspective(fovy, aspect, near, far); gl.uniformMatrix4fv( modelViewMatrixLoc, false, flatten(modelViewMatrix) ); gl.uniformMatrix4fv( projectionMatrixLoc, false, flatten(projectionMatrix) ); gl.drawArrays( gl.TRIANGLES, 0, numVertices ); requestAnimFrame(render); }
'use strict'; var shelljs = require('shelljs'); var format = require('string-template'); var request = require('request'); var _ = require('lodash'); module.exports = function(grunt){ var getPort = function(){ var port = grunt.option( 'port' ) || 3000; if(grunt.option( 'host' ) && !grunt.option( 'port' )){ port = 80; } return port; }; // A task for generating documentation using doxx CLI grunt.task.registerTask('doxx:shell', 'documentation', function() { var options = { ignore: 'tests,views', source: 'app', dest: grunt.config.process('<%= meta.reports %>') + '/docs/doxx', title: 'Documentation' }; var template = './node_modules/doxx/bin/doxx --source {source} --target \'{dest}\' --ignore \'{ignore}\' -t \'{title}\''; var command = format(template, options); var result = shelljs.exec(command); if(result.code === 0){ grunt.log.ok(this.name + ' - Documentation created successfully'); }else{ grunt.log.error(this.name + ' - ERROR: something went wrong!'); } }); // A task for running tests with mocha CLI and doing code coverage with istanbul CLI grunt.task.registerTask('istanbul:mocha:cover', 'nodejs code coverage', function() { var options = { configFile: 'config/.istanbul.yml', testFiles: 'app/tests/**/*.js', }; var template = 'istanbul cover --config={configFile} node_modules/.bin/_mocha {testFiles}'; var command = format(template, options); var result = shelljs.exec(command); if(result.code === 0){ grunt.log.ok(this.name + ' - Coverage done successfully'); }else{ grunt.log.error(this.name + ' - ERROR: oops. something went wrong!'); } }); grunt.registerTask('setTestEnvVars', 'updates url in waitServer.', function() { var port = getPort(); var envName = grunt.option( 'env' ) || 'dev'; var dbName = grunt.option( 'dbname' ) || ('jean-' + port); var gruntConfigProp = 'env'; var env = { DB_NAME: dbName, PORT: port }; var prop = grunt.config.get(gruntConfigProp); prop[envName] = _.extend(prop[envName], env); grunt.config.set(gruntConfigProp, prop); grunt.log.write('Complete. env vars \n' , prop[envName]); }); };
module.exports = function($scope, todoService) { $scope.loaded = false; $scope.newTitle = ""; $scope.stats = todoService.getStats(); $scope.tabs = todoService.getTabs(); $scope.removeCompleted = function() { todoService.removeCompleted(); }; $scope.selectTab = function(option) { todoService.selectTab(option); }; todoService.start.then(function(data) { $scope.loaded = true; $scope.todos = data; }); $scope.createItem = function() { // NOTE: prevent default here with event object if form validation fails todoService.createItem($scope.newTitle); $scope.newTitle = ""; }; };
import React from 'react' import classNames from 'classnames'; class PageAnimator extends React.Component { constructor(props) { super(props); this.state = { active: false } } componentDidMount() { setTimeout(() => { this.setState({active: true}) }, 5) } render() { const { animateType = "fade" } = this.props; const { active } = this.state; var classes = classNames( 'page-animate-' + animateType, { "PageAnimator": true, "active": active, }); return ( <div className={classes}> {this.props.children} </div> ) } } export default PageAnimator;
(function () { 'use strict'; angular .module('milesBoard') .controller('AddRunToUserController', AddRunToUserController); AddRunToUserController.$inject = ['$scope', '$uibModalInstance']; function AddRunToUserController($scope, $uibModalInstance) { let vm = this; vm.$onInit = onInit; vm.save = save; vm.cancel = cancel; function onInit() { vm.cal_opened = false; vm.run = { user_id: '', distance: '', run_date: new Date(), }; vm.dateOptions = { maxDate: new Date(), }; } function save(user_id) { vm.run.user_id = user_id; $uibModalInstance.close(vm.run); } function cancel() { $uibModalInstance.close(null); } } })();
/** * Created with JetBrains WebStorm. * User: teisaacs * Date: 10/15/13 * Time: 6:21 PM * To change this template use File | Settings | File Templates. */ var Store = (function() { // private variables and functions var API_KEY = ""; var DB_NAME = "dwitasks"; var COLLECTION_LIST = "lists"; var URL = "https://api.mongolab.com/api/1/databases/" + DB_NAME + "/collections/" + COLLECTION_LIST; var KEY_PARAM = "?apiKey=" + API_KEY; /** * Pulls the entire collection of Lists * * @param onSuccess * @param onError * @private */ // var _loadLists = function(onSuccess, onError) { // $.ajax({ // url: URL + KEY_PARAM, // type: "GET", // contentType: "application/json" // }).done( function (result) { // if (onSuccess) { // onSuccess(result); // } // }).fail(function(jqXHR, textStatus){ // if (onError) { // onError(jqXHR, textStatus); // } // }); // }; /** * Saves a single list object/mongo document. We can get more granular with the save and update parts of the * document, for now just save the whole document. * * NOTE: the REST url for this document .../DOCUMENT_ID?.... This allows us to update this individual item. If we * did not use this ID in the url we would have to specify a query param to limit the update 'q={}' . * * @param list * @param onSuccess * @param onError * @private */ // var _saveList = function(list, onSuccess, onError) { // $.ajax({ // url: URL + "/" + list._id.$oid + KEY_PARAM, // data: JSON.stringify(list), // type: "PUT", // contentType: "application/json" // }).done(function (result) { // if (onSuccess) { // onSuccess(result); // } // }).fail(function(jqXHR, textStatus){ // if (onError) { // onError(jqXHR, textStatus); // } // }); // }; /** * Removes a single List document. * @param list * @private */ // var _removeList = function(list, onSuccess, onError) { // $.mobile.loading('show'); // $.ajax({ // url: URL + "/" + list._id.$oid + KEY_PARAM, // type: "DELETE", // async: true, // timeout: 300000} // ).done(function () { // if (onSuccess) { // onSuccess(); // } // }).fail(function(jqXHR, textStatus){ // if (onError) { // onError(jqXHR, textStatus); // } // }); // }; /** * Save a new List document. * Mongo will add the $oid in the returned object. * * @param itemName * @param onSuccess * @param OnError * @private */ // var _addListItem = function(itemName, onSuccess, onError) { // $.ajax({ // url: URL + KEY_PARAM, // type: "POST", // contentType: "application/json", // data: JSON.stringify({ "name": itemName }) // }).done(function (result) { // if (onSuccess) { // onSuccess(result); // } // }).fail(function(jqXHR, textStatus){ // if (onError) { // onError(jqXHR, textStatus); // } // }); // }; // expose public API return { loadLists: _loadLists, addListItem: _addListItem, removeList: _removeList, saveList : _saveList }; })();
function Cleanup(list) { function cleanup(target) { if (isNode(this) && !isNode(target)) { target = this; } for (var cx = list.length - 1; cx >= 0; cx--) { var element = list[cx]; if (element === target) { list.splice(cx, 1); } } } return cleanup; }
module.exports = 'module-one-A-applicationMiddleware';
import Ember from 'ember'; import Registry from './registry'; export default Ember.Mixin.create({ registerWithParent: Ember.on('didInsertElement', function() { var registry = this.get('parentComponent'); if (registry) { registry.register(this); } }), deregisterWithParent: Ember.on('willDestroyElement', function() { var registry = this.get('parentComponent'); registry.deregister(this); }), parentComponent: Ember.computed(function() { return this.nearestOfType(Registry); }), });
import Twit from 'twit' import Async from 'async' import log from './helpers/logger' import User from './models/User' const WAITING_PERIOD = 15 * 60 * 1000 const RATE_LIMIT_FLAG = 'rate-limit' const MAX_IDS = 100 let twitter = function (options) { this.followersQueue = Async.queue((worker, callback) => this._getFollowers(worker, callback), 1) this.usersQueue = Async.queue((worker, callback) => this._getUsers(worker, callback), 1) this._T = new Twit(options) } twitter.prototype.start = function (id) { log.info('Twitter crawler started for user ' + id) this.usersQueue.push({id: id}, _usersCallback) this.followersQueue.push({id: id}, _followersCallback) } twitter.prototype._getFollowers = function (request, cb) { let fields = { user_id: request.id, count: 5000 } if (request.cursor) fields.cursor = request.cursor if (request.ids) fields.ids = request.ids log.debug('Making request for followers - ', fields.user_id) this._followersRequest('followers/ids', fields, (err, data, response) => { if (err && err === RATE_LIMIT_FLAG) { // Redo the request later if (data.cursor) request.cursor = data.cursor this.followersQueue.push(request, _followersCallback) return cb(err) } if (err) { log.error('Error getting followers from twitter', err) return cb(err) } let user = { id: request.id, followers: data.ids, updated: Date() } // Set user requests to queue this._queueUserRequests(user.followers) // Set follower requests to queue this._queueFollowerRequests(user.followers) // Update user in database User.findOneAndUpdate({id: user.id}, user, {new: true, upsert: true}, (err, _user) => { if (err) { log.error('Error updating user followers', err) return cb(err) } log.debug('Updated followers for: ' + _user.id + ' handler: ' + _user.handler) cb() }) }) } twitter.prototype._getUsers = function (request, cb) { let ids = request.id log.debug('Making request for users - ', request) this._usersRequest('users/lookup', {user_id: ids, include_entities: false}, (err, data, response) => { if (err && err === RATE_LIMIT_FLAG) { // Redo the request later this.usersQueue.push(request, _usersCallback) return cb(err) } if (err) { log.error('Error getting users from twitter', err) return cb(err) } // Update user in database Async.each(data, (user, cbEach) => { let newUser = { id: user.id, name: user.name, handler: user.screen_name, img: user.profile_image_url, location: user.location, updated: Date() } User.findOneAndUpdate({id: user.id}, newUser, {new: true, upsert: true}, (err, _user) => { if (err) { log.error('Error updating user', err) return cbEach(err) } log.debug('Updated user info: ' + _user.id + ' handler: ' + _user.handler) cbEach() }) }, cb) }) } twitter.prototype._queueUserRequests = function (users) { // Set user requests to queue if (!users || users.length === 0) { return } for (let i = 0; i < users.length; i += MAX_IDS) { let ids = users.slice(i, i + MAX_IDS).join(',') this.usersQueue.push({id: ids}, _usersCallback) } } twitter.prototype._queueFollowerRequests = function (users) { // Set follower requests to queue if (!users || users.length === 0) { return } for (let i = 0; i < users.length; i++) { this.followersQueue.push({id: users[i]}, _followersCallback) } } twitter.prototype._followersRequest = function (path, params, callback) { // Hack so we can fetch all the ids let result = {ids: params.ids || []} delete params.ids this._T.get(path, params, (err, data, response) => { if (response.statusCode === 429) { log.debug('Pausing followers queue') this.followersQueue.pause() setTimeout(() => { log.debug('Resuming followers queue') this.followersQueue.resume() }, WAITING_PERIOD) // Buble data for the next request return callback(RATE_LIMIT_FLAG, params) } if (err) { return callback(err) } result.ids = result.ids.concat(data.ids) log.debug('Got', data.ids.length, 'ids, total is', result.ids.length) if (data.next_cursor_str && data.next_cursor_str !== '0') { params.cursor = data.next_cursor_str params.ids = result.ids return this._followersRequest(path, params, callback) } callback(null, result, response) }) } twitter.prototype._usersRequest = function (path, params, callback) { this._T.get(path, params, (err, data, response) => { if (response.statusCode === 429) { log.debug('Pausing users queue') this.usersQueue.pause() setTimeout(() => { log.debug('Resuming users queue') this.usersQueue.resume() }, WAITING_PERIOD) return callback(RATE_LIMIT_FLAG) } if (err) { return callback(err) } callback(null, data, response) }) } function _usersCallback (err) { if (err && err === RATE_LIMIT_FLAG) { return log.warn('Users queue stopped due to rate limit - EXITING') } if (err) { return log.error('Error getting users', err) } log.debug('Retrieved users successfuly') } function _followersCallback (err) { if (err && err === RATE_LIMIT_FLAG) { return log.warn('Followers queue stopped due to rate limit - EXITING') } if (err) { return log.error('Error getting followers', err) } log.debug('Retrieved followers successfuly') } export default twitter
import './imported_item_timeline.html'; import './imported_item_timeline.css'; import { Template } from 'meteor/templating'; import { Util } from '../../../../imports/api/util'; import '../contributors/contributor_link'; /** * Template Helpers */ Template.ImportedItemTimeline.helpers({ timelineEntries () { let item = this, entries = [ { number: 1, date : item.dateCreated, data : { actor: item.createdBy, title: 'Created' } } ]; if (item.statusHistory) { item.statusHistory.forEach((entry, i) => { entries.push({ number: i + 2, date : entry.date, data : { actor: entry.owner, title: entry.to && entry.to.label } }) }) } entries.forEach((entry, i) => { if (i < entries.length - 1) { let next = entries[ i + 1 ]; entry.delta = { workDays: Util.workDaysDiff(entry.date, next.date) }; } else { entry.delta = { workDays: Util.workDaysDiff(entry.date, new Date()) }; } }); return entries } }); /** * Template Event Handlers */ Template.ImportedItemTimeline.events({}); /** * Template Created */ Template.ImportedItemTimeline.onCreated(() => { }); /** * Template Rendered */ Template.ImportedItemTimeline.onRendered(() => { }); /** * Template Destroyed */ Template.ImportedItemTimeline.onDestroyed(() => { });
'use strict'; var React = require('react'), RouteHandler = require('react-router').RouteHandler, Header = require('./header.jsx'), App; App = React.createClass({ render: function render() { return ( <div> <Header /> <RouteHandler/> </div> ); } }); module.exports = App;
module.exports = { 'id' : 1, 'username' : 'admin@easymongo.com', 'password' : 'demo', 'type' : 'admin' };
'use strict'; module.exports = { type: 'error', error: { line: 1, column: 3, message: 'Unexpected end of line. Number at 1:1 is unfinished.', }, };
version https://git-lfs.github.com/spec/v1 oid sha256:273a225e99d1d16cfb16d2a22ec1fe6ea074604a73a572f4dd6253aeb614fbe5 size 3784
version https://git-lfs.github.com/spec/v1 oid sha256:788a4cc38870b8c76a644e6646a6cad68034f34dcd884a8f94447f5858d2377c size 22885
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // // Rails Frameworks //= require jquery //= require jquery_ujs //= require turbolinks // PlugIns //= require materialize //= require scrollTo.min // My JS //= require home $(function(){ $('.slider').slider(); $(".button-collapse").sideNav(); $('.nav_actions a').scrollTo({ speed: 500 }); });