code
stringlengths
2
1.05M
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.2.3_A1_T13; * @section: 15.10.2.3; * @assertion: The | regular expression operator separates two alternatives. * The pattern first tries to match the left Alternative (followed by the sequel of the regular expression). * If it fails, it tries to match the right Disjunction (followed by the sequel of the regular expression); * @description: Execute /(.)..|abc/.exec("abc") and check results; */ __executed = /(.)..|abc/.exec("abc"); __expected = ["abc","a"]; __expected.index = 0; __expected.input = "abc"; //CHECK#1 if (__executed.length !== __expected.length) { $ERROR('#1: __executed = /(.)..|abc/.exec("abc"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length); } //CHECK#2 if (__executed.index !== __expected.index) { $ERROR('#2: __executed = /(.)..|abc/.exec("abc"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index); } //CHECK#3 if (__executed.input !== __expected.input) { $ERROR('#3: __executed = /(.)..|abc/.exec("abc"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input); } //CHECK#4 for(var index=0; index<__expected.length; index++) { if (__executed[index] !== __expected[index]) { $ERROR('#4: __executed = /(.)..|abc/.exec("abc"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]); } }
exports.types = { NewStartingHashKey: { type: 'String', notNull: true, regex: '0|([1-9]\\d{0,38})', }, StreamName: { type: 'String', notNull: true, regex: '[a-zA-Z0-9_.-]+', lengthGreaterThanOrEqual: 1, lengthLessThanOrEqual: 128, }, ShardToSplit: { type: 'String', notNull: true, regex: '[a-zA-Z0-9_.-]+', lengthGreaterThanOrEqual: 1, lengthLessThanOrEqual: 128, }, }
var db = require('./db.js'); module.exports.getId = function(user) { return user.id; }; module.exports.fetchById = function(id,cb) { console.log('calling fetchById'); db.user.findOne({ _id : id }, function(err, obj) { var user = { id: obj._id, userName: obj.userName, firstName: obj.firstName, lastName: obj.lastName, password: obj.password }; return cb(null, user); }); }; module.exports.fetchByUsername = function(username, cb) { db.User.findOne({ userName: username}, function(err, obj) { if (err) { console.log('we have an error in fetchbyusername'); } if (obj) { var user = { id: obj._id, userName: obj.userName, firstName: obj.firstName, lastName: obj.lastName, password: obj.password }; return cb(null, user); } else { console.log('no user'); cb(); } }); }; module.exports.checkPassword = function(user, password, cb) { if (user) { (user.password == password) ? cb(null, true) : cb(null, false); } else { cb(null, false); } }; module.exports.fetchFromRequest = function(req) { return req.session.user; };
// Copyright (c) Microsoft Corp. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. (function () { "use strict"; // A property processor should return this if the intention is that the return value is not to be set on the control property var doNotSetOptionOnControl = {}; // Check if property starts with 'on' to see if it's an event handler function isPropertyEventHandler(propertyName) { return propertyName[0] === "o" && propertyName[1] === "n"; } // Check if two WinJS layouts are considered the same function isSameLayout(layout1, layout2) { if (layout1 && layout2 && layout1.type && layout2.type) { return objectShallowEquals(layout1, layout2); } else { return layout1 === layout2; } }; function arrayShallowEquals(array1, array2) { if (array1 === array2) { return true; } if (!array1 || !array2 || array1.length !== array2.length) { return false; } for (var i in array1) { if (array2[i] !== array1[i]) { return false; } } return true; } // Perform a shallow comparison of two objects function objectShallowEquals(object1, object2) { if (object1 === object2) { return true; } for (var prop in object1) { if (object1[prop] !== object2[prop]) { return false; } } for (var prop in object2) { if (object1[prop] !== object2[prop]) { return false; } } return true; } function addBindings(controls, eventConfig) { Object.keys(controls).forEach(function (name) { var controlConfiguration = controls[name]; var eventsChangingProperties = eventConfig[name]; var ctor = WinJS.Utilities.getMember("WinJS.UI." + name); var propertyProcessor = controlConfiguration.propertyProcessor || {}; var delayedPropertyProcessor = controlConfiguration.postCtorPropertyProcessor || {}; var bindDescendantsBeforeParent = controlConfiguration.bindDescendantsBeforeParent || false; var bindingName = "win" + name; ko.bindingHandlers[bindingName] = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { // The options for the control var value = valueAccessor(); // Options record for the WinJS Control var options = {}; // If the WinJS control depends on having child elements if (element.children.length > 0 && bindDescendantsBeforeParent) { ko.applyBindingsToDescendants(bindingContext, element); } // Iterate over the observable properties to get their value for (var property in value) { // Exclude events from options to set up during ctor, we explicitly set event handlers in the update function // because setting an event property will not unhook the event listener that was set as options during initialization. if (value.hasOwnProperty(property) && !isPropertyEventHandler(property) && (!delayedPropertyProcessor[property])) { if (propertyProcessor[property]) { var propertyResult = propertyProcessor[property](value[property], function () { return element }); // doNotSetOptionOnControl from propertyProcessor means don't set the option on the control if (propertyResult !== doNotSetOptionOnControl) { options[property] = propertyResult; } } else { options[property] = ko.unwrap(value[property]); } } } // Create a new instance of the control with the element and options var control = new ctor(element, options); // Add event handler that will kick off changes to the changing properties that are observed if (eventConfig[name]) { var events = eventConfig[name]; for (var event in events) { ko.utils.registerEventHandler(element, event, function changed(e) { // Iterate over the properties that change as a result of the events for (var propertyIndex in eventConfig[name][event]) { var property = eventConfig[name][event][propertyIndex]; // Check to see if they exist if (value && value.hasOwnProperty(property)) { // Determine if that value is a writableObservable property and check the property has changed if (ko.isWriteableObservable(value[property]) && value[property]() !== control[property]) { // Kickoff updates value[property](control[property]); } } } }); } } // Add disposal callback to dispose the WinJS control when it's not needed anymore ko.utils.domNodeDisposal.addDisposeCallback(element, function (e) { if (element.winControl) { element.winControl.dispose(); } }); return { controlsDescendantBindings: bindDescendantsBeforeParent }; }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { // Get the WinJS control var control = element.winControl; var value = valueAccessor(); // Only update the control properties that are different with the unpacked value, we also process delayed property processors only here for (var property in value) { if (value.hasOwnProperty(property)) { var unwrappedValue = ko.unwrap(value[property]); if (control[property] !== unwrappedValue) { if (propertyProcessor && propertyProcessor[property]) { var returnValue = propertyProcessor[property](value[property], function () { return element }, control[property]); if (returnValue !== doNotSetOptionOnControl) { control[property] = returnValue; } } else if (delayedPropertyProcessor && delayedPropertyProcessor[property]) { var returnValue = delayedPropertyProcessor[property](value[property], function () { return element }, control[property]); if (returnValue !== doNotSetOptionOnControl) { control[property] = returnValue; } } else { control[property] = unwrappedValue; } } } } } } }); } // Helper for diffing between an obserable array and binding list function bindingListWatch(value, oldValue, sourceElement) { var unpacked = ko.unwrap(value); // Will create a bindingList once per new observable array var retVal = doNotSetOptionOnControl; if (Array.isArray(unpacked) && ko.isWriteableObservable(value)) { if (!value._winKoChangesSubscription) { if (value._rateLimitedChange) { throw new Error("Knockout-WinJS does not support rate limited observable arrays currently"); } var bindingList = new WinJS.Binding.List(unpacked); value._winKoChangesSubscriptionDisabled = false; value._winKoBindingList = bindingList; // Subscribe to the array diff callback for observable array changes value._winKoChangesSubscription = value.subscribe(function (newValue) { if (!value._winKoChangesSubscriptionDisabled) { // disable binding list callbacks to prevent an infinte loop bindingList._winKoChangesSubscriptionDisabled = true; var offset = 0; var deletes = newValue.filter(function (item) { return item.status === "deleted"; }); var adds = newValue.filter(function (item) { return item.status === "added"; }); for (var deletedItem in deletes) { var item = deletes[deletedItem]; bindingList.splice(item.index - offset, 1); offset++; } var arrayLength = bindingList.length; for (var i = 0; i < adds.length; i++) { var item = adds[i]; if (item.index === arrayLength) { bindingList.push(item.value); } else if (item.index === 0) { bindingList.unshift(item.value); } else { bindingList.push(item.value) bindingList.move(arrayLength, item.index); } arrayLength++; } bindingList._winKoChangesSubscriptionDisabled = false; } }, this, "arrayChange"); // Binding list may also change on its accord (i.e. ListView reorder) for which we should update the observable array var bindingListMutationEvents = ["itemchanged", "itemmoved", "itemmutated", "itemremoved", "reload"]; var updateOriginalArray = function () { if (!bindingList._winKoChangesSubscriptionDisabled) { // Disable observable array callbacks to prevent an infinite loop value._winKoChangesSubscriptionDisabled = true; value.removeAll(); for (var i = 0, len = bindingList.length; i < len; i++) { value.push(bindingList.getAt(i)); } value._winKoChangesSubscriptionDisabled = false; } }; bindingListMutationEvents.forEach(function (event) { bindingList.addEventListener(event, updateOriginalArray); }); // Dispose the old subscription or when the element gets disposed ko.utils.domNodeDisposal.addDisposeCallback(sourceElement(), function () { value._winKoChangesSubscription.dispose(); }); } // Only return the binding list data source if it was not set priorly if (!sourceElement()._winKoDataSourceBound) { sourceElement()._winKoDataSourceBound = true; retVal = value._winKoBindingList.dataSource; } } else { retVal = unpacked; } return retVal; } // Helper for itemTemplate changes function itemTemplateWatch(value, oldValue, sourceElement, property) { var retVal = doNotSetOptionOnControl; value = ko.unwrap(value); var template = value; var renderer; sourceElement = sourceElement(); // If the renderer is a string that means we are trying to render a KO template if (typeof value === "string") { renderer = WinJS.UI.simpleItemRenderer(function (item) { var element = document.createElement("div"); ko.renderTemplate(template, item.data, {}, element); return element; }); } else { // Otherwise the template is a WinJS function template renderer = value; } var templateProp = "win" + property + "Old"; if (!oldValue || template !== sourceElement[templateProp]) { sourceElement[templateProp] = template; retVal = renderer; } return retVal; } var controls = { // We need to bind child nodes of AppBar (buttons) before AppBar itself in knockout AppBar: { bindDescendantsBeforeParent: true }, AppBarCommand: { propertyProcessor: { 'type': function (value, appBarCommandElement, update) { if (!appBarCommandElement._winTypeInitialized) { appBarCommandElement._winTypeInitialized = true; return value; } else { console.warn("Cannot change AppBarCommand type after initializing the control"); } } } }, AutoSuggestBox: {}, BackButton: {}, Command: { propertyProcessor: { 'type': function (value, commandElement, update) { if (!commandElement._winTypeInitialized) { commandElement._winTypeInitialized = true; return value; } else { console.warn("Cannot change Command type after initializing the control"); } } } }, ContentDialog: {}, DatePicker: {}, FlipView: { propertyProcessor: { 'itemTemplate': function (value, flipViewElement, current) { return itemTemplateWatch(value, current, flipViewElement, 'ItemTemplate'); }, 'itemDataSource': function (value, flipViewElement, current) { return bindingListWatch(value, current, flipViewElement); } }, bindDescendantsBeforeParent: true }, Flyout: {}, Hub: { bindDescendantsBeforeParent: true, }, HubSection: {}, ItemContainer: {}, ListView: { propertyProcessor: { 'groupHeaderTemplate': function (value, listViewElement, current) { return itemTemplateWatch(value, current, listViewElement, 'GroupHeaderTemplate'); }, 'groupDataSource': function (value, listViewElement, current) { return bindingListWatch(value, current, listViewElement); }, 'itemTemplate': function (value, listViewElement, current) { return itemTemplateWatch(value, current, listViewElement, 'ItemTemplate'); }, 'itemDataSource': function (value, listViewElement, current) { return bindingListWatch(value, current, listViewElement); }, 'layout': function (value, listViewElement, current) { var retVal = doNotSetOptionOnControl; var unpacked = ko.unwrap(value); var listViewElement = listViewElement(); // Only set layout if it's an actually different one if (!current || !isSameLayout(unpacked, listViewElement._winCachedLayout)) { retVal = (unpacked && unpacked.type) ? new unpacked.type(unpacked) : unpacked; listViewElement._winCachedLayout = unpacked; } return retVal; } }, postCtorPropertyProcessor: { // Selection needs to set selection object on the list view and needs the control to be initialized 'selection': function (value, listViewElement, current) { var unpacked = ko.unwrap(value); listViewElement = listViewElement(); // If value is a ko.observableArray, subscribe to selection changes on it if (Array.isArray(unpacked) && ko.isWriteableObservable(value)) { if (!listViewElement._winKoSelectionChangedHandlerSet) { listViewElement.winControl.addEventListener("selectionchanged", function () { var currSelectionArray = listViewElement.winControl.selection.getIndices(); var oldSelection = ko.unwrap(value); if (!arrayShallowEquals(oldSelection, currSelectionArray)) { value(listViewElement.winControl.selection.getIndices()); } }); listViewElement._winKoSelectionChangedHandlerSet = true; } } listViewElement.winControl.selection.set(unpacked); return doNotSetOptionOnControl; } }, bindDescendantsBeforeParent: true }, Menu: { bindDescendantsBeforeParent: true }, MenuCommand: {}, Pivot: { bindDescendantsBeforeParent: true, propertyProcessor: { 'selectedIndex': function (value, pivotElement, current) { // Temporary workaround for selectionchanged not updating this property until WinJS issue #1317 is fixed if (!pivotElement._winKoSelectedIndexHandlerSet) { pivotElement().addEventListener("selectionchanged", function (e) { if (ko.isWriteableObservable(value)) { value(e.detail.index); } }); pivotElement()._winKoSelectedIndexHandlerSet = true; } return ko.unwrap(value); }, 'selectedItem': function (value, pivotElement, current) { // Temporary workaround for selectionchanged not updating this property until WinJS issue #1317 is fixed if (!pivotElement._winKoSelectedItemHandlerSet) { pivotElement().addEventListener("selectionchanged", function (e) { if (ko.isWriteableObservable(value)) { value(pivotElement().winControl.items.getAt(e.detail.index)); } }); pivotElement()._winKoSelectedItemHandlerSet = true; } return ko.unwrap(value); }, } }, PivotItem: {}, Rating: {}, SemanticZoom: { bindDescendantsBeforeParent: true }, SplitView: {}, SplitViewCommand: {}, SplitViewPaneToggle: {}, TimePicker: {}, ToggleSwitch: {}, ToolBar: { bindDescendantsBeforeParent: true }, Tooltip: { propertyProcessor: { 'contentElement': function (value, toolTipElement, current) { var value = ko.unwrap(value); var element = document.querySelector(value); return element; } } }, ViewBox: {} }; // An object to store which event of a control changes what property var eventConfig = { AppBar: { "afterclose": ["opened"], "afteropen": ["opened"] }, AutoSuggestBox: { "querychanged": ["queryText"] }, ContentDialog: { "afterhide": ["hidden"], "aftershow": ["hidden"] }, DatePicker: { "change": ["current"] }, FlipView: { "pageselected": ["currentPage"] }, Flyout: { "afterhide": ["hidden"], "aftershow": ["hidden"] }, Hub: { "loadingstatechanged": ["loadingState"] }, ItemContainer: { "selectionchanged": ["selected"] }, ListView: { "loadingstatechanged": ["loadingState"] }, Menu: { "afterhide": ["hidden"], "aftershow": ["hidden"] }, NavBar: { "afterclose": ["opened"], "afteropen": ["opened"] }, Pivot: null, // "selectionchanged": ["selectedIndex", "selectedItem"] Need a custom hook for selectionchanged // until WinJS #1317 Pivot selectedItem and selectedIndex are not updated on selectionchanged handler is fixed // }, Rating: { "change": ["userRating"] }, SemanticZoom: { "zoomchanged": ["zoomedOut"] }, SplitView: { "afterclose": ["paneOpened"], "afteropen": ["paneOpened"] }, TimePicker: { "change": ["current"] }, ToggleSwitch: { "change": ["checked"] }, ToolBar: { "afterclose": ["opened"], "afteropen": ["opened"] } }; addBindings(controls, eventConfig); })();
require1 = require ("require1"); require2 = require ("require2"); require1.sayHi(); require2.sayHi();
// JavaScript Document // // Persistence Models var Region = persistence.define('Region', { fid: "TEXT", accuracy: "INT", radius: "INT", latitude: "TEXT", longitude: "TEXT", currentlyHere: "TEXT", address: "TEXT", name: "TEXT" }); $('#mainPage').live("pageshow", function() { console.log("page show"); persistence.store.websql.config(persistence, 'regiontracker', 'Region Tracker DB', 5 * 1024 * 1024); persistence.schemaSync(function(tx) { var regions = Region.all(); // Returns QueryCollection of all Projects in Database regions.list(null, function (results) { var list = $( "#mainPage" ).find( ".lstMyRegions" ); //Empty current list list.empty(); //Use template to create items & add to list $( "#regionItem" ).tmpl( results ).appendTo( list ); //Call the listview jQuery UI Widget after adding //items to the list allowing correct rendering list.listview( "refresh" ); }); }); }); $('#projectOptions').live("pageshow", function() { $.mobile.showPageLoadingMsg(); $( "#projectOptions" ).find( ".ui-title" ).html("Loading Project..."); Project.findBy("fid", $.mobile.pageData.fid, function(project) { $( "#projectOptions" ).find( ".ui-title" ).html(project.name); //MIKE TODO - Add Check for notifications here. I hardcoded true for now... var shouldnotify = true; var params = {"fid": project.fid}; DGPTimeTracker.getShouldAutoUpdateProjectEvents( params, function(result) { shouldnotify = (result.shouldautoupdate == 0) ? false:true; $( "#notifyState" ).val((shouldnotify) ? "on" : "off").change(); var here = result.currentlyhere; if(here) { $("#btnCheckin .ui-btn-text").text("Check Out"); } else { $("#btnCheckin .ui-btn-text").text("Check In"); } $.mobile.hidePageLoadingMsg(); }, function(error) { console.log("Error : \r\n"+error); $( "#notifyState" ).val((shouldnotify) ? "on" : "off").change(); $("#btnCheckin .ui-btn-text").text("Check In"); $.mobile.hidePageLoadingMsg(); } ); }); }); $('#map_page').live("pageshow", function() { $('#map_canvas').gmap( { 'center' : new google.maps.LatLng(currentLocation.location.lat, currentLocation.location.lng), 'mapTypeControl' : true } ); $('#map_canvas').gmap('refresh'); $('#map_canvas').gmap('clear', 'markers'); var marker = $('#map_canvas').gmap( 'addMarker',{ id:'m_1', 'position': new google.maps.LatLng(currentLocation.location.lat, currentLocation.location.lng), 'bounds': true , 'animation' : google.maps.Animation.DROP} ) .click(function() { $('#map_canvas').gmap('openInfoWindow', { 'content': currentLocation.name }, this); }); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S8.7_A2; * @section: 8.7; * @assertion: Reference to Self-Modifying Object remain the integrity; * @description: Create a reference to the array, and change original array; */ ////////////////////////////////////////////////////////////////////////////// //CHECK#1 // Create an array of items var items = new Array( "one", "two", "three" ); // Create a reference to the array of items var itemsRef = items; // Add an item to the original array items.push( "four" );var itemsRef = items; // The length of each array should be the same, // since they both point to the same array object if( itemsRef.length !== 4){ $ERROR('#1: var items = new Array( "one", "two", "three" ); var itemsRef = items; items.push( "four" );var itemsRef = items; itemsRef.length !== 4'); }; // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK# // Create an array of items var items = new Array( "one", "two", "three" ); // Create a reference to the array of items var itemsRef = items; // Add an item to the original array items[1]="duo"; // The length of each array should be the same, // since they both point to the same array object if( itemsRef[1] !== "duo"){ $ERROR('#2: var items = new Array( "one", "two", "three" ); var itemsRef = items; items[1]="duo"; itemsRef[1] === "duo". Actual: ' + (itemsRef[1])); }; // //////////////////////////////////////////////////////////////////////////////
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M20 8h-3V4H1v13h2c0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h2v-5l-3-4zM6 18c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm13.5-8.5l1.96 2.5H17V9.5h2.5zM18 18c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /></React.Fragment> , 'LocalShippingSharp');
import React from 'react'; import App from './App'; React.render(<App id="2"/>, document.getElementById('root'));
/* * cliff.js: CLI output formatting tools: "Your CLI Formatting Friend". * * (C) 2010, Nodejitsu Inc. * */ var colors = require('colors'), eyes = require('eyes'), winston = require('winston'); var cliff = exports, logger; cliff.__defineGetter__('logger', function () { return logger; }); cliff.__defineSetter__('logger', function (val) { logger = val; // // Setup winston to use the `cli` formats // if (logger.cli) { logger.cli(); } }); // // Set the default logger for cliff. // cliff.logger = new winston.Logger({ transports: [new winston.transports.Console()] }); // // Expose a default `eyes` inspector. // cliff.inspector = eyes.inspector; cliff.inspect = eyes.inspector({ stream: null, styles: { // Styles applied to stdout all: null, // Overall style applied to everything label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` other: 'inverted', // Objects which don't have a literal representation, such as functions key: 'grey', // The keys in object literals, like 'a' in `{a: 1}` special: 'grey', // null, undefined... number: 'blue', // 0, 1, 2... bool: 'magenta', // true false regexp: 'green' // /\d+/ } }); // // ### function extractFrom (obj, properties) // #### @obj {Object} Object to extract properties from. // #### @properties {Array} List of properties to output. // Creates an array representing the values for `properties` in `obj`. // cliff.extractFrom = function (obj, properties) { return properties.map(function (p) { return obj[p]; }); }; // // ### function columnMajor (rows) // #### @rows {ArrayxArray} Row-major Matrix to transpose // Transposes the row-major Matrix, represented as an array of rows, // into column major form (i.e. an array of columns). // cliff.columnMajor = function (rows) { var columns = []; rows.forEach(function (row) { for (var i = 0; i < row.length; i += 1) { if (!columns[i]) { columns[i] = []; } columns[i].push(row[i]); } }); return columns; }; // // ### arrayLengths (arrs) // #### @arrs {ArrayxArray} Arrays to calculate lengths for // Creates an array with values each representing the length // of an array in the set provided. // cliff.arrayLengths = function (arrs) { var i, lengths = []; for (i = 0; i < arrs.length; i += 1) { lengths.push(longestElement(arrs[i].map(cliff.stringifyLiteral))); } return lengths; }; // // ### function stringifyRows (rows, colors) // #### @rows {ArrayxArray} Matrix of properties to output in row major form // #### @colors {Array} Set of colors to use for the headers // Outputs the specified `rows` as fixed-width columns, adding // colorized headers if `colors` are supplied. // cliff.stringifyRows = function (rows, colors) { var lengths, columns, output = [], headers; columns = cliff.columnMajor(rows); lengths = cliff.arrayLengths(columns); function stringifyRow(row, colorize) { var rowtext = '', padding, item, i, length; for (i = 0; i < row.length; i += 1) { item = cliff.stringifyLiteral(row[i]); item = colorize ? item[colors[i]] : item; length = realLength(item); padding = length < lengths[i] ? lengths[i] - length + 2 : 2; rowtext += item + new Array(padding).join(' '); } output.push(rowtext); } // If we were passed colors, then assume the first row // is the headers for the rows if (colors) { headers = rows.splice(0, 1)[0]; stringifyRow(headers, true); } rows.forEach(function (row) { stringifyRow(row, false); }); return output.join('\n'); }; // // ### function rowifyObjects (objs, properties, colors) // #### @objs {Array} List of objects to create output for // #### @properties {Array} List of properties to output // #### @colors {Array} Set of colors to use for the headers // Extracts the lists of `properties` from the specified `objs` // and formats them according to `cliff.stringifyRows`. // cliff.stringifyObjectRows = cliff.rowifyObjects = function (objs, properties, colors) { var rows = [properties].concat(objs.map(function (obj) { return cliff.extractFrom(obj, properties); })); return cliff.stringifyRows(rows, colors); }; // // ### function putRows (level, rows, colors) // #### @level {String} Log-level to use // #### @rows {Array} Array of rows to log at the specified level // #### @colors {Array} Set of colors to use for the specified row(s) headers. // Logs the stringified table result from `rows` at the appropriate `level` using // `cliff.logger`. If `colors` are supplied then use those when stringifying `rows`. // cliff.putRows = function (level, rows, colors) { cliff.stringifyRows(rows, colors).split('\n').forEach(function (str) { logger.log(level, str); }); }; // // ### function putObjectRows (level, rows, colors) // #### @level {String} Log-level to use // #### @objs {Array} List of objects to create output for // #### @properties {Array} List of properties to output // #### @colors {Array} Set of colors to use for the headers // Logs the stringified table result from `objs` at the appropriate `level` using // `cliff.logger`. If `colors` are supplied then use those when stringifying `objs`. // cliff.putObjectRows = function (level, objs, properties, colors) { cliff.rowifyObjects(objs, properties, colors).split('\n').forEach(function (str) { logger.log(level, str); }); }; // // ### function putObject (obj, [rewriters, padding]) // #### @obj {Object} Object to log to the command line // #### @rewriters {Object} **Optional** Set of methods to rewrite certain object keys // #### @padding {Number} **Optional** Length of padding to put around the output. // Inspects the object `obj` on the command line rewriting any properties which match // keys in `rewriters` if any. Adds additional `padding` if supplied. // cliff.putObject = function (/*obj, [rewriters, padding] */) { var args = Array.prototype.slice.call(arguments), obj = args.shift(), padding = typeof args[args.length - 1] === 'number' && args.pop(), rewriters = typeof args[args.length -1] === 'object' && args.pop(), keys = Object.keys(obj).sort(), sorted = {}, matchers = {}, inspected; padding = padding || 0; rewriters = rewriters || {}; function pad () { for (var i = 0; i < padding / 2; i++) { logger.data(''); } } keys.forEach(function (key) { sorted[key] = obj[key]; }); inspected = cliff.inspect(sorted); Object.keys(rewriters).forEach(function (key) { matchers[key] = new RegExp(key); }); pad(); inspected.split('\n').forEach(function (line) { Object.keys(rewriters).forEach(function (key) { if (matchers[key].test(line)) { line = rewriters[key](line); } }); logger.data(line); }); pad(); }; cliff.stringifyLiteral = function stringifyLiteral (literal) { switch (cliff.typeOf(literal)) { case 'number' : return literal + ''; case 'null' : return 'null'; case 'undefined': return 'undefined'; case 'boolean' : return literal + ''; default : return literal; } }; cliff.typeOf = function typeOf(value) { var s = typeof(value), types = [Object, Array, String, RegExp, Number, Function, Boolean, Date]; if (s === 'object' || s === 'function') { if (value) { types.forEach(function (t) { if (value instanceof t) { s = t.name.toLowerCase(); } }); } else { s = 'null'; } } return s; }; function realLength(str) { return ("" + str).replace(/\u001b\[\d+m/g,'').length; } function longestElement(a) { var l = 0; for (var i = 0; i < a.length; i++) { var new_l = realLength(a[i]); if (l < new_l) { l = new_l; } } return l; }
version https://git-lfs.github.com/spec/v1 oid sha256:687a8eeb0916b40f8152b2d4ffd07fc1ab22ee6195b616368fe8196a0d5e4df2 size 2637
/** * @class AsyncTask * @author Daniel Lidón <dlidon@elconfidencial.com> * @classdesc Clase que permite ejecutar una tarea dada en paralelo lanzandola * en otro hilo. La tarea debe estar preparada para ser lanzada como Worker. * * @constructor * @param {Object} options * @returns {AsyncTask} */ var AsyncTask = function(options) { var default_options = { /** * URL del fichero JS con la tarea que se ejecutará en su propio hilo. * La tarea debe estar preparada para ser lanzada como Worker. * @memberOf AsyncTask# */ task_url: '', /** * Función callback que se ejecuta al completarse la ejecución de la tarea. * @memberOf AsyncTask# * @param {Object} data */ onComplete: function(data) { console.log(data.msg); }, /** * Función callback que se ejecutará cada vez que se consulte el progreso * de la tarea. * @memberOf AsyncTask# * @param {Object} data */ onProgress: function(data) { if (data.val == -1) { console.log("Ejecución del Hilo no iniciada. Inicia el hilo!"); } else { console.log(data.msg + " Progreso: " + data.val + "%"); } }, /** * Función callback que se ejecuta cuando la ejecución del hilo se * detenga. * @memberOf AsyncTask# * @param {Object} data */ onStop: function(data) { console.log(data.msg); }, /** * Función callback que se ejecuta cuando se produce un error en la * ejecución del hilo. * @memberOf AsyncTask# * @param {Object} data */ onError: function(data) { console.log(data.msg); }, task_options: {} }; this.options = jQuery.extend(true, default_options, options); this._progress = 0; /* Contador del progreso del hilo */ this._initiated = false; /* Verdadero si el hilo se ha iniciado correctamente */ this._completed = false; /* Verdadero si el hilo ha acabado su ejecución */ /* Peparando hilo */ var This = this; if (!this.options.task_url) { console.log("Error! Falta argumento: define la url de la tarea en task_url."); return; } this._worker = new Worker(this.options.task_url); /* Control de respuestas del hilo */ this._worker.addEventListener('message', function(event) { var data = event.data; switch (data.cmd) { case 'init' : This._initiated = true; break; case 'complete': This._completed = true; This.options.onComplete(data); break; case 'progress': This._progress = data.val; break; case 'feedback' : console.log(data.msg); break; case 'stop': This.options.onStop(data); break; case 'error': This.options.onError(data); break; default: console.log("Error! El hilo ha tenido un comportamiento no" + " esperado. Msg: " + data); } }, false); /* Control de errores en el código de la tarea */ this._worker.addEventListener('error', function(event) { console.log("Error! Linea " + event.lineno + " en " + event.filename + " : " + event.message); This.options.onError(event); }, false); }; AsyncTask.prototype = { /** * @method init * @memberOf AsyncTask * @desc Lanza el hilo y comienza la ejecución de la tarea. */ init: function() { this._worker.postMessage({'cmd': 'init', 'options': this.options.task_options}); }, /** * @method stop * @memberOf AsyncTask * @desc Para la ejecución de la tarea. */ stop: function() { this._worker.terminate(); this.options.onStop({msg: "Hilo cancelado manualmente."}); }, /** * @method checkProgress * @memberOf AsyncTask * @desc Consulta el progreso de la tarea. */ checkProgress: function() { var This = this; if (!this._initiated) { this.options.onProgress({ msg: "Hilo no iniciado.", 'val': -1 }); return; } if (this._completed) { this.options.onProgress({ msg: "Ejecución del hilo completada.", 'val': 100 }); return; } this.options.onProgress({ msg: "Ejecución del hilo en progreso.", 'val': This._progress }); }, /** * @method isInitiated * @memberOf AsyncTask# * @returns {Boolean} * @desc Devuelve true si el hilo ha iniciado su ejecución. */ isInitiated : function() { return this._initiated; }, /** * @method isCompleted * @memberOf AsyncTask# * @returns {Boolean} * @desc Devuelve true si el hilo ha terminado correctamente su ejecución. */ isCompleted: function() { return this._completed; } };
(function(window) { var re = { not_string: /[^s]/, number: /[dief]/, text: /^[^\x25]+/, modulo: /^\x25{2}/, placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/, key: /^([a-z_][a-z_\d]*)/i, key_access: /^\.([a-z_][a-z_\d]*)/i, index_access: /^\[(\d+)\]/, sign: /^[\+\-]/ } function sprintf() { var key = arguments[0], cache = sprintf.cache if (!(cache[key] && cache.hasOwnProperty(key))) { cache[key] = sprintf.parse(key) } return sprintf.format.call(null, cache[key], arguments) } sprintf.format = function(parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" for (i = 0; i < tree_length; i++) { node_type = get_type(parse_tree[i]) if (node_type === "string") { output[output.length] = parse_tree[i] } else if (node_type === "array") { match = parse_tree[i] // convenience purposes only if (match[2]) { // keyword argument arg = argv[cursor] for (k = 0; k < match[2].length; k++) { if (!arg.hasOwnProperty(match[2][k])) { throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) } arg = arg[match[2][k]] } } else if (match[1]) { // positional argument (explicit) arg = argv[match[1]] } else { // positional argument (implicit) arg = argv[cursor++] } if (get_type(arg) == "function") { arg = arg() } if (re.not_string.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) } if (re.number.test(match[8])) { is_positive = arg >= 0 } switch (match[8]) { case "b": arg = arg.toString(2) break case "c": arg = String.fromCharCode(arg) break case "d": case "i": arg = parseInt(arg, 10) break case "e": arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() break case "f": arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) break case "o": arg = arg.toString(8) break case "s": arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) break case "u": arg = arg >>> 0 break case "x": arg = arg.toString(16) break case "X": arg = arg.toString(16).toUpperCase() break } if (re.number.test(match[8]) && (!is_positive || match[3])) { sign = is_positive ? "+" : "-" arg = arg.toString().replace(re.sign, "") } else { sign = "" } pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " pad_length = match[6] - (sign + arg).length pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) } } return output.join("") } sprintf.cache = {} sprintf.parse = function(fmt) { var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 while (_fmt) { if ((match = re.text.exec(_fmt)) !== null) { parse_tree[parse_tree.length] = match[0] } else if ((match = re.modulo.exec(_fmt)) !== null) { parse_tree[parse_tree.length] = "%" } else if ((match = re.placeholder.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1 var field_list = [], replacement_field = match[2], field_match = [] if ((field_match = re.key.exec(replacement_field)) !== null) { field_list[field_list.length] = field_match[1] while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { if ((field_match = re.key_access.exec(replacement_field)) !== null) { field_list[field_list.length] = field_match[1] } else if ((field_match = re.index_access.exec(replacement_field)) !== null) { field_list[field_list.length] = field_match[1] } else { throw new SyntaxError("[sprintf] failed to parse named argument key") } } } else { throw new SyntaxError("[sprintf] failed to parse named argument key") } match[2] = field_list } else { arg_names |= 2 } if (arg_names === 3) { throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") } parse_tree[parse_tree.length] = match } else { throw new SyntaxError("[sprintf] unexpected placeholder") } _fmt = _fmt.substring(match[0].length) } return parse_tree } var vsprintf = function(fmt, argv, _argv) { _argv = (argv || []).slice(0) _argv.splice(0, 0, fmt) return sprintf.apply(null, _argv) } /** * helpers */ function get_type(variable) { return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() } function str_repeat(input, multiplier) { return Array(multiplier + 1).join(input) } /** * export to either browser or node.js */ if (typeof exports !== "undefined") { exports.sprintf = sprintf exports.vsprintf = vsprintf } else { window.sprintf = sprintf window.vsprintf = vsprintf if (typeof define === "function" && define.amd) { define(function() { return { sprintf: sprintf, vsprintf: vsprintf } }) } } })(typeof window === "undefined" ? this : window);
import React from 'react'; import PropTypes from 'prop-types'; import { Box } from '@strapi/design-system/Box'; import Cross from '@strapi/icons/Cross'; import { Tag } from '@strapi/design-system/Tag'; import { useIntl } from 'react-intl'; const AttributeTag = ({ attribute, filter, onClick, operator, value }) => { const { formatMessage, formatDate, formatTime, formatNumber } = useIntl(); const handleClick = () => { onClick(filter); }; const { fieldSchema } = attribute; const type = fieldSchema?.mainField?.schema.type || fieldSchema.type; let formattedValue = value; if (type === 'date') { formattedValue = formatDate(value, { dateStyle: 'full' }); } if (type === 'datetime') { formattedValue = formatDate(value, { dateStyle: 'full', timeStyle: 'short' }); } if (type === 'time') { const [hour, minute] = value.split(':'); const date = new Date(); date.setHours(hour); date.setMinutes(minute); formattedValue = formatTime(date, { numeric: 'auto', style: 'short', }); } if (['float', 'integer', 'biginteger', 'decimal'].includes(type)) { formattedValue = formatNumber(value); } const content = `${attribute.metadatas.label || attribute.name} ${formatMessage({ id: `components.FilterOptions.FILTER_TYPES.${operator}`, defaultMessage: operator, })} ${operator !== '$null' && operator !== '$notNull' ? formattedValue : ''}`; return ( <Box padding={1} onClick={handleClick}> <Tag icon={<Cross />}>{content}</Tag> </Box> ); }; AttributeTag.propTypes = { attribute: PropTypes.shape({ name: PropTypes.string.isRequired, fieldSchema: PropTypes.object.isRequired, metadatas: PropTypes.shape({ label: PropTypes.string.isRequired }).isRequired, }).isRequired, filter: PropTypes.object.isRequired, onClick: PropTypes.func.isRequired, operator: PropTypes.string.isRequired, value: PropTypes.string.isRequired, }; export default AttributeTag;
goo.V.attachToGlobal(); V.describe('Render pulsating lines of all the different available preset colors.' + '<br>' + 'Colors are, from left to right: white, red, green, blue, aqua, magenta, yellow and black.' + '<br>' + 'The pulsating of lines should affect the amount of render calls.'); var gooRunner = V.initGoo({showStats: true}); var world = gooRunner.world; var lineRenderSystem = new LineRenderSystem(world); gooRunner.setRenderSystem(lineRenderSystem); V.addOrbitCamera(new Vector3(Math.PI * 2, Math.PI / 2.3, 0.2)); var lineSpacing = 0.5; var coloredLinesStart = new Vector3(-4 * lineSpacing, -0.5, 0); //will be set in update var coloredLinesEnd = new Vector3(); var invisibleLineIndex = 0; var invisibleTimer = 0; var invisibleTime = 0.5; var presetColors = [lineRenderSystem.WHITE, lineRenderSystem.RED, lineRenderSystem.GREEN, lineRenderSystem.BLUE, lineRenderSystem.AQUA, lineRenderSystem.MAGENTA, lineRenderSystem.YELLOW, lineRenderSystem.BLACK]; var update = function () { invisibleTimer += world.tpf; while (invisibleTimer >= invisibleTime) { invisibleTimer -= invisibleTime; invisibleLineIndex = (invisibleLineIndex + 1) % 9; } //draw 3 colored lines! for (var i = 0; i < 8; i++) { if (i === invisibleLineIndex) { continue; } var color = presetColors[i]; coloredLinesStart.setDirect(-3.5 * lineSpacing + i * lineSpacing, -0.5, 0); coloredLinesEnd.set(coloredLinesStart).addDirect(0, 1, 0); lineRenderSystem.drawLine(coloredLinesStart, coloredLinesEnd, color); } }; gooRunner.callbacks.push(update); V.process();
// angular.module('core').directive('stick', function($window, $location) { // return function(scope, elem, attrs) { // console.log(elem); // angular.element($window).bind('scroll', function() { // var windowpos = $window.pageYOffset; // var a = elem[0].offsetTop - windowpos; // if (a < 80) { // elem.addClass("fixed-twitter"); // elem.removeClass("col-md-4"); // } else { // elem.removeClass("fixed-twitter"); // elem.addClass("col-md-4"); // } // }); // } // });
(function() { 'use strict'; /** * @description * The sideMenuCtrl lets you quickly have a draggable side * left and/or right menu, which a center content area. */ angular.module('ionic.ui.slideBox', []) /** * The internal controller for the side menu controller. This * extends our core Ionic side menu controller and exposes * some side menu stuff on the current scope. */ .directive('slideBox', ['$compile', function($compile) { return { restrict: 'E', replace: true, transclude: true, controller: ['$scope', '$element', function($scope, $element) { $scope.slides = []; this.slideAdded = function() { $scope.slides.push({}); }; }], scope: {}, template: '<div class="slide-box">\ <div class="slide-box-slides" ng-transclude>\ </div>\ </div>', link: function($scope, $element, $attr, slideBoxCtrl) { // If the pager should show, append it to the slide box if($attr.showPager !== "false") { var childScope = $scope.$new(); var pager = $compile('<pager></pager>')(childScope); $element.append(pager); $scope.slideBox = new ionic.views.SlideBox({ el: $element[0], slideChanged: function(slideIndex) { $scope.$parent.$broadcast('slideBox.slideChanged', slideIndex); } }); } } } }]) .directive('slide', function() { return { restrict: 'E', replace: true, require: '^slideBox', transclude: true, template: '<div class="slide-box-slide" ng-transclude></div>', compile: function(element, attr, transclude) { return function($scope, $element, $attr, slideBoxCtrl) { slideBoxCtrl.slideAdded(); } } } }) .directive('pager', function() { return { restrict: 'E', replace: true, require: '^slideBox', template: '<div class="slide-box-pager"><span ng-repeat="slide in slides"><i class="icon ion-record"></i></span></div>' } }); })();
export default from './Banner'
/** * Neon Login Script * * Developed by Arlind Nushi - www.laborator.co */ var neonLogin = neonLogin || {}; ;(function($, window, undefined) { "use strict"; $(document).ready(function() { neonLogin.$container = $("#form_login"); // Login Form & Validation neonLogin.$container.validate({ rules: { _username: { required: true }, _password: { required: true } }, highlight: function(element){ $(element).closest('.input-group').addClass('validate-has-error'); }, unhighlight: function(element) { $(element).closest('.input-group').removeClass('validate-has-error'); }, submitHandler: function(ev) { /* Updated on v1.1.4 Login form now processes the login data, here is the file: data/sample-login-form.php */ $(".login-page").addClass('logging-in'); // This will hide the login form and init the progress bar // Hide Errors $(".form-login-error").slideUp('fast'); // We will wait till the transition ends setTimeout(function() { var random_pct = 25 + Math.round(Math.random() * 30); // The form data are subbmitted, we can forward the progress to 70% neonLogin.setPercentage(40 + random_pct); // Send data to the server $.ajax({ url: neonLogin.$container.attr('action'), method: 'POST', dataType: 'json', data: { _username: $("input#username").val(), _password: $("input#password").val() }, error: function() { alert("An error occoured!"); }, success: function(response) { // Login status [success|invalid] var login_status = response.login_status; // Form is fully completed, we update the percentage neonLogin.setPercentage(100); // We will give some time for the animation to finish, then execute the following procedures setTimeout(function() { // If login is invalid, we store the if(login_status == 'invalid') { $(".login-page").removeClass('logging-in'); neonLogin.resetProgressBar(true); } else if(login_status == 'success') { // Redirect to login page setTimeout(function() { var redirect_url = baseurl; if(response.redirect_url && response.redirect_url.length) { redirect_url = response.redirect_url; } window.location.href = redirect_url; }, 400); } }, 1000); } }); }, 650); } }); // Lockscreen & Validation var is_lockscreen = $(".login-page").hasClass('is-lockscreen'); if(is_lockscreen) { neonLogin.$container = $("#form_lockscreen"); neonLogin.$ls_thumb = neonLogin.$container.find('.lockscreen-thumb'); neonLogin.$container.validate({ rules: { _password: { required: true } }, highlight: function(element){ $(element).closest('.input-group').addClass('validate-has-error'); }, unhighlight: function(element) { $(element).closest('.input-group').removeClass('validate-has-error'); }, submitHandler: function(ev) { /* Demo Purpose Only Here you can handle the page login, currently it does not process anything, just fills the loader. */ $(".login-page").addClass('logging-in-lockscreen'); // This will hide the login form and init the progress bar // We will wait till the transition ends setTimeout(function() { var random_pct = 25 + Math.round(Math.random() * 30); neonLogin.setPercentage(random_pct, function() { // Just an example, this is phase 1 // Do some stuff... // After 0.77s second we will execute the next phase setTimeout(function() { neonLogin.setPercentage(100, function() { // Just an example, this is phase 2 // Do some other stuff... // Redirect to the page setTimeout("window.location.href = '../../'", 600); }, 2); }, 820); }); }, 650); } }); } // Login Form Setup neonLogin.$body = $(".login-page"); neonLogin.$login_progressbar_indicator = $(".login-progressbar-indicator h3"); neonLogin.$login_progressbar = neonLogin.$body.find(".login-progressbar div"); neonLogin.$login_progressbar_indicator.html('0%'); if(neonLogin.$body.hasClass('login-form-fall')) { var focus_set = false; setTimeout(function(){ neonLogin.$body.addClass('login-form-fall-init') setTimeout(function() { if( !focus_set) { neonLogin.$container.find('input:first').focus(); focus_set = true; } }, 550); }, 0); } else { neonLogin.$container.find('input:first').focus(); } // Focus Class neonLogin.$container.find('.form-control').each(function(i, el) { var $this = $(el), $group = $this.closest('.input-group'); $this.prev('.input-group-addon').click(function() { $this.focus(); }); $this.on({ focus: function() { $group.addClass('focused'); }, blur: function() { $group.removeClass('focused'); } }); }); // Functions $.extend(neonLogin, { setPercentage: function(pct, callback) { pct = parseInt(pct / 100 * 100, 10) + '%'; // Lockscreen if(is_lockscreen) { neonLogin.$lockscreen_progress_indicator.html(pct); var o = { pct: currentProgress }; TweenMax.to(o, .7, { pct: parseInt(pct, 10), roundProps: ["pct"], ease: Sine.easeOut, onUpdate: function() { neonLogin.$lockscreen_progress_indicator.html(o.pct + '%'); drawProgress(parseInt(o.pct, 10)/100); }, onComplete: callback }); return; } // Normal Login neonLogin.$login_progressbar_indicator.html(pct); neonLogin.$login_progressbar.width(pct); var o = { pct: parseInt(neonLogin.$login_progressbar.width() / neonLogin.$login_progressbar.parent().width() * 100, 10) }; TweenMax.to(o, .7, { pct: parseInt(pct, 10), roundProps: ["pct"], ease: Sine.easeOut, onUpdate: function() { neonLogin.$login_progressbar_indicator.html(o.pct + '%'); }, onComplete: callback }); }, resetProgressBar: function(display_errors) { TweenMax.set(neonLogin.$container, {css: {opacity: 0}}); setTimeout(function() { TweenMax.to(neonLogin.$container, .6, {css: {opacity: 1}, onComplete: function() { neonLogin.$container.attr('style', ''); }}); neonLogin.$login_progressbar_indicator.html('0%'); neonLogin.$login_progressbar.width(0); if(display_errors) { var $errors_container = $(".form-login-error"); $errors_container.show(); var height = $errors_container.outerHeight(); $errors_container.css({ height: 0 }); TweenMax.to($errors_container, .45, {css: {height: height}, onComplete: function() { $errors_container.css({height: 'auto'}); }}); // Reset password fields neonLogin.$container.find('input[type="password"]').val(''); } }, 800); } }); // Lockscreen Create Canvas if(is_lockscreen) { neonLogin.$lockscreen_progress_canvas = $('<canvas></canvas>'); neonLogin.$lockscreen_progress_indicator = neonLogin.$container.find('.lockscreen-progress-indicator'); neonLogin.$lockscreen_progress_canvas.appendTo(neonLogin.$ls_thumb); var thumb_size = neonLogin.$ls_thumb.width(); neonLogin.$lockscreen_progress_canvas.attr({ width: thumb_size, height: thumb_size }); neonLogin.lockscreen_progress_canvas = neonLogin.$lockscreen_progress_canvas.get(0); // Create Progress Circle var bg = neonLogin.lockscreen_progress_canvas, ctx = bg.getContext('2d'), imd = null, circ = Math.PI * 2, quart = Math.PI / 2, currentProgress = 0; ctx.beginPath(); ctx.strokeStyle = '#eb7067'; ctx.lineCap = 'square'; ctx.closePath(); ctx.fill(); ctx.lineWidth = 3.0; imd = ctx.getImageData(0, 0, thumb_size, thumb_size); var drawProgress = function(current) { ctx.putImageData(imd, 0, 0); ctx.beginPath(); ctx.arc(thumb_size/2, thumb_size/2, 70, -(quart), ((circ) * current) - quart, false); ctx.stroke(); currentProgress = current * 100; } drawProgress(0/100); neonLogin.$lockscreen_progress_indicator.html('0%'); ctx.restore(); } }); })(jQuery, window);
/** * config/globals.js * * Configuration for globals */ module.exports = { // @TODO make all keys here globals }
module.exports = function( msg, onErr, cb ) { var err = new Error( msg ); onErr( err ); if( cb ) cb( err ); }
/** * @license RequireJS text 2.0.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/requirejs/text for details */ /*jslint regexp: true */ /*global require: false, XMLHttpRequest: false, ActiveXObject: false, define: false, window: false, process: false, Packages: false, java: false, location: false */ define(['module'], function (module) { 'use strict'; var text, fs, progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im, hasLocation = typeof location !== 'undefined' && location.href, defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''), defaultHostName = hasLocation && location.hostname, defaultPort = hasLocation && (location.port || undefined), buildMap = [], masterConfig = (module.config && module.config()) || {}; text = { version: '2.0.5', strip: function (content) { //Strips <?xml ...?> declarations so that external SVG and XML //documents can be added to a document without worry. Also, if the string //is an HTML document, only the part inside the body tag is returned. if (content) { content = content.replace(xmlRegExp, ""); var matches = content.match(bodyRegExp); if (matches) { content = matches[1]; } } else { content = ""; } return content; }, jsEscape: function (content) { return content.replace(/(['\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r") .replace(/[\u2028]/g, "\\u2028") .replace(/[\u2029]/g, "\\u2029"); }, createXhr: masterConfig.createXhr || function () { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else if (typeof ActiveXObject !== "undefined") { for (i = 0; i < 3; i += 1) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } return xhr; }, /** * Parses a resource name into its component parts. Resource names * look like: module/name.ext!strip, where the !strip part is * optional. * @param {String} name the resource name * @returns {Object} with properties "moduleName", "ext" and "strip" * where strip is a boolean. */ parseName: function (name) { var modName, ext, temp, strip = false, index = name.indexOf("."), isRelative = name.indexOf('./') === 0 || name.indexOf('../') === 0; if (index !== -1 && (!isRelative || index > 1)) { modName = name.substring(0, index); ext = name.substring(index + 1, name.length); } else { modName = name; } temp = ext || modName; index = temp.indexOf("!"); if (index !== -1) { //Pull off the strip arg. strip = temp.substring(index + 1) === "strip"; temp = temp.substring(0, index); if (ext) { ext = temp; } else { modName = temp; } } return { moduleName: modName, ext: ext, strip: strip }; }, xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, /** * Is an URL on another domain. Only works for browser use, returns * false in non-browser environments. Only used to know if an * optimized .js version of a text resource should be loaded * instead. * @param {String} url * @returns Boolean */ useXhr: function (url, protocol, hostname, port) { var uProtocol, uHostName, uPort, match = text.xdRegExp.exec(url); if (!match) { return true; } uProtocol = match[2]; uHostName = match[3]; uHostName = uHostName.split(':'); uPort = uHostName[1]; uHostName = uHostName[0]; return (!uProtocol || uProtocol === protocol) && (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) && ((!uPort && !uHostName) || uPort === port); }, finishLoad: function (name, strip, content, onLoad) { content = strip ? text.strip(content) : content; if (masterConfig.isBuild) { buildMap[name] = content; } onLoad(content); }, load: function (name, req, onLoad, config) { //Name has format: some.module.filext!strip //The strip part is optional. //if strip is present, then that means only get the string contents //inside a body tag in an HTML string. For XML/SVG content it means //removing the <?xml ...?> declarations so the content can be inserted //into the current doc without problems. // Do not bother with the work if a build and text will // not be inlined. if (config.isBuild && !config.inlineText) { onLoad(); return; } masterConfig.isBuild = config.isBuild; var parsed = text.parseName(name), nonStripName = parsed.moduleName + (parsed.ext ? '.' + parsed.ext : ''), url = req.toUrl(nonStripName), useXhr = (masterConfig.useXhr) || text.useXhr; //Load the text. Use XHR if possible and in a browser. if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) { text.get(url, function (content) { text.finishLoad(name, parsed.strip, content, onLoad); }, function (err) { if (onLoad.error) { onLoad.error(err); } }); } else { //Need to fetch the resource across domains. Assume //the resource has been optimized into a JS module. Fetch //by the module name + extension, but do not include the //!strip part to avoid file system issues. req([nonStripName], function (content) { text.finishLoad(parsed.moduleName + '.' + parsed.ext, parsed.strip, content, onLoad); }); } }, write: function (pluginName, moduleName, write, config) { if (buildMap.hasOwnProperty(moduleName)) { var content = text.jsEscape(buildMap[moduleName]); write.asModule(pluginName + "!" + moduleName, "define(function () { return '" + content + "';});\n"); } }, writeFile: function (pluginName, moduleName, req, write, config) { var parsed = text.parseName(moduleName), extPart = parsed.ext ? '.' + parsed.ext : '', nonStripName = parsed.moduleName + extPart, //Use a '.js' file name so that it indicates it is a //script that can be loaded across domains. fileName = req.toUrl(parsed.moduleName + extPart) + '.js'; //Leverage own load() method to load plugin value, but only //write out values that do not have the strip argument, //to avoid any potential issues with ! in file names. text.load(nonStripName, req, function (value) { //Use own write() method to construct full module value. //But need to create shell that translates writeFile's //write() to the right interface. var textWrite = function (contents) { return write(fileName, contents); }; textWrite.asModule = function (moduleName, contents) { return write.asModule(moduleName, fileName, contents); }; text.write(pluginName, nonStripName, textWrite, config); }, config); } }; if (masterConfig.env === 'node' || (!masterConfig.env && typeof process !== "undefined" && process.versions && !!process.versions.node)) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); text.get = function (url, callback) { var file = fs.readFileSync(url, 'utf8'); //Remove BOM (Byte Mark Order) from utf8 files if it is there. if (file.indexOf('\uFEFF') === 0) { file = file.substring(1); } callback(file); }; } else if (masterConfig.env === 'xhr' || (!masterConfig.env && text.createXhr())) { text.get = function (url, callback, errback, headers) { var xhr = text.createXhr(), header; xhr.open('GET', url, true); //Allow plugins direct access to xhr headers if (headers) { for (header in headers) { if (headers.hasOwnProperty(header)) { xhr.setRequestHeader(header.toLowerCase(), headers[header]); } } } //Allow overrides specified in config if (masterConfig.onXhr) { masterConfig.onXhr(xhr, url); } xhr.onreadystatechange = function (evt) { var status, err; //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { status = xhr.status; if (status > 399 && status < 600) { //An http 4xx or 5xx error. Signal an error. err = new Error(url + ' HTTP status: ' + status); err.xhr = xhr; errback(err); } else { callback(xhr.responseText); } } }; xhr.send(null); }; } else if (masterConfig.env === 'rhino' || (!masterConfig.env && typeof Packages !== 'undefined' && typeof java !== 'undefined')) { //Why Java, why is this so awkward? text.get = function (url, callback) { var stringBuffer, line, encoding = "utf-8", file = new java.io.File(url), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), content = ''; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // http://www.unicode.org/faq/utf_bom.html // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 if (line && line.length() && line.charAt(0) === 0xfeff) { // Eat the BOM, since we've already found the encoding on this file, // and we plan to concatenating this buffer with others; the BOM should // only appear at the top of a file. line = line.substring(1); } if (line !== null) { stringBuffer.append(line); } while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator); stringBuffer.append(line); } //Make sure we return a JavaScript string and not a Java string. content = String(stringBuffer.toString()); //String } finally { input.close(); } callback(content); }; } return text; });
define([ 'angularjs-wrappers', 'globals', 'helpers', 'jquery-wrappers', 'plumbing' ], function(angularjsWrappers, globals, helpers, jQueryWrappers, plumbing) { /** * @ngdoc overview * @name init * @description * Call the init function once to initialize the FamilySearch object before calling any other functions. */ var exports = {}; /** * @ngdoc function * @name init.functions:init * @function * * @description * Initialize the FamilySearch object * * **Options** * * - `app_key` - the developer key you received from FamilySearch * - `environment` - sandbox, staging, or production * - `http_function` - a function for issuing http requests: `jQuery.ajax` or angular's `$http`, or eventually node.js's ... * - `deferred_function` - a function for creating deferred's: `jQuery.Deferred` or angular's `$q.defer` or eventually `Q` * - `timeout_function` - optional timeout function: angular users should pass `$timeout`; otherwise the global `setTimeout` is used * - `auth_callback` - the OAuth2 redirect uri you registered with FamilySearch. Does not need to exist, * but must have the same host and port as the server running your script * - `auto_expire` - set to true if you want to the system to clear the access token when it has expired * (after one hour of inactivity or 24 hours, whichever comes first; should probably be false for node.js) * - `auto_signin` - set to true if you want the user to be prompted to sign in whenever you call an API function * without an access token (must be false for node.js, and may result in a blocked pop-up if the API call is * not in direct response to a user-initiated action) * - `save_access_token` - set to true if you want the access token to be saved and re-read in future init calls * (uses a session cookie, must be false for node.js) - *setting `save_access_token` along with `auto_signin` and * `auto_expire` is very convenient* * - `access_token` - pass this in if you already have an access token * - `debug` - set to true to turn on console logging during development * * @param {Object} opts opts */ exports.init = function(opts) { opts = opts || {}; if(!opts['app_key']) { throw 'app_key must be set'; } //noinspection JSUndeclaredVariable globals.appKey = opts['app_key']; if(!opts['environment']) { throw 'environment must be set'; } //noinspection JSUndeclaredVariable globals.environment = opts['environment']; if(!opts['http_function']) { throw 'http must be set; e.g., jQuery.ajax'; } var httpFunction = opts['http_function']; if (httpFunction.defaults) { globals.httpWrapper = angularjsWrappers.httpWrapper(httpFunction); } else { globals.httpWrapper = jQueryWrappers.httpWrapper(httpFunction); } if(!opts['deferred_function']) { throw 'deferred_function must be set; e.g., jQuery.Deferred'; } var deferredFunction = opts['deferred_function']; var d = deferredFunction(); d.resolve(); // required for unit tests if (!helpers.isFunction(d.promise)) { globals.deferredWrapper = angularjsWrappers.deferredWrapper(deferredFunction); } else { globals.deferredWrapper = jQueryWrappers.deferredWrapper(deferredFunction); } var timeout = opts['timeout_function']; if (timeout) { globals.setTimeout = function(fn, delay) { return timeout(fn, delay); }; globals.clearTimeout = function(timer) { timeout.cancel(timer); }; } else { // not sure why I can't just set globals.setTimeout = setTimeout, but it doesn't seem to work; anyone know why? globals.setTimeout = function(fn, delay) { return setTimeout(fn, delay); }; globals.clearTimeout = function(timer) { clearTimeout(timer); }; } globals.authCallbackUri = opts['auth_callback']; globals.autoSignin = opts['auto_signin']; globals.autoExpire = opts['auto_expire']; if (opts['save_access_token']) { globals.saveAccessToken = true; helpers.readAccessToken(); } if (opts['access_token']) { globals.accessToken = opts['access_token']; } globals.debug = opts['debug']; // request the discovery resource globals.discoveryPromise = plumbing.get(globals.discoveryUrl); globals.discoveryPromise.then(function(discoveryResource) { globals.discoveryResource = discoveryResource; }); }; return exports; });
var YTAPI = require('../index'); /** * The used Youtube-User 'gronkh' is a famous german lets player, * I just used him to test this functions. Every other should also be working. * * APIKEY must be replaced by a real API Key from Google. * To find out how to get one see: https://developers.google.com/youtube/registering_an_application (you need the API Key) */ var APIKEY = '###########'; //Must be Replaced by your API-Key YTAPI.setup(APIKEY); //Gets all playlists for user 'gronkh' YTAPI.playlistFunctions.getPlaylistsForUser('gronkh').then(function (data) { console.log('All Playlists:'); console.log(data); }); //Gets only 10 playlists for user 'gronkh' YTAPI.playlistFunctions.getPlaylistsForUser('gronkh', 10).then(function (data) { console.log('All Playlists:'); console.log(data); }); //Gets all videos for specified playlistID. YTAPI.playlistFunctions.getVideosForPlaylist('PLGWGc5dfbzn_pvtJg7XskLva9XZpNTI88').then(function (data) { console.log('All Videos:'); console.log(data); }); //Gets 10 videos for specified playlistID. YTAPI.playlistFunctions.getVideosForPlaylist('PLGWGc5dfbzn_pvtJg7XskLva9XZpNTI88', 10).then(function (data) { console.log('All Videos:'); console.log(data); });
initSidebarItems({"struct":[["CrateReader",""]],"fn":[["validate_crate_name",""]]});
describe("Testing array collection property type with its", function() { var classInst = app.getClass('Class/AdvancedDefinition').createInstance(); var prop = classInst.getProperty('propArrayCollectionCollectionArray'); it ("modifying state before manipulations", function() { expect(prop.isModified()).toBe(false); }); it ("value", function() { var value = classInst.getPropArrayCollectionCollectionArray(); expect(value.length).toBe(2); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(0).get(1)).toBe('item12'); expect(value.get(0).get(2)).toBe('item13'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); var data = classInst.getPropArrayCollectionCollectionArray().getData(); expect(data.length).toBe(2); expect(data[0].length).toBe(3); expect(data[0][0]).toBe('item11'); expect(data[0][1]).toBe('item12'); expect(data[0][2]).toBe('item13'); expect(data[1].length).toBe(3); expect(data[1][0]).toBe('item21'); expect(data[1][1]).toBe('item22'); expect(data[1][2]).toBe('item23'); }); it ("ability to set new value", function() { prop.setValue([]); var value = prop.getValue(); expect(value.length).toBe(0); classInst.setPropArrayCollectionCollectionArray([ ['s1'], ['s2'] ]); value = classInst.getPropArrayCollectionCollectionArray(); expect(value.length).toBe(2); expect(value.get(0).length).toBe(1); expect(value.get(0).get(0)).toBe('s1'); expect(value.get(1).length).toBe(1); expect(value.get(1).get(0)).toBe('s2'); value.replaceItems([ ['s3'], ['s4'], ['s5'] ]); value = classInst.getPropArrayCollectionCollectionArray(); expect(value.length).toBe(3); expect(value.get(0).length).toBe(1); expect(value.get(0).get(0)).toBe('s3'); expect(value.get(1).length).toBe(1); expect(value.get(1).get(0)).toBe('s4'); expect(value.get(2).length).toBe(1); expect(value.get(2).get(0)).toBe('s5'); expect(function() { classInst.setPropArrayCollectionCollectionArray("60"); }).toThrow(); expect(function() { classInst.setPropArrayCollectionCollectionArray(['str1', 'str2', 'str3']); }).toThrow(); expect(function() { classInst.setPropArrayCollectionCollectionArray([ [11, 12, 13], [21, 22, 23] ]); }).toThrow(); }); it ("nullable", function() { prop.setValue(null); expect(prop.getValue()).toBe(null); prop.setValue([]); var value = prop.getValue(); value.add([]); value.get(0).add('item11'); value.get(0).add('item12'); value.get(0).add('item13'); value.add([]); value.get(1).add('item21'); value.get(1).add('item22'); value.get(1).add('item23'); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(0).get(1)).toBe('item12'); expect(value.get(0).get(2)).toBe('item13'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); }); it ("manipulations with collection items", function() { var value = classInst.getPropArrayCollectionCollectionArray(); // removing all value.removeItems(); expect(value.length).toBe(0); // add items value.addItems([ [ 'item11' , 'item12', 'item13'], [ 'item21' , 'item22', 'item23'] ]); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(0).get(1)).toBe('item12'); expect(value.get(0).get(2)).toBe('item13'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); // add item value.add([ 'item31', 'item32', 'item33']); value.forEach(function(itemValue, itemIndex) { itemValue.add('item' + (itemIndex + 1) + (itemValue.length + 1)); }); expect(function() { value.add(true); }).toThrow(); expect(value.length).toBe(3); value.forEach(function(itemValue, itemIndex) { expect(/4$/.test(itemValue.get(3))).toBe(true); }); // push item value.push([ 'item41' ]); expect(value.length).toBe(4); expect(value.get(3).get(0)).toBe('item41'); // pop item var removedItem = value.pop(); expect(Array.isArray(removedItem)).toBe(true); expect(removedItem.length).toBe(1); expect(removedItem[0]).toBe('item41'); expect(value.length).toBe(3); // unshift item value.forEach(function(itemValue, itemIndex) { itemValue.unshift('item' + (itemIndex + 1) + '0'); }); expect(value.length).toBe(3); expect(value.get(0).length).toBe(5); expect(value.get(0).get(0)).toBe('item10'); expect(value.get(0).get(1)).toBe('item11'); expect(value.get(0).get(2)).toBe('item12'); expect(value.get(0).get(3)).toBe('item13'); expect(value.get(0).get(4)).toBe('item14'); expect(value.get(1).length).toBe(5); expect(value.get(1).get(0)).toBe('item20'); expect(value.get(1).get(1)).toBe('item21'); expect(value.get(1).get(2)).toBe('item22'); expect(value.get(1).get(3)).toBe('item23'); expect(value.get(1).get(4)).toBe('item24'); expect(value.get(2).length).toBe(5); expect(value.get(2).get(0)).toBe('item30'); expect(value.get(2).get(1)).toBe('item31'); expect(value.get(2).get(2)).toBe('item32'); expect(value.get(2).get(3)).toBe('item33'); expect(value.get(2).get(4)).toBe('item34'); // shift item value.forEach(function(itemValue, itemIndex) { var removed = itemValue.shift(); expect(/0$/.test(removed)).toBe(true); }); removedItem = value.shift(); expect(value.length).toBe(2); expect(removedItem.length).toBe(4); expect(removedItem[0]).toBe('item11'); expect(removedItem[1]).toBe('item12'); expect(removedItem[2]).toBe('item13'); expect(removedItem[3]).toBe('item14'); expect(value.get(0).length).toBe(4); expect(value.get(0).get(0)).toBe('item21'); expect(value.get(0).get(1)).toBe('item22'); expect(value.get(0).get(2)).toBe('item23'); expect(value.get(0).get(3)).toBe('item24'); expect(value.get(1).length).toBe(4); expect(value.get(1).get(0)).toBe('item31'); expect(value.get(1).get(1)).toBe('item32'); expect(value.get(1).get(2)).toBe('item33'); expect(value.get(1).get(3)).toBe('item34'); // remove one item value.unshift(['item11', 'item12', 'item13', 'item14']); removedItem = value.remove(1); expect(Array.isArray(removedItem)).toBe(true); expect(removedItem.length).toBe(4); expect(removedItem[0]).toBe('item21'); expect(removedItem[1]).toBe('item22'); expect(removedItem[2]).toBe('item23'); expect(removedItem[3]).toBe('item24'); expect(value.length).toBe(2); expect(value.isset(2)).toBe(false); expect(function() { prop.get(2); }).toThrow(); expect(value.get(0).length).toBe(4); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(0).get(1)).toBe('item12'); expect(value.get(0).get(2)).toBe('item13'); expect(value.get(0).get(3)).toBe('item14'); expect(value.get(1).length).toBe(4); expect(value.get(1).get(0)).toBe('item31'); expect(value.get(1).get(1)).toBe('item32'); expect(value.get(1).get(2)).toBe('item33'); expect(value.get(1).get(3)).toBe('item34'); // set one item value.set(1, [ 'item21', 'item22', 'item23', 'item24' ]); expect(value.get(1).length).toBe(4); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); expect(value.get(1).get(3)).toBe('item24'); value.set(10, [ 'item10' ]); expect(value.length).toBe(11); expect(value.get(4).length).toBe(0); expect(value.get(7).length).toBe(0); // removing a few items value.removeItems(7, 2); expect(value.length).toBe(9); expect(value.get(8).get(0)).toBe('item10'); value.removeItems(2); expect(value.length).toBe(2); expect(value.get(value.length - 1).get(0)).toBe('item21'); // set a few items value.setItems([ [ "item1" ], [ "item2" ], [ "item3" ], [ "item4" ] ]); expect(value.length).toBe(4); expect(value.get(0).get(0)).toBe('item1'); expect(value.get(1).get(0)).toBe('item2'); expect(value.get(2).get(0)).toBe('item3'); expect(value.get(3).get(0)).toBe('item4'); // replace items value.replaceItems([ [ 'item11', 'item12', 'item13' ], [ 'item21', 'item22', 'item23' ] ]); expect(value.length).toBe(2); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(0).get(1)).toBe('item12'); expect(value.get(0).get(2)).toBe('item13'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); // indexOf method expect(value.indexOf('unexistent')).toBe(-1); expect(value.get(0).indexOf('item12')).toBe(1); expect(value.get(0).indexOf(function(value, key) { return value == 'item13'; })).toBe(2); // lastIndexOf method value.get(0).add('item12'); expect(value.get(0).lastIndexOf('unexistent')).toBe(-1); expect(value.get(0).lastIndexOf(function(value, key) { return value == 'item12'; })).toBe(3); value.get(0).pop(); // join method expect(value.join()).toBe('item11,item12,item13,item21,item22,item23'); expect(value.join('. ')).toBe('item11,item12,item13. item21,item22,item23'); // swap items method value.add(['item31', 'item32', 'item33']); value.swap(0, 2); expect(value.get(0).get(0)).toBe('item31'); expect(value.get(2).get(0)).toBe('item11'); value.swap(0, 2); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(2).get(0)).toBe('item31'); value.swap(1, 2); expect(value.get(1).get(0)).toBe('item31'); expect(value.get(2).get(0)).toBe('item21'); value.swap(1, 2); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(2).get(0)).toBe('item31'); // reverse items order value.reverse(); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item31'); expect(value.get(0).get(1)).toBe('item32'); expect(value.get(0).get(2)).toBe('item33'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); expect(value.get(2).length).toBe(3); expect(value.get(2).get(0)).toBe('item11'); expect(value.get(2).get(1)).toBe('item12'); expect(value.get(2).get(2)).toBe('item13'); value.reverse(); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(0).get(1)).toBe('item12'); expect(value.get(0).get(2)).toBe('item13'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); expect(value.get(2).length).toBe(3); expect(value.get(2).get(0)).toBe('item31'); expect(value.get(2).get(1)).toBe('item32'); expect(value.get(2).get(2)).toBe('item33'); // sort items value.sort(function(a, b) { a = a.get(0); b = b.get(0); if (a > b) { return -1; } else if (a < b) { return 1; } return 0; }); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item31'); expect(value.get(0).get(1)).toBe('item32'); expect(value.get(0).get(2)).toBe('item33'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); expect(value.get(2).length).toBe(3); expect(value.get(2).get(0)).toBe('item11'); expect(value.get(2).get(1)).toBe('item12'); expect(value.get(2).get(2)).toBe('item13'); value.reverse(); // slice method var slicedArr = value.slice(1, 2); expect(slicedArr.length).toBe(1); expect(Array.isArray(slicedArr)).toBe(true); expect(slicedArr[0].get(0)).toBe('item21'); // filter method var filterResult = value.filter(function(itemValue, itemIndex) { return itemValue.get(0) == 'item21' || itemIndex == 2; }); expect(filterResult.length).toBe(2); expect(Array.isArray(filterResult)).toBe(true); expect(filterResult[0].get(0)).toBe('item21'); expect(filterResult[1].get(0)).toBe('item31'); // getting data var data = value.getData(); expect(data[0].length).toBe(3); expect(data[0][0]).toBe('item11'); expect(data[0][1]).toBe('item12'); expect(data[0][2]).toBe('item13'); expect(data[1].length).toBe(3); expect(data[1][0]).toBe('item21'); expect(data[1][1]).toBe('item22'); expect(data[1][2]).toBe('item23'); expect(data[2].length).toBe(3); expect(data[2][0]).toBe('item31'); expect(data[2][1]).toBe('item32'); expect(data[2][2]).toBe('item33'); }); it ("ability to lock its writable capability", function() { expect(prop.isLocked()).toBe(false); prop.lock(); classInst.setPropArrayCollectionCollectionArray([ [ 'str1' ], [ 'str2' ] ]); var value = classInst.getPropArrayCollectionCollectionArray(); expect(value.get(0).length).toBe(3); expect(value.get(0).get(0)).toBe('item11'); expect(value.get(0).get(1)).toBe('item12'); expect(value.get(0).get(2)).toBe('item13'); expect(value.get(1).length).toBe(3); expect(value.get(1).get(0)).toBe('item21'); expect(value.get(1).get(1)).toBe('item22'); expect(value.get(1).get(2)).toBe('item23'); expect(value.get(2).length).toBe(3); expect(value.get(2).get(0)).toBe('item31'); expect(value.get(2).get(1)).toBe('item32'); expect(value.get(2).get(2)).toBe('item33'); prop.unlock(); classInst.setPropArrayCollectionCollectionArray([ [ 'str1' ], [ 'str2' ] ]); value = classInst.getPropArrayCollectionCollectionArray(); expect(value.length).toBe(2); expect(value.get(0).get(0)).toBe('str1'); expect(value.get(1).get(0)).toBe('str2'); }); it ("modifying state after manipulations", function() { expect(prop.isModified()).toBe(true); }); it ("default value", function() { var data = prop.getDefaultValue(); expect(data.length).toBe(2); expect(data[0][0]).toBe('str11'); expect(data[0][1]).toBe('str12'); expect(data[0][2]).toBe('str13'); expect(data[1][0]).toBe('str21'); expect(data[1][1]).toBe('str22'); expect(data[1][2]).toBe('str23'); }); it ("watchers", function() { expect(classInst.changedPropArrayCollectionCollectionArray).toBe(true); expect(classInst.propArrayCollectionCollectionArrayOld.length).toBe(3); expect(classInst.propArrayCollectionCollectionArrayOld[0].length).toBe(3); expect(classInst.propArrayCollectionCollectionArrayOld[0][0]).toBe('item11'); expect(classInst.propArrayCollectionCollectionArrayOld[0][1]).toBe('item12'); expect(classInst.propArrayCollectionCollectionArrayOld[0][2]).toBe('item13'); expect(classInst.propArrayCollectionCollectionArrayOld[1].length).toBe(3); expect(classInst.propArrayCollectionCollectionArrayOld[1][0]).toBe('item21'); expect(classInst.propArrayCollectionCollectionArrayOld[1][1]).toBe('item22'); expect(classInst.propArrayCollectionCollectionArrayOld[1][2]).toBe('item23'); expect(classInst.propArrayCollectionCollectionArrayOld[2].length).toBe(3); expect(classInst.propArrayCollectionCollectionArrayOld[2][0]).toBe('item31'); expect(classInst.propArrayCollectionCollectionArrayOld[2][1]).toBe('item32'); expect(classInst.propArrayCollectionCollectionArrayOld[2][2]).toBe('item33'); expect(classInst.propArrayCollectionCollectionArrayNew.length).toBe(2); expect(classInst.propArrayCollectionCollectionArrayNew[0][0]).toBe('str1'); expect(classInst.propArrayCollectionCollectionArrayNew[1][0]).toBe('str2'); }); });
(function() { define(function(require) { var Color, Context, Mesh, PerspectiveCamera, Scene; Context = require('pex/gl/Context'); Mesh = require('pex/gl/Mesh'); Color = require('pex/color/Color'); PerspectiveCamera = require('pex/scene/PerspectiveCamera'); return Scene = (function() { Scene.prototype.currentCamera = -1; Scene.prototype.clearColor = Color.BLACK; Scene.prototype.clearDepth = true; Scene.prototype.viewport = null; function Scene() { this.drawables = []; this.cameras = []; this.gl = Context.currentContext.gl; } Scene.prototype.setClearColor = function(color) { return this.clearColor = color; }; Scene.prototype.setClearDepth = function(clearDepth) { return this.clearDepth = clearDepth; }; Scene.prototype.setViewport = function(viewport) { return this.viewport = viewport; }; Scene.prototype.add = function(obj) { if (obj.draw) { this.drawables.push(obj); } if (obj instanceof PerspectiveCamera) { return this.cameras.push(obj); } }; Scene.prototype.remove = function(obj) { var index; index = this.drawables.indexOf(obj); if (index !== -1) { return this.drawables.splice(index, 1); } }; Scene.prototype.clear = function() { var clearBits; clearBits = 0; if (this.clearColor) { this.gl.clearColor(this.clearColor.r, this.clearColor.g, this.clearColor.b, this.clearColor.a); clearBits |= this.gl.COLOR_BUFFER_BIT; } if (this.clearDepth) { clearBits |= this.gl.DEPTH_BUFFER_BIT; } if (clearBits) { return this.gl.clear(clearBits); } }; Scene.prototype.draw = function(camera) { var aspectRatio, drawable, _i, _len, _ref; if (!camera) { if (this.currentCamera >= 0 && this.currentCamera < this.cameras.length) { camera = this.cameras[this.currentCamera]; } else if (this.cameras.length > 0) { camera = this.cameras[0]; } else { throw 'Scene.draw: missing a camera'; } } if (this.viewport) { this.viewport.bind(); aspectRatio = this.viewport.bounds.width / this.viewport.bounds.height; if (camera.getAspectRatio() !== aspectRatio) { camera.setAspectRatio(aspectRatio); } } this.clear(); _ref = this.drawables; for (_i = 0, _len = _ref.length; _i < _len; _i++) { drawable = _ref[_i]; if (drawable.enabled !== false) { drawable.draw(camera); } } if (this.viewport) { return this.viewport.unbind(); } }; return Scene; })(); }); }).call(this);
/* * */ var qure = require('../src/qure.js'); describe('Trying out', function() { /* * */ it('sequence', function(done) { qure .sequence('test1', function(arg) { // notice that "this" context is "Qure" this.wait(500) .then(function() { console.log(arg); }); }) .sequence('test2', function(arg) { // notice that "this" context is "Qure" this.wait(1000) .then(function() { console.log(arg); done(); }); }); qure.run('test1', 5); qure.run('test2', 10); }); });
var SerialPort = require("serialport"); var intel_hex = require('intel-hex'); // require version 1 of stk500 var stk500 = require('../').v1; var async = require("async"); var fs = require('fs'); var usbttyRE = /(cu\.usb|ttyACM|COM\d+)/; var data = fs.readFileSync('arduino-1.0.6/uno/Blink.cpp.hex', { encoding: 'utf8' }); var hex = intel_hex.parse(data).data; //TODO standardize chip configs //uno var pageSize = 128; var baud = 115200; var delay1 = 1; //minimum is 2.5us, so anything over 1 fine? var delay2 = 1; var signature = new Buffer([0x1e, 0x95, 0x0f]); var options = { pagesizelow:pageSize }; SerialPort.list(function (err, ports) { ports.forEach(function(port) { console.log("found " + port.comName); if(usbttyRE.test(port.comName)) { console.log("trying" + port.comName); var serialPort = new SerialPort.SerialPort(port.comName, { baudrate: baud, parser: SerialPort.parsers.raw }, false); var programmer = new stk500(serialPort); async.series([ programmer.connect.bind(programmer), programmer.reset.bind(programmer,delay1, delay2), programmer.sync.bind(programmer, 3), programmer.verifySignature.bind(programmer, signature), programmer.setOptions.bind(programmer, options), programmer.enterProgrammingMode.bind(programmer), programmer.upload.bind(programmer, hex, pageSize), programmer.exitProgrammingMode.bind(programmer) ], function(error){ programmer.disconnect(); if(error){ console.log("programing FAILED: " + error); process.exit(1); }else{ console.log("programing SUCCESS!"); process.exit(0); } }); }else{ console.log("skipping " + port.comName); } }); });
'use strict'; module.exports = { title: 'PM01', unit: 'µg/m³', sensorType: 'PMS 3003', icon: 'osem-cloud' };
Ext.namespace('Phlexible.users.security'); Phlexible.users.security.LoginWindow = Ext.extend(Ext.Window, { modal: false, closable: false, collapsible: false, draggable: false, resizable: false, border: false, shadow: true, width: 420, height: 400, layout: 'border', cls: 'p-security-login-window', initComponent: function () { this.items = [ { region: 'north', height: 145, frame: false, border: true, style: 'text-align: center;', html: '<img src="' + Phlexible.bundlePath + '/phlexiblegui/images/logo.gif" width="300" height="120" style="padding-top: 15px" />' }, { region: 'center', xtype: 'form', bodyStyle: 'padding: 10px;', labelWidth: 100, frame: true, monitorValid: true, url: this.checkPath, standardSubmit: true, listeners: { render: function (c) { c.form.el.dom.action = this.checkPath; }, scope: this }, items: [ { frame: false, border: false, bodyStyle: 'padding-bottom: 10px; text-align: center;', html: this.enterUsernamePasswordText }, { frame: false, border: false, bodyStyle: 'padding-bottom: 10px; text-align: center; color: red;', html: this.errorMessage || '' }, { xtype: 'hidden', name: '_csrf_token', value: this.csrfToken }, { xtype: 'textfield', anchor: '100%', fieldLabel: this.usernameText, labelSeparator: "", name: '_username', msgTarget: 'under', allowBlank: false, value: this.lastUsername || '' }, { xtype: 'textfield', inputType: 'password', anchor: '100%', fieldLabel: this.passwordText, labelSeparator: "", name: '_password', msgTarget: 'under', allowBlank: false }, { xtype: 'checkbox', anchor: '100%', labelSeparator: '', fieldLabel: '', boxLabel: this.rememberMeText, name: '_remember_me', msgTarget: 'under', allowBlank: false } ], bindHandler: function () { var valid = true; this.form.items.each(function (f) { if (!f.isValid(true)) { valid = false; return false; } }); if (this.ownerCt.buttons) { for (var i = 0, len = this.ownerCt.buttons.length; i < len; i++) { var btn = this.ownerCt.buttons[i]; if (btn.formBind === true && btn.disabled === valid) { btn.setDisabled(!valid); } } } this.fireEvent('clientvalidation', this, valid); } } ]; this.buttons = [ { text: this.lostPasswordText, handler: function() { document.location.href = this.resetUrl }, scope: this }, { text: this.submitText, formBind: true, iconCls: 'p-user-login-icon', handler: this.submit, scope: this } ]; this.on({ render: function (c) { var keyMap = this.getKeyMap(); keyMap.addBinding({ key: Ext.EventObject.ENTER, fn: this.submit, scope: this }); }, show: this.focusField, move: this.focusField, resize: this.focusField, scope: this }); Phlexible.users.security.LoginWindow.superclass.initComponent.call(this); }, focusField: function () { var c; if (this.getUsernameField().getValue()) { c = this.getPasswordField(); } else { c = this.getUsernameField(); } c.focus(false, 10); }, getUsernameField: function () { return this.getComponent(1).getComponent(3); }, getPasswordField: function () { return this.getComponent(1).getComponent(4); }, submit: function () { var form = this.getComponent(1).getForm(); if (!form.isValid()) return; form.submit(); } });
/*jshint esversion: 6 */ const md5 = require('js-md5'); const {User, Room, Note, db} = require('./db-config'); const createNewRoom = ({topic, className, lecturer, hostId}, cb) => { const pathUrl = generatePathUrl(topic + className + lecturer + hostId); Room.create({ pathUrl: pathUrl, topic: topic, className: className, lecturer: lecturer, hostId: hostId }) .then(roomInfo => cb(roomInfo)); }; const generatePathUrl = data => md5(data + Math.random()).slice(0, 5); const joinRoom = (userId, pathUrl, cb) => { User.findById(userId) .then(currentUser => { Room.findOne({ where: { pathUrl: pathUrl } }) .then(currentRoom => { currentUser.addRoom(currentRoom) .then(() => cb(currentRoom)); }); }); }; const createNewNote = (note, cb) => { note.editingUserId = note.originalUserId; note.show = true; Note.create(note) .then(cb) .catch(cb); }; const multiplyNotes = (notes, arrOfClients) => { let multipliedNotes = []; for (let i = 0; i < notes.length; i++) { for (let j = 0; j < arrOfClients.length; j++) { if (notes[i].originalUserId !== Number(arrOfClients[j]) && !notes[i].thought) { var copy = JSON.parse(JSON.stringify(notes[i])); copy.editingUserId = arrOfClients[j]; copy.show = false; multipliedNotes.push(copy); } } multipliedNotes.push(notes[i]); } return multipliedNotes; }; const createRoomNotes = (notes, roomId, arrOfClients, cb) => { notes = notes.map(note => { note.roomId = roomId; return note; }); notes = multiplyNotes(notes, arrOfClients); Note.bulkCreate(notes) .then(() => cb()); }; const showAllNotes = ({userId, roomId}, cb) => { Note.findAll({ where: { editingUserId: userId }, include: { model: Room, where: { id: roomId }, attributes: [] } }) .then(allNotes => cb(allNotes)); }; const showFilteredNotes = ({userId, roomId}, cb) => { Note.findAll({ where: { editingUserId: userId, show: true }, include: { model: Room, where: { id: roomId }, attributes: [] } }) .then(allNotes => cb(allNotes)); }; const updateNotes = (userId, roomId, allNotes, cb) => { let promises = []; const updateOneNote = note => { Note.update(note, { where: { id: note.id, editingUserId: userId, roomId: roomId } }); // .then(data => console.log('notes deleted:', data)); }; for (let i = 0; i < allNotes.length; i++) { promises.push(updateOneNote(allNotes[i])); } Promise.all(promises).then((data) => { cb(null); }, error => { console.log('ERROR', error); cb(error); }); }; const findRoom = (pathUrl, cb) => { Room.findOne({ where: {pathUrl: pathUrl} }) .then(cb); }; const getAllUserRooms = (userId, cb) => { User.findById(userId) .then((user) => user.getRooms({raw: true})) .then(cb); }; const getRoom = (pathUrl, userId, cb) => { User.findById(userId) .then((user) => user.getRooms({where: {pathUrl: pathUrl}, raw: true})) .then((room) => { // can be optimized with promises... nice to have later getRoomParticipants(pathUrl, ({users}) => { cb({ roomInfo: room[0], participants: users }); }); }); }; const saveAudioToRoom = (pathUrl, audioUrl, cb) => { Room.update({audioUrl: audioUrl}, {where: {pathUrl: pathUrl}}) .then(cb); }; const saveStartTimestamp = (pathUrl, startTimestamp) => { Room.update({startTimestamp}, {where: {pathUrl}}); }; const saveTimeLength = (pathUrl, endTimestamp) => { Room.findOne({where: {pathUrl}}) .then(room => callback(room.startTimestamp)); var callback = (start) => { let timeLength = endTimestamp - start; Room.update({timeLength}, {where: {pathUrl}}); }; }; const getAudioForRoom = (pathUrl, cb) => { Room.findOne({ where: { pathUrl }, raw: true}) .then(room => cb(room.audioUrl)); }; const deleteNotes = (noteIds, cb) => { const promises = noteIds.map((id) => { return Note.destroy({ where: {id} }); }); Promise.all(promises) .then( data => cb(null, data), cb ); }; const deleteANote = (id, cb) => { Note.destroy({ where: {id} }) .then( data => cb(null, data), cb ); }; const getRoomParticipants = (pathUrl, cb) => { Room.findOne({ attributes: [], where: { pathUrl }, include: { model: User, through: { attributes: [] } } }) .then(cb); }; const deleteNotebook = (userId, roomId, cb) => { User.findById(userId) .then((user) => user.removeRoom(roomId)) .then(cb); }; module.exports = { createNewRoom, generatePathUrl, joinRoom, showAllNotes, showFilteredNotes, findRoom, createRoomNotes, multiplyNotes, updateNotes, getAllUserRooms, getRoom, saveAudioToRoom, createNewNote, saveStartTimestamp, saveTimeLength, getAudioForRoom, deleteNotes, deleteANote, deleteNotebook, };
/** * [Javascript core part]: swfobject 扩展 */ Jx().$package(function(J){ /* SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ /** * @namespace swfobject 名字空间 * @name swfobject */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ /** * @ignore */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ /** * @ignore */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its style are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; /** * @ignore */ win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.style.position = 'absolute'; o.style.left = '-9999px'; o.style.top = '-9999px'; o.style.width = '1px'; o.style.height = '1px'; o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, /** * swfobject 嵌入flash的方法 * * @memberOf swfobject * * @param {String} path swf文件的路径 * @returns * * @example * Jx().$package(function(J){ * J.swfobject.embedSWF( path, 'swfSound_Flash_div', '1', '1', '8.0.0', './expressInstall.swf', flashvars, params, attributes); * }; * */ embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }(); J.swfobject = swfobject; ;(function(){ // Flash Player Version Detection - Rev 1.6 // Detect Client Browser type // Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; function ControlVersion() { var version; var axo; var e; // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry try { // version will be set for 7.X or greater players axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); version = axo.GetVariable("$version"); } catch (e) { } if (!version) { try { // version will be set for 6.X players only axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); // installed player is some revision of 6.0 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29, // so we have to be careful. // default to the first public version version = "WIN 6,0,21,0"; // throws if AllowScripAccess does not exist (introduced in 6.0r47) axo.AllowScriptAccess = "always"; // safe to call for 6.0r47 or greater version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 4.X or 5.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 3.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = "WIN 3,0,18,0"; } catch (e) { } } if (!version) { try { // version will be set for 2.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); version = "WIN 2,0,0,11"; } catch (e) { version = -1; } } return version; } // JavaScript helper required to detect Flash Player PlugIn version information function GetSwfVer(){ // NS/Opera version >= 3 check for Flash plugin in plugin array var flashVer = -1; if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; var descArray = flashDescription.split(" "); var tempArrayMajor = descArray[2].split("."); var versionMajor = tempArrayMajor[0]; var versionMinor = tempArrayMajor[1]; var versionRevision = descArray[3]; if (versionRevision == "") { versionRevision = descArray[4]; } if (versionRevision[0] == "d") { versionRevision = versionRevision.substring(1); } else if (versionRevision[0] == "r") { versionRevision = versionRevision.substring(1); if (versionRevision.indexOf("d") > 0) { versionRevision = versionRevision.substring(0, versionRevision.indexOf("d")); } } var flashVer = versionMajor + "." + versionMinor + "." + versionRevision; //alert("flashVer="+flashVer); } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; else if ( isIE && isWin && !isOpera ) { flashVer = ControlVersion(); } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) { var versionStr = GetSwfVer(); if (versionStr == -1 ) { return false; } else if (versionStr != 0) { var tempArray, tempString, versionArray; if(isIE && isWin && !isOpera) { // Given "WIN 2,0,0,11" tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"] tempString = tempArray[1]; // "2,0,0,11" versionArray = tempString.split(","); // ['2', '0', '0', '11'] } else { versionArray = versionStr.split("."); } var versionMajor = versionArray[0]; var versionMinor = versionArray[1]; var versionRevision = versionArray[2]; // is the major.revision >= requested major.revision AND the minor version >= requested minor if (versionMajor > parseFloat(reqMajorVer)) { return true; } else if (versionMajor == parseFloat(reqMajorVer)) { if (versionMinor > parseFloat(reqMinorVer)) return true; else if (versionMinor == parseFloat(reqMinorVer)) { if (versionRevision >= parseFloat(reqRevision)) return true; } } return false; } } function AC_AddExtension(src, ext) { if (src.indexOf('?') != -1) return src.replace(/\?/, ext+'?'); else return src + ext; } function AC_Generateobj(objAttrs, params, embedAttrs) { var str = ''; if (isIE && isWin && !isOpera) { str += '<object '; for (var i in objAttrs) str += i + '="' + objAttrs[i] + '" '; for (var i in params) str += '><param name="' + i + '" value="' + params[i] + '" /> '; str += '></object>'; } else { str += '<embed '; for (var i in embedAttrs) str += i + '="' + embedAttrs[i] + '" '; str += '> </embed>'; } document.write(str); } function AC_FL_RunContent(){ var ret = AC_GetArgs ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" , "application/x-shockwave-flash" ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_GetArgs(args, ext, srcParamName, classid, mimeType){ var ret = new Object(); ret.embedAttrs = new Object(); ret.params = new Object(); ret.objAttrs = new Object(); for (var i=0; i < args.length; i=i+2){ var currArg = args[i].toLowerCase(); switch (currArg){ case "classid": break; case "pluginspage": ret.embedAttrs[args[i]] = args[i+1]; break; case "src": case "movie": args[i+1] = AC_AddExtension(args[i+1], ext); ret.embedAttrs["src"] = args[i+1]; ret.params[srcParamName] = args[i+1]; break; case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblClick": case "ondrag": case "ondragend": case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown": case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload": case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart": case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": case "type": case "codebase": ret.objAttrs[args[i]] = args[i+1]; break; case "id": case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name": case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1]; break; default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1]; } } ret.objAttrs["classid"] = classid; if (mimeType) ret.embedAttrs["type"] = mimeType; return ret; } J.GetSwfVer= GetSwfVer; })(); });
Package.describe({ summary: "Latest version of Ionicons", version: "2.0.1_1", name: "pagebakers:ionicons", git: "https://github.com/Pagebakers/meteor-ionicons.git" }); Package.onUse(function (api){ api.addFiles([ 'ionicons.js' ], 'client'); });
import { Box } from '@rocket.chat/fuselage'; import React, { forwardRef } from 'react'; const UserCardContainer = forwardRef(function UserCardContainer(props, ref) { return ( <Box rcx-user-card bg='surface' elevation='2' p='x24' display='flex' borderRadius='x2' width='439px' {...props} ref={ref} /> ); }); export default UserCardContainer;
function $ViewScrollProvider(){var e=!1;this.useAnchorScroll=function(){e=!0},this.$get=["$anchorScroll" ,"$timeout",function(t,n){return e?t:function(e){n(function(){e[0].scrollIntoView()},0,!1)}}]}angular .module("ui.router.state").provider("$uiViewScroll",$ViewScrollProvider);
define(function(require) { 'use strict'; const InterWindowMediator = require('oroui/js/app/services/inter-window-mediator/inter-window-mediator'); return new InterWindowMediator; });
import tools from "crankshaft-tools"; import optimist from "optimist"; import path from "path"; import fsutils from "../utils/fs"; import { print, getLogger } from "../utils/logging"; import cli from "../utils/cli"; const argv = optimist.argv; const printSyntax = (msg) => { if (msg) { print(`Error: ${msg}`); } print(`Usage: fora new <template> <project_name> [-d <destination>] [--recreate]`); process.exit(); }; const getArgs = function() { const args = cli.getArgs(); if (args.length < 5) { printSyntax(); } /* params */ const template = args[3]; const name = args[4].trim().replace(/\s+/g, '-').toLowerCase(); return { template, name }; }; /* Copy files from the template directory to the destination directory. */ const copyTemplateFiles = async function() { const logger = getLogger(argv.quiet || false); const { template, name } = getArgs(); const destination = path.join((argv.d || argv.destination || "./"), name); const destinationExists = await fsutils.exists(destination); //Make sure the directory is empty or the recreate flag is on if (destinationExists && !argv.recreate) { print(`Conflict: ${path.resolve(destination)} is not empty. Delete the directory manually or use --recreate.`); } else { if (destinationExists) { if (argv.recreate) { print(`Deleting ${destination}`); await fsutils.remove(destination); await fsutils.mkdirp(destination); } } else { await fsutils.mkdirp(destination); } //Copy template const _shellExec = tools.process.spawn({ stdio: "inherit" }); const shellExec = async function(cmd) { await _shellExec("sh", ["-c", cmd]); }; const exec = tools.process.exec(); const templatePath = await resolveTemplatePath(template); logger(`Copying ${templatePath} -> ${destination}`); await fsutils.copyRecursive(templatePath, destination, { forceDelete: true }); //Install npm dependencies. const curdir = await exec(`pwd`); process.chdir(destination); await shellExec(`npm install`); process.chdir(curdir); //Let's overwrite package.json const packageJsonPath = path.join(destination, "package.json"); const packageJson = await fsutils.readFile(packageJsonPath); const packageInfo = JSON.parse(packageJson); packageInfo.name = name; packageInfo.description = argv["set-package-description"] || "Description for your project"; packageInfo.version = argv["set-package-version"] || "0.0.1"; packageInfo.homepage = argv["set-package-homepage"] || "Your home page"; packageInfo.repository = { type: argv["set-package-repository-type"] || "git", url: argv["set-package-repository-url"] || "https://example.com/your/repository/path" }; packageInfo.author = argv["set-package-author"] || "Your name"; packageInfo.email = argv["set-package-email"] || "youremail@example.com"; packageInfo.bugs = argv["set-package-bugs"] || "http://www.example.com/bugzilla/your-project"; await fsutils.writeFile(path.join(destination, "package.json"), JSON.stringify(packageInfo, null, 4)); print(`New ${template} site installed in ${path.resolve(destination)}.`); } }; /* Search paths are: a) Current node_modules directory b) ~/.fora/templates/node_modules */ const resolveTemplatePath = async function(name) { const templateName = /^fora-template-/.test(name) ? name : `fora-template-${name}`; //Current node_modules_dir const node_modules_templatePath = path.resolve(GLOBAL.__libdir, "../node_modules", name); const node_modules_prefixedTemplatePath = path.resolve(GLOBAL.__libdir, "../node_modules", `fora-template-${name}`); /* Templates can also be under ~/.fora/templates/example-template ~/.fora/templates/node_modules/example-template */ const HOME_DIR = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE; const HOME_templatePath = path.resolve(`${HOME_DIR}/.fora/templates`, name); const HOME_prefixedTemplatePath = path.resolve(`${HOME_DIR}/.fora/templates`, `fora-template-${name}`); const HOME_node_modules_templatePath = path.resolve(`${HOME_DIR}/.fora/templates/node_modules`, name); const HOME_node_modules_prefixedTemplatePath = path.resolve(`${HOME_DIR}/.fora/templates/node_modules`, `fora-template-${name}`); const paths = [ node_modules_templatePath, node_modules_prefixedTemplatePath, HOME_templatePath, HOME_prefixedTemplatePath, HOME_node_modules_templatePath, HOME_node_modules_prefixedTemplatePath ]; for (let templatePath of paths) { if (await fsutils.exists(templatePath)) { return templatePath; } } throw new Error(`Template "${name}" or "fora-template-${name}" was not found.`); }; export default copyTemplateFiles;
beforeEach(function() { global.disableOptInFeatures(); global.addToEqualMatchMatcher(); }); describe('XRegExp.matchRecursive addon:', function() { describe('XRegExp.matchRecursive()', function() { it('should pass the readme example for basic usage', function() { var str = '(t((e))s)t()(ing)'; expect(XRegExp.matchRecursive(str, '\\(', '\\)', 'g')).toEqual(['t((e))s', '', 'ing']); }); it('should pass the readme example for extended information mode with valueNames', function() { var str = 'Here is <div> <div>an</div></div> example'; expect( XRegExp.matchRecursive(str, '<div\\s*>', '</div>', 'gi', { valueNames: ['between', 'left', 'match', 'right'] })) .toEqual([ {name: 'between', value: 'Here is ', start: 0, end: 8}, {name: 'left', value: '<div>', start: 8, end: 13}, {name: 'match', value: ' <div>an</div>', start: 13, end: 27}, {name: 'right', value: '</div>', start: 27, end: 33}, {name: 'between', value: ' example', start: 33, end: 41} ]); }); it('should pass the readme example for omitting unneeded parts with null valueNames and using escapeChar', function() { var str = '...{1}.\\{{function(x,y){return {y:x}}}'; expect( XRegExp.matchRecursive(str, '{', '}', 'g', { valueNames: ['literal', null, 'value', null], escapeChar: '\\' })) .toEqual([ {name: 'literal', value: '...', start: 0, end: 3}, {name: 'value', value: '1', start: 4, end: 5}, {name: 'literal', value: '.\\{', start: 6, end: 9}, {name: 'value', value: 'function(x,y){return {y:x}}', start: 10, end: 37} ]); }); it('should pass the readme example for sticky mode via flag y', function() { var str = '<1><<<2>>><3>4<5>'; expect(XRegExp.matchRecursive(str, '<', '>', 'gy')).toEqual(['1', '<<2>>', '3']); }); // TODO: Add complete specs }); });
gd.Spinner = function() { var opts = { lines: 13, // The number of lines to draw length: 20, // The length of each line width: 10, // The line thickness radius: 30, // The radius of the inner circle corners: 1, // Corner roundness (0..1) rotate: 0, // The rotation offset direction: 1, // 1: clockwise, -1: counterclockwise color: '#000', // #rgb or #rrggbb or array of colors speed: 1, // Rounds per second trail: 60, // Afterglow percentage shadow: false, // Whether to render a shadow hwaccel: false, // Whether to use hardware acceleration className: 'spinner', // The CSS class to assign to the spinner zIndex: 2e9, // The z-index (defaults to 2000000000) top: ($(window).height() / 2) + 'px', // Top position relative to parent in px left: ($(window).width() / 2) + 'px'// Left position relative to parent in px }; this.spinnerDelegate = new Spinner(opts); }; /** * Attaches the spinner to the target, or body by default, and starts * spinning. */ gd.Spinner.prototype.spin = function(opt_target) { var target = opt_target || document.body; this.spinnerDelegate.spin(target); }; /** Stops the spinner. */ gd.Spinner.prototype.stop = function() { this.spinnerDelegate.stop(); };
module.exports={A:{A:{"2":"H D G E A B EB"},B:{"2":"C p x J L N I"},C:{"2":"0 1 2 3 4 5 6 8 9 ZB BB F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y XB RB"},D:{"2":"0 1 2 3 4 5 6 8 9 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y LB GB FB bB a HB IB JB"},E:{"2":"F K H D G E A B C KB CB MB NB OB PB QB z SB"},F:{"2":"0 7 E B C J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w TB UB VB WB z AB YB"},G:{"2":"CB aB DB cB","129":"G dB eB fB gB hB iB jB kB lB"},H:{"2":"mB"},I:{"1":"BB F a qB DB rB sB","2":"nB","257":"oB pB"},J:{"1":"A","16":"D"},K:{"1":"M","2":"7 A B C z AB"},L:{"1":"a"},M:{"2":"y"},N:{"2":"A B"},O:{"516":"tB"},P:{"1":"F K uB vB"},Q:{"16":"wB"},R:{"1":"xB"}},B:4,C:"HTML Media Capture"};
import Ember from 'ember'; import DS from 'ember-data'; import ModelWithoutValidation from './model-without-validation'; import EmberValidations from 'ember-validations'; /** Base model that supports projections, validations and copying. @module ember-flexberry-data @class Model @namespace Projection @extends ModelWithoutValidation @uses EmberValidationsMixin @event preSave @param {Object} event Event object @param {Promise[]} promises Array to which custom 'preSave' promises could be pushed @public */ var Model = ModelWithoutValidation.extend(EmberValidations, { /** Model validation rules. @property validations @type Object @default {} */ validations: {}, /** Checks that model satisfies validation rules defined in 'validations' property. @method validate @param {Object} [options] Method options @param {Boolean} [options.validateDeleted = true] Flag: indicates whether to validate model, if it is deleted, or not @return {Promise} A promise that will be resolved if model satisfies validation rules defined in 'validations' property */ validate(options) { options = Ember.merge({ validateDeleted: true }, options || {}); if (options.validateDeleted === false && this.get('isDeleted')) { // Return resolved promise, because validation is unnecessary for deleted model. return new Ember.RSVP.Promise((resolve) => { resolve(); }); } // Validate model. let validationPromises = { base: this._super(options) }; let hasManyRelationships = Ember.A(); this.eachRelationship((name, attrs) => { if (attrs.kind === 'hasMany') { hasManyRelationships.pushObject(attrs.key); } }); // Validate hasMany relationships. hasManyRelationships.forEach((relationshipName) => { let details = this.get(relationshipName); if (!Ember.isArray(details)) { details = Ember.A(); } details.forEach((detailModel, i) => { validationPromises[relationshipName + '.' + i] = detailModel.validate(options); }); }); return new Ember.RSVP.Promise((resolve, reject) => { Ember.RSVP.hash(validationPromises).then((hash) => { resolve(this.get('errors')); }).catch((reason) => { reject(this.get('errors')); }); }); }, /** Validates model, triggers 'preSave' event, and finally saves model. @method save @param {Object} [options] Method options @param {Boolean} [options.softSave = false] Flag: indicates whether following 'save' will be soft (without sending a request to server) or not @return {Promise} A promise that will be resolved after model will be successfully saved */ save(options) { options = Ember.merge({ softSave: false }, options || {}); return new Ember.RSVP.Promise((resolve, reject) => { // If we are updating while syncing up then checking of validation rules should be skipped // because they can be violated by unfilled fields of model. let promise = this.get('isSyncingUp') && this.get('dirtyType') === 'updated' ? Ember.RSVP.resolve() : this.validate({ validateDeleted: false }); promise.then(() => this.beforeSave(options)).then(() => { // Call to base class 'save' method with right context. // The problem is that call to current save method will be already finished, // and traditional _this._super will point to something else, but not to DS.Model 'save' method, // so there is no other way, except to call it through the base class prototype. if (!options.softSave) { return DS.Model.prototype.save.call(this, options); } }).then(value => { // Assuming that record is not updated during sync up; this.set('isUpdatedDuringSyncUp', false); // Model validation was successful (model is valid or deleted), // all 'preSave' event promises has been successfully resolved, // finally model has been successfully saved, // so we can resolve 'save' promise. resolve(value); }).catch(reason => { // Any of 'validate', 'beforeSave' or 'save' promises has been rejected, // so we should reject 'save' promise. reject(reason); }); }); }, /** Initializes model. */ init() { this._super(...arguments); // Attach validation observers for hasMany relationships. this.eachRelationship((name, attrs) => { if (attrs.kind !== 'hasMany') { return; } let detailsName = attrs.key; Ember.addObserver(this, `${detailsName}.[]`, this, this._onChangeHasManyRelationship); Ember.addObserver(this, `${detailsName}.@each.isDeleted`, this, this._onChangeHasManyRelationship); }); }, /** Destroys model. */ willDestroy() { this._super(...arguments); // Detach validation observers for hasMany relationships. this.eachRelationship((name, attrs) => { if (attrs.kind !== 'hasMany') { return; } let detailsName = attrs.key; Ember.removeObserver(this, `${detailsName}.[]`, this, this._onChangeHasManyRelationship); Ember.removeObserver(this, `${detailsName}.@each.isDeleted`, this, this._onChangeHasManyRelationship); }); }, /** Observes & handles changes in each hasMany relationship. @method _onChangeHasManyRelationship @param {Object} changedObject Reference to changed object. @param {changedPropertyPath} changedPropertyPath Path to changed property. @private */ _onChangeHasManyRelationship(changedObject, changedPropertyPath) { Ember.run.once(this, '_aggregateHasManyRelationshipValidationErrors', changedObject, changedPropertyPath); }, /** Aggregates validation error messages for hasMany relationships. @method _aggregateHasManyRelationshipValidationErrors @param {Object} changedObject Reference to changed object. @param {changedPropertyPath} changedPropertyPath Path to changed property. @private */ _aggregateHasManyRelationshipValidationErrors(changedObject, changedPropertyPath) { // Retrieve aggregator's validation errors object. let errors = Ember.get(this, 'errors'); let detailsName = changedPropertyPath.split('.')[0]; let details = Ember.get(this, detailsName); if (!Ember.isArray(details)) { return; } // Collect each detail's errors object into single array of error messages. let detailsErrorMessages = Ember.A(); details.forEach((detail, i) => { let detailErrors = Ember.get(detail, 'errors'); for (let detailPropertyName in detailErrors) { let detailPropertyErrorMessages = detailErrors[detailPropertyName]; if (detailErrors.hasOwnProperty(detailPropertyName) && Ember.isArray(detailPropertyErrorMessages)) { detailPropertyErrorMessages.forEach((detailPropertyErrorMessage) => { Ember.removeObserver(this, `${detailsName}.@each.${detailPropertyName}`, this, this._onChangeHasManyRelationship); if (!Ember.get(detail, 'isDeleted')) { Ember.addObserver(this, `${detailsName}.@each.${detailPropertyName}`, this, this._onChangeHasManyRelationship); detailsErrorMessages.pushObject(detailPropertyErrorMessage); } }); } } }); // Remember array of error messages in aggregator's errors object. Ember.set(errors, detailsName, detailsErrorMessages); }, }); export default Model;
import { CylinderGeometry } from './CylinderGeometry.js'; class ConeGeometry extends CylinderGeometry { constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); this.type = 'ConeGeometry'; this.parameters = { radius: radius, height: height, radialSegments: radialSegments, heightSegments: heightSegments, openEnded: openEnded, thetaStart: thetaStart, thetaLength: thetaLength }; } } export { ConeGeometry, ConeGeometry as ConeBufferGeometry };
const Vec3 = require("vec3").Vec3; const path = require('path'); const requireIndex = require('requireindex'); const plugins = requireIndex(path.join(__dirname,'..', 'plugins')); const Command = require('flying-squid').Command; module.exports.server=function(serv,options) { serv._server.on('connection', client => client.on('error',error => serv.emit('clientError',client,error))); serv._server.on('login', async (client) => { if(client.socket.listeners('end').length==0) return; // TODO: should be fixed properly in nmp instead try { const player = serv.initEntity('player', null, serv.overworld, new Vec3(0,0,0)); player._client=client; player.profileProperties=player._client.profile ? player._client.profile.properties : []; player.commands = new Command({}); Object.keys(plugins) .filter(pluginName => plugins[pluginName].player!=undefined) .forEach(pluginName => plugins[pluginName].player(player, serv, options)); serv.emit("newPlayer",player); player.emit('asap'); await player.login(); } catch(err){ setTimeout(() => {throw err;},0) } }); }; module.exports.player=function(player,serv,settings) { function addPlayer() { player.type = 'player'; player.health = 20; player.food = 20; player.crouching = false; // Needs added in prismarine-entity later player.op = settings["everybody-op"]; // REMOVE THIS WHEN OUT OF TESTING player.username=player._client.username; serv.players.push(player); serv.uuidToPlayer[player._client.uuid] = player; player.heldItemSlot=36; player.loadedChunks={}; } function sendLogin() { // send init data so client will start rendering world player._client.write('login', { entityId: player.id, levelType: 'default', gameMode: player.gameMode, dimension: 0, difficulty: 0, reducedDebugInfo: false, maxPlayers: serv._server.maxPlayers }); player.position=player.spawnPoint.toFixedPosition(); } function sendChunkWhenMove() { player.on("move", () => { if(!player.sendingChunks && player.position.distanceTo(player.lastPositionChunkUpdated)>16*32) player.sendRestMap(); }); } function updateTime() { player._client.write('update_time', { age: [0, 0], time: [0, serv.time] }); } player.setGameMode = gameMode => { player.gameMode=gameMode; player._client.write('game_state_change', { reason: 3, gameMode: player.gameMode }); serv._writeAll('player_info',{ action: 1, data: [{ UUID: player._client.uuid, gamemode: player.gameMode }] }); player.sendAbilities(); }; function fillTabList() { player._writeOthers('player_info',{ action: 0, data: [{ UUID: player._client.uuid, name: player.username, properties: player.profileProperties, gamemode: player.gameMode, ping: player._client.latency }] }); player._client.write('player_info', { action: 0, data: serv.players.map((otherPlayer) => ({ UUID: otherPlayer._client.uuid, name: otherPlayer.username, properties: otherPlayer.profileProperties, gamemode: otherPlayer.gameMode, ping: otherPlayer._client.latency })) }); setInterval(() => player._client.write('player_info',{ action:2, data:serv.players.map(otherPlayer => ({ UUID: otherPlayer._client.uuid, ping:otherPlayer._client.latency })) }),5000); } function announceJoin() { serv.broadcast(serv.color.yellow + player.username + ' joined the game.'); player.emit("connected"); } player.waitPlayerLogin = () => { const events=["flying","look"]; return new Promise(function(resolve){ const listener=()=> { events.map(event => player._client.removeListener(event,listener)); resolve(); }; events.map(event =>player._client.on(event,listener)); }); }; player.login = async () => { if (serv.uuidToPlayer[player._client.uuid]) { player.kick("You are already connected"); return; } if (serv.bannedPlayers[player._client.uuid]) { player.kick(serv.bannedPlayers[player._client.uuid].reason); return; } if(serv.bannedIPs[player._client.socket.remoteAddress]){ player.kick(serv.bannedIPs[player._client.socket.remoteAddress].reason); return } addPlayer(); await player.findSpawnPoint(); sendLogin(); await player.sendMap(); player.sendSpawnPosition(); player.sendSelfPosition(); player.updateHealth(player.health); player.sendAbilities(); updateTime(); fillTabList(); player.updateAndSpawn(); announceJoin(); player.emit("spawned"); await player.waitPlayerLogin(); player.sendRestMap(); sendChunkWhenMove(); }; };
/** * MVC如何实现的 * 控制器C * 1.自然约定 无路由 * 2.手工指定 */ var http = require('http'); var url = require('url'); /** * localhost:8080 /user/add * localhost:8080 /user/delete */ http.createServer(function(req,res){ var handler = { user:{ add:function(req,res,username,age){ res.end('add '+username+' '+age); }, delete:function(req,res,id){ res.end('delete '+id); } } } var pathname = url.parse(req.url).pathname;//得到pathname var paths = pathname.split('/'); var controller = paths[1];//得到控制器实体 var oper = paths[2];//得到操作方法 var args = paths.slice(3); if(handler[controller]&& handler[controller][oper]){ //handler[controller][oper](req,res); handler[controller][oper].apply(null,[req,res].concat(args)); }else{ res.end('404'); } }).listen(8080);
module.exports = { before: function (browser) { browser.app = browser.page.app(); browser.signinScreen = browser.page.signin(); browser.selectsTab = browser.page.home().section.fieldsGroup.section.selectsTab; browser.app.navigate(); browser.app.waitForElementVisible('@signinScreen'); browser.signinScreen.signin(); browser.app.waitForElementVisible('@homeScreen'); }, after: function (browser) { browser.app.signout(); browser.end(); }, 'Home view should have a Selects tab under the Fields dashboard sub-heading': function (browser) { browser.selectsTab.expect.element('@label') .text.to.equal('Selects'); }, 'Home view should have a + link for the Selects tab under the Fields dashboard sub-heading': function (browser) { browser.selectsTab.expect.element('@plusIconLink') .to.be.visible; }, 'Home view should have a + icon for the Selects tab under the Fields dashboard sub-heading': function (browser) { browser.selectsTab.expect.element('@plusIconLink') .to.have.attribute('class').which.contains('dashboard-group__list-create octicon octicon-plus'); }, 'Home view should show 0 Items for the Selects tab under the Fields dashboard sub-heading': function (browser) { browser.selectsTab.expect.element('@itemCount') .text.to.equal('0 Items'); }, };
/* * Translated default messages for the jQuery validation plugin. * Locale: NO (Norwegian; Norsk) */ $.extend($.validator.messages, { required: "Dette feltet er obligatorisk.", maxlength: $.validator.format("Maksimalt {0} tegn."), minlength: $.validator.format("Minimum {0} tegn."), rangelength: $.validator.format("Angi minimum {0} og maksimum {1} tegn."), email: "Oppgi en gyldig epostadresse.", url: "Angi en gyldig URL.", date: "Angi en gyldig dato.", dateISO: "Angi en gyldig dato (&ARING;&ARING;&ARING;&ARING;-MM-DD).", dateSE: "Angi en gyldig dato.", number: "Angi et gyldig nummer.", numberSE: "Angi et gyldig nummer.", digits: "Skriv kun tall.", equalTo: "Skriv samme verdi igjen.", range: $.validator.format("Angi en verdi mellom {0} og {1}."), max: $.validator.format("Angi en verdi som er mindre eller lik {0}."), min: $.validator.format("Angi en verdi som er st&oslash;rre eller lik {0}."), creditcard: "Angi et gyldig kredittkortnummer." });
import { AsyncSubject } from '../AsyncSubject'; import { multicast } from './multicast'; /** * @owner Observable * @this {?} * @return {?} */ export function publishLast() { return multicast.call(this, new AsyncSubject()); }
'use strict'; const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const join = require('path').join; common.refreshTmpDir(); const filename = join(common.tmpDir, 'test.txt'); const s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; const input = Uint8Array.from(Buffer.from(s, 'utf8')); fs.writeFileSync(filename, input); assert.strictEqual(fs.readFileSync(filename, 'utf8'), s); fs.writeFile(filename, input, common.mustCall((e) => { assert.ifError(e); assert.strictEqual(fs.readFileSync(filename, 'utf8'), s); }));
//HERE COMES THE IE SHITSTORM if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; }
var fs = require('fs'); var path = require('path'); var protobuf = require('pomelo-protobuf'); var Constants = require('../util/constants'); var crypto = require('crypto'); var logger = require('pomelo-logger').getLogger('pomelo', __filename); module.exports = function(app, opts) { return new Component(app, opts); }; var Component = function(app, opts) { this.app = app; opts = opts || {}; this.watchers = {}; this.serverProtos = {}; this.clientProtos = {}; this.version = ""; var env = app.get(Constants.RESERVED.ENV); var originServerPath = path.join(app.getBase(), Constants.FILEPATH.SERVER_PROTOS); var presentServerPath = path.join(Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.SERVER_PROTOS)); var originClientPath = path.join(app.getBase(), Constants.FILEPATH.CLIENT_PROTOS); var presentClientPath = path.join(Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.CLIENT_PROTOS)); this.serverProtosPath = opts.serverProtos || (fs.existsSync(originClientPath) ? Constants.FILEPATH.SERVER_PROTOS : presentServerPath); this.clientProtosPath = opts.clientProtos || (fs.existsSync(originServerPath) ? Constants.FILEPATH.CLIENT_PROTOS : presentClientPath); this.setProtos(Constants.RESERVED.SERVER, path.join(app.getBase(), this.serverProtosPath)); this.setProtos(Constants.RESERVED.CLIENT, path.join(app.getBase(), this.clientProtosPath)); protobuf.init({encoderProtos:this.serverProtos, decoderProtos:this.clientProtos}); }; var pro = Component.prototype; pro.name = '__protobuf__'; pro.encode = function(key, msg) { return protobuf.encode(key, msg); }; pro.encode2Bytes = function(key, msg) { return protobuf.encode2Bytes(key, msg); }; pro.decode = function(key, msg) { return protobuf.decode(key, msg); }; pro.getProtos = function() { return { server : this.serverProtos, client : this.clientProtos, version : this.version }; }; pro.getVersion = function() { return this.version; }; pro.setProtos = function(type, path) { if(!fs.existsSync(path)) { return; } if(type === Constants.RESERVED.SERVER) { this.serverProtos = protobuf.parse(require(path)); } if(type === Constants.RESERVED.CLIENT) { this.clientProtos = protobuf.parse(require(path)); } var protoStr = JSON.stringify(this.clientProtos) + JSON.stringify(this.serverProtos); this.version = crypto.createHash('md5').update(protoStr).digest('base64'); //Watch file var watcher = fs.watch(path, this.onUpdate.bind(this, type, path)); if (this.watchers[type]) { this.watchers[type].close(); } this.watchers[type] = watcher; }; pro.onUpdate = function(type, path, event) { if(event !== 'change') { return; } fs.readFile(path, 'utf8' ,function(err, data) { try { var protos = protobuf.parse(JSON.parse(data)); if(type === Constants.RESERVED.SERVER) { protobuf.setEncoderProtos(protos); } else { protobuf.setDecoderProtos(protos); } this.version = fs.statSync(path).mtime.getTime(); logger.debug('change proto file , type : %j, path : %j, version : %j', type, path, this.version); } catch(e) { logger.warn("change proto file error! path : %j", path); logger.warn(e); } }); }; pro.stop = function(force, cb) { for (var type in this.watchers) { this.watchers[type].close(); } this.watchers = {}; process.nextTick(cb); };
// ========================================================================== // sakinijino.com // ========================================================================== // sc_require("core") iRich.LocalDataSource = SC.DataSource.extend({ LOCAL_STORAGE_KEY: "irich.local", _local_version: "", _local_storage_record_types: [], _storage_adapter_class: null, _support_type: SC.Record.LOCAL, _sync_model: false, _lscKey: function(recordTypeStr){ var prefix = this.LOCAL_STORAGE_KEY+"."+recordTypeStr if (SC.empty(this._local_version)) return prefix; return prefix+".v."+this._local_version; }, _recordTypeLocalStorageAdapter: function(recordTypeStr){ var key = this._lscKey(recordTypeStr) SCUDS.LocalStorageAdapterFactory._adapterClass = this._storage_adapter_class var adp = SCUDS.LocalStorageAdapterFactory.getAdapter(key); SCUDS.LocalStorageAdapterFactory._adapterClass = null return adp; }, loadPersistenceConfig: function(conf) { conf = conf ? conf : PERSISTENCE_CONFIG if (conf.Version) this._local_version = conf.Version if (conf.Record) for (var rname in conf.Record) { var r = SC.objectForPropertyPath(rname) if (r &&conf.Record[rname].location == this._support_type) this._local_storage_record_types.push(r) } }, clearlocalStorage: function(){ for (var i=0; i<this._local_storage_record_types.length; ++i) { var r = this._local_storage_record_types[i] var adp = this._recordTypeLocalStorageAdapter(SC._object_className(r)); adp.nuke(); } }, // Copy and modify from SCUDS.LocalDataSource.fetch fetch: function(store, query) { var recordType = query.get('recordType') if (SC.typeOf(recordType) !== SC.T_CLASS || recordType.persistenceStratgy.location != this._support_type) return NO; var recordTypeStr = SC._object_className(recordType) if (this._sync_model) { this._fetch.apply(this, [store, query, recordType, recordTypeStr]) } else { var _this = this; this.invokeLater(function(){ _this._fetch.apply(_this, [store, query, recordType, recordTypeStr]) }, 250); } return YES; }, _fetch: function(store, query, recordType, recordTypeStr) { var adp = this._recordTypeLocalStorageAdapter(recordTypeStr) var tmp = adp.getAll(); var records = [] var storeKeys = [] for (var i=0; i< tmp.length; ++i) { if (SC.typeOf(tmp[i]) === SC.T_HASH) { records.push(tmp[i]) storeKeys.push(recordType.storeKeyFor(tmp[i][recordType.prototype.primaryKey])) } } if (query.get("location")==SC.Query.LOCAL) { store.loadRecords(recordType, records); store.dataSourceDidFetchQuery(query); } else { store.loadRecords(recordType, records); store.loadQueryResults(query, storeKeys); } }, _isLocalStorageRequest: function(store, storeKey){ return (store.recordTypeFor(storeKey).persistenceStratgy.location == this._support_type) }, _localStorageRequestDispatcher: function(store, storeKey, action){ var recordType = store.recordTypeFor(storeKey) var recordTypeStr = SC._object_className(recordType) var id = store.idFor(storeKey) var args = [store, storeKey, recordType, recordTypeStr, id] if (this._sync_model) { action.apply(this, args) } else { var _this = this; this.invokeLater(function(){ action.apply(_this, args) }, 250); } }, retrieveRecord: function(store, storeKey) { if (!this._isLocalStorageRequest(store, storeKey)) return NO this._localStorageRequestDispatcher(store, storeKey, this._retrieveRecord) return YES }, _retrieveRecord: function(store, storeKey, recordType, recordTypeStr, id) { var hash = this._recordTypeLocalStorageAdapter(recordTypeStr).get(id) if (hash) store.dataSourceDidComplete(storeKey, hash) else store.dataSourceDidError(storeKey) }, createRecord: function(store, storeKey) { if (!this._isLocalStorageRequest(store, storeKey)) return NO this._localStorageRequestDispatcher(store, storeKey, this._createRecord) return YES }, _guidKeyGenerator: function(storeKey, recordType, recordTypeStr) { // Simple auto-increment id generator // Should replace by robust id generator in real application var adp = this._recordTypeLocalStorageAdapter(recordTypeStr) var nextId = adp.get("nextId") nextId = nextId!=null ? nextId : 1; var id = nextId++; adp.save(nextId, "nextId") return id }, _createRecord: function(store, storeKey, recordType, recordTypeStr, id) { var adp = this._recordTypeLocalStorageAdapter(recordTypeStr) var id = this._guidKeyGenerator(storeKey, recordType, recordTypeStr) var hash = store.readDataHash(storeKey) var key = {} key[recordType.prototype.primaryKey] = id SC.mixin(hash, key) if (adp.save(hash, id)) store.dataSourceDidComplete(storeKey, hash, id) else store.dataSourceDidError(storeKey) }, updateRecord: function(store, storeKey) { if (!this._isLocalStorageRequest(store, storeKey)) return NO this._localStorageRequestDispatcher(store, storeKey, this._updateRecord) return YES }, _updateRecord: function(store, storeKey, recordType, recordTypeStr, id) { var adp = this._recordTypeLocalStorageAdapter(recordTypeStr) var hash = store.readDataHash(storeKey) if (adp.save(hash, id)) store.dataSourceDidComplete(storeKey, hash) else store.dataSourceDidError(storeKey) }, destroyRecord: function(store, storeKey) { if (!this._isLocalStorageRequest(store, storeKey)) return NO this._localStorageRequestDispatcher(store, storeKey, this._destroyRecord) return YES }, _destroyRecord: function(store, storeKey, recordType, recordTypeStr, id) { var adp = this._recordTypeLocalStorageAdapter(recordTypeStr) adp.remove(id) store.dataSourceDidDestroy(storeKey) } })
define({ root: ({ _widgetLabel: "Zoom Slider" }), "ar": 1, "bs": 1, "cs": 1, "da": 1, "de": 1, "el": 1, "es": 1, "et": 1, "fi": 1, "fr": 1, "he": 1, "hi": 1, "hr": 1, "it": 1, "id": 1, "ja": 1, "ko": 1, "lt": 1, "lv": 1, "nb": 1, "nl": 1, "pl": 1, "pt-br": 1, "pt-pt": 1, "ro": 1, "ru": 1, "sr": 1, "sv": 1, "th": 1, "tr": 1, "vi": 1, "zh-cn": 1, "zh-hk": 1, "zh-tw": 1 });
describe("Dependency injector", function() { var api = require('../../index.js')(); it("should have the injector API available", function(done) { expect(api.di).toBeDefined(); expect(api.di).not.toBe(null); done(); }); it("should define a dependency and use it", function(done) { api.di.register("AwesomeModule", function() { return 42; }); var doSomething = api.di.resolve(function(AwesomeModule) { expect(AwesomeModule()).toBe(42); done(); }); doSomething(); }); it("should use other parameters", function(done) { api.di.flush().register("AwesomeModule", function() { return 30; }); var doSomething = api.di.resolve(function(a, AwesomeModule, b) { expect(a).toBe(2); expect(b).toBe(10); expect(AwesomeModule() + a + b).toBe(42); done(); }); doSomething(2, 10); }); it("should protect from minification", function(done) { api.di.flush() .register("AwesomeModule", function() { return 30; }) .register("UselessModule", function() { return 'absolutely nothing'; }); var doSomething = api.di.resolve(',AwesomeModule,,UselessModule', function(a, AwesomeModule, b, UselessModule) { expect(a).toBe(2); expect(b).toBe(10); expect(AwesomeModule() + a + b).toBe(42); expect(UselessModule()).toBe('absolutely nothing'); done(); }); doSomething(2, 10); }); it("should keep the scope", function(done) { api.di.flush().register("AwesomeModule", function() { return 42; }); var component = { answer: 0, print: function() { return "The answer is " + this.answer; }, doSomething: function(AwesomeModule) { this.answer = AwesomeModule(); expect(this.print()).toBe("The answer is 42"); done(); } } component.doSomething = api.di.resolve(component.doSomething, component); component.doSomething(); }); it("should resolve an object", function(done) { api.di.flush().register("AwesomeModule", function() { return 42; }); var component = { answer: 0, print: function() { return "The answer is " + this.answer; }, doSomething: function(AwesomeModule) { this.answer = AwesomeModule(); expect(this.print()).toBe("The answer is 42"); done(); } } api.di.resolveObject(component); component.doSomething(); }); it("should resolve an object protected from minification", function(done) { api.di.flush() .register("AwesomeModule", function() { return 42; }) .register("UselessModule", function() { return 'absolutely nothing'; }); var component = { answer: 0, print: function() { return "The answer is " + this.answer; }, doSomething: ['AwesomeModule, UselessModule', function(AwesomeModule, UselessModule) { this.answer = AwesomeModule(); expect(this.print()).toBe("The answer is 42"); expect(UselessModule()).toBe("absolutely nothing"); done(); }] } api.di.resolveObject(component); component.doSomething(); }); it("should use same function with different parameters", function(done) { api.di.flush().register("service", function(value) { return value; }); var App = { init: [',service,', function(a, service, b) { if(!this.tested) { this.tested = true; expect(service(42)).toBeDefined(42); expect(a.value).toBe("A"); expect(b.value).toBe("B"); } else { expect(a.value).toBe(10); expect(b.value).toBe(20); done(); } return this; }] }; api.di.resolveObject(App); App.init( { value: "A" }, { value: "B" } ).init( { value: 10 }, { value: 20 } ); }); it("should be able to pass a boolean", function(done) { api.di.register("BooleanValue", false); var doSomething = api.di.resolve(function(BooleanValue) { expect(BooleanValue).toBeDefined(); expect(typeof BooleanValue).toBe('boolean'); expect(BooleanValue).toBe(false); done(); }); doSomething(); }); it("should use the host", function(done) { var ExternalService = { gogo: function() { return this.host.name; } } api.di.register("es", ExternalService); var doSomething = api.di.resolve(function(es) { this.name = 42; expect(es.gogo()).toBe(42); done(); }); doSomething(); }); it("should use the host while a function is injected", function(done) { var ExternalService = function() { return { name: this.host.name }; } api.di.register("es", ExternalService); var doSomething = api.di.resolve(function(es) { this.name = 42; expect((new es()).name).toBe(42); done(); }); doSomething(); }); });
file:/home/charlike/dev/glob-fs/fixtures/a/e5.js
/************************** bazaar styler ***************************/ var j = jQuery.noConflict(); j(document).ready(function () { j("div[id$='Available']").addClass('baz_available'); j(".baz_available") .observe('childlist', "div[id$='Available_results']", function(record) { console.log("mut"); updateButtons(); wellBazaar(); updateWorkflowIcons(); }); defaultBazaar(); }); function defaultBazaar() { var bazdivs = j("div[id$='Installed'] > div, div[id$='Developer'] > div"); for (var i = 0; i < bazdivs.length; i += 3) { bazdivs.slice(i, i + 3).wrapAll("<div class='well well-sm'></div>"); } } function wellBazaar() { var bazdivs = j("div[id$='Available_results'] > div"); for (var i = 0; i < bazdivs.length; i += 3) { bazdivs.slice(i, i + 3).wrapAll("<div class='well well-sm'></div>"); } }
// parse command line options var minimist = require('minimist'); var mopts = { string: [ 'runner', 'server', 'suite', 'task', 'version' ] }; var options = minimist(process.argv, mopts); // remove well-known parameters from argv before loading make, // otherwise each arg will be interpreted as a make target process.argv = options._; // modules var make = require('shelljs/make'); var fs = require('fs'); var os = require('os'); var path = require('path'); var semver = require('semver'); var util = require('./make-util'); // util functions var cd = util.cd; var cp = util.cp; var mkdir = util.mkdir; var rm = util.rm; var test = util.test; var run = util.run; var banner = util.banner; var rp = util.rp; var fail = util.fail; var ensureExists = util.ensureExists; var pathExists = util.pathExists; var buildNodeTask = util.buildNodeTask; var addPath = util.addPath; var copyTaskResources = util.copyTaskResources; var matchFind = util.matchFind; var matchCopy = util.matchCopy; var ensureTool = util.ensureTool; var assert = util.assert; var getExternals = util.getExternals; var createResjson = util.createResjson; var createTaskLocJson = util.createTaskLocJson; var validateTask = util.validateTask; // global paths var buildPath = path.join(__dirname, '_build', 'Tasks'); var buildTestsPath = path.join(__dirname, '_build', 'Tests'); var commonPath = path.join(__dirname, '_build', 'Tasks', 'Common'); var packagePath = path.join(__dirname, '_package'); var legacyTestPath = path.join(__dirname, '_test', 'Tests-Legacy'); var legacyTestTasksPath = path.join(__dirname, '_test', 'Tasks'); // node min version var minNodeVer = '4.0.0'; if (semver.lt(process.versions.node, minNodeVer)) { fail('requires node >= ' + minNodeVer + '. installed: ' + process.versions.node); } // add node modules .bin to the path so we can dictate version of tsc etc... var binPath = path.join(__dirname, 'node_modules', '.bin'); if (!test('-d', binPath)) { fail('node modules bin not found. ensure npm install has been run.'); } addPath(binPath); // resolve list of tasks var taskList; if (options.task) { // find using --task parameter taskList = matchFind(options.task, path.join(__dirname, 'Tasks'), { noRecurse: true, matchBase: true }) .map(function (item) { return path.basename(item); }); if (!taskList.length) { fail('Unable to find any tasks matching pattern ' + options.task); } } else { // load the default list taskList = JSON.parse(fs.readFileSync(path.join(__dirname, 'make-options.json'))).tasks; } // set the runner options. should either be empty or a comma delimited list of test runners. // for example: ts OR ts,ps // // note, currently the ts runner igores this setting and will always run. process.env['TASK_TEST_RUNNER'] = options.runner || ''; target.clean = function () { rm('-Rf', path.join(__dirname, '_build')); mkdir('-p', buildPath); rm('-Rf', path.join(__dirname, '_test')); }; // // ex: node make.js build // ex: node make.js build --task ShellScript // target.build = function() { target.clean(); ensureTool('tsc', '--version', 'Version 1.8.7'); ensureTool('npm', '--version', function (output) { if (semver.lt(output, '3.0.0')) { fail('expected 3.0.0 or higher'); } }); taskList.forEach(function(taskName) { banner('Building: ' + taskName); var taskPath = path.join(__dirname, 'Tasks', taskName); ensureExists(taskPath); // load the task.json var outDir; var shouldBuildNode = test('-f', path.join(taskPath, 'tsconfig.json')); var taskJsonPath = path.join(taskPath, 'task.json'); if (test('-f', taskJsonPath)) { var taskDef = require(taskJsonPath); validateTask(taskDef); // fixup the outDir (required for relative pathing in legacy L0 tests) outDir = path.join(buildPath, taskDef.name); // create loc files createTaskLocJson(taskPath); createResjson(taskDef, taskPath); // determine the type of task shouldBuildNode = shouldBuildNode || taskDef.execution.hasOwnProperty('Node'); } else { outDir = path.join(buildPath, path.basename(taskPath)); } mkdir('-p', outDir); // get externals var taskMakePath = path.join(taskPath, 'make.json'); var taskMake = test('-f', taskMakePath) ? require(taskMakePath) : {}; if (taskMake.hasOwnProperty('externals')) { console.log('Getting task externals'); getExternals(taskMake.externals, outDir); } //-------------------------------- // Common: build, copy, install //-------------------------------- if (taskMake.hasOwnProperty('common')) { var common = taskMake['common']; common.forEach(function(mod) { var modPath = path.join(taskPath, mod['module']); var modName = path.basename(modPath); var modOutDir = path.join(commonPath, modName); if (!test('-d', modOutDir)) { banner('Building module ' + modPath, true); mkdir('-p', modOutDir); // create loc files var modJsonPath = path.join(modPath, 'module.json'); if (test('-f', modJsonPath)) { createResjson(require(modJsonPath), modPath); } // npm install and compile if ((mod.type === 'node' && mod.compile == true) || test('-f', path.join(modPath, 'tsconfig.json'))) { buildNodeTask(modPath, modOutDir); } // copy default resources and any additional resources defined in the module's make.json console.log(); console.log('> copying module resources'); var modMakePath = path.join(modPath, 'make.json'); var modMake = test('-f', modMakePath) ? require(modMakePath) : {}; copyTaskResources(modMake, modPath, modOutDir); // get externals if (modMake.hasOwnProperty('externals')) { console.log('Getting module externals'); getExternals(modMake.externals, modOutDir); } } // npm install the common module to the task dir if (mod.type === 'node' && mod.compile == true) { mkdir('-p', path.join(taskPath, 'node_modules')); rm('-Rf', path.join(taskPath, 'node_modules', modName)); var originalDir = pwd(); cd(taskPath); run('npm install ' + modOutDir); cd(originalDir); } // copy module resources to the task output dir else if (mod.type === 'ps') { console.log(); console.log('> copying module resources to task'); var dest; if (mod.hasOwnProperty('dest')) { dest = path.join(outDir, mod.dest, modName); } else { dest = path.join(outDir, 'ps_modules', modName); } matchCopy('!Tests', modOutDir, dest, { noRecurse: true, matchBase: true }); } }); } // build Node task if (shouldBuildNode) { buildNodeTask(taskPath, outDir); } // copy default resources and any additional resources defined in the task's make.json console.log(); console.log('> copying task resources'); copyTaskResources(taskMake, taskPath, outDir); }); banner('Build successful', true); } // // will run tests for the scope of tasks being built // npm test // node make.js test // node make.js test --task ShellScript --suite L0 // target.test = function() { ensureTool('tsc', '--version', 'Version 1.8.7'); ensureTool('mocha', '--version', '2.3.3'); // build the general tests and ps test infra rm('-Rf', buildTestsPath); mkdir('-p', path.join(buildTestsPath)); cd(path.join(__dirname, 'Tests')); run(`tsc --rootDir ${path.join(__dirname, 'Tests')} --outDir ${buildTestsPath}`); console.log(); console.log('> copying ps test lib resources'); mkdir('-p', path.join(buildTestsPath, 'lib')); matchCopy(path.join('**', '@(*.ps1|*.psm1)'), path.join(__dirname, 'Tests', 'lib'), path.join(buildTestsPath, 'lib')); // find the tests var suiteType = options.suite || 'L0'; var taskType = options.task || '*'; var pattern1 = buildPath + '/' + taskType + '/Tests/' + suiteType + '.js'; var pattern2 = buildPath + '/Common/' + taskType + '/Tests/' + suiteType + '.js'; var pattern3 = buildTestsPath + '/' + suiteType + '.js'; var testsSpec = matchFind(pattern1, buildPath) .concat(matchFind(pattern2, buildPath)) .concat(matchFind(pattern3, buildTestsPath, { noRecurse: true })); if (!testsSpec.length && !process.env.TF_BUILD) { fail(`Unable to find tests using the following patterns: ${JSON.stringify([pattern1, pattern2, pattern3])}`); } run('mocha ' + testsSpec.join(' '), /*inheritStreams:*/true); } // // node make.js testLegacy // node make.js testLegacy --suite L0/XCode // target.testLegacy = function() { ensureTool('tsc', '--version', 'Version 1.8.7'); ensureTool('mocha', '--version', '2.3.3'); if (options.suite) { fail('The "suite" parameter has been deprecated. Use the "task" parameter instead.'); } // clean console.log('removing _test'); rm('-Rf', path.join(__dirname, '_test')); // copy the L0 source files for each task; copy the layout for each task console.log(); console.log('> copying tasks'); taskList.forEach(function (taskName) { var testCopySource = path.join(__dirname, 'Tests-Legacy', 'L0', taskName); // copy the L0 source files if exist if (test('-e', testCopySource)) { console.log('copying ' + taskName); var testCopyDest = path.join(legacyTestPath, 'L0', taskName); matchCopy('*', testCopySource, testCopyDest, { noRecurse: true, matchBase: true }); // copy the task layout var taskJsonPath = path.join(__dirname, 'Tasks', taskName, 'task.json'); var taskJson = JSON.parse(fs.readFileSync(taskJsonPath).toString()); var taskCopySource = path.join(buildPath, taskJson.name); var taskCopyDest = path.join(legacyTestTasksPath, taskJson.name); matchCopy('*', taskCopySource, taskCopyDest, { noRecurse: true, matchBase: true }); } // copy each common-module L0 source files if exist var taskMakePath = path.join(__dirname, 'Tasks', taskName, 'make.json'); var taskMake = test('-f', taskMakePath) ? JSON.parse(fs.readFileSync(taskMakePath).toString()) : {}; if (taskMake.hasOwnProperty('common')) { var common = taskMake['common']; common.forEach(function(mod) { // copy the common-module L0 source files if exist and not already copied var modName = path.basename(mod['module']); console.log('copying ' + modName); var modTestCopySource = path.join(__dirname, 'Tests-Legacy', 'L0', `Common-${modName}`); var modTestCopyDest = path.join(legacyTestPath, 'L0', `Common-${modName}`); if (test('-e', modTestCopySource) && !test('-e', modTestCopyDest)) { matchCopy('*', modTestCopySource, modTestCopyDest, { noRecurse: true, matchBase: true }); } var modCopySource = path.join(commonPath, modName); var modCopyDest = path.join(legacyTestTasksPath, 'Common', modName); if (test('-e', modCopySource) && !test('-e', modCopyDest)) { // copy the common module layout matchCopy('*', modCopySource, modCopyDest, { noRecurse: true, matchBase: true }); } }); } }); // short-circuit if no tests if (!test('-e', legacyTestPath)) { banner('no legacy tests found', true); return; } // copy the legacy test infra console.log(); console.log('> copying legacy test infra'); matchCopy('@(definitions|lib|tsconfig.json)', path.join(__dirname, 'Tests-Legacy'), legacyTestPath, { noRecurse: true, matchBase: true }); // copy the lib tests when running all legacy tests if (!options.task) { matchCopy('*', path.join(__dirname, 'Tests-Legacy', 'L0', 'lib'), path.join(legacyTestPath, 'L0', 'lib'), { noRecurse: true, matchBase: true }); } // compile legacy L0 and lib var testSource = path.join(__dirname, 'Tests-Legacy'); cd(legacyTestPath); run('tsc --rootDir ' + legacyTestPath); // create a test temp dir - used by the task runner to copy each task to an isolated dir var tempDir = path.join(legacyTestPath, 'Temp'); process.env['TASK_TEST_TEMP'] = tempDir; mkdir('-p', tempDir); // suite paths var testsSpec = matchFind(path.join('**', '_suite.js'), path.join(legacyTestPath, 'L0')); if (!testsSpec.length) { fail(`Unable to find tests using the pattern: ${path.join('**', '_suite.js')}`); } // mocha doesn't always return a non-zero exit code on test failure. when only // a single suite fails during a run that contains multiple suites, mocha does // not appear to always return non-zero. as a workaround, the following code // creates a wrapper suite with an "after" hook. in the after hook, the state // of the runnable context is analyzed to determine whether any tests failed. // if any tests failed, log a ##vso command to fail the build. var testsSpecPath = '' var testsSpecPath = path.join(legacyTestPath, 'testsSpec.js'); var contents = 'var __suite_to_run;' + os.EOL; contents += 'describe(\'Legacy L0\', function (__outer_done) {' + os.EOL; contents += ' after(function (done) {' + os.EOL; contents += ' var failedCount = 0;' + os.EOL; contents += ' var suites = [ this._runnable.parent ];' + os.EOL; contents += ' while (suites.length) {' + os.EOL; contents += ' var s = suites.pop();' + os.EOL; contents += ' suites = suites.concat(s.suites); // push nested suites' + os.EOL; contents += ' failedCount += s.tests.filter(function (test) { return test.state != "passed" }).length;' + os.EOL; contents += ' }' + os.EOL; contents += '' + os.EOL; contents += ' if (failedCount && process.env.TF_BUILD) {' + os.EOL; contents += ' console.log("##vso[task.logissue type=error]" + failedCount + " test(s) failed");' + os.EOL; contents += ' console.log("##vso[task.complete result=Failed]" + failedCount + " test(s) failed");' + os.EOL; contents += ' }' + os.EOL; contents += '' + os.EOL; contents += ' done();' + os.EOL; contents += ' });' + os.EOL; testsSpec.forEach(function (itemPath) { contents += ` __suite_to_run = require(${JSON.stringify(itemPath)});` + os.EOL; }); contents += '});' + os.EOL; fs.writeFileSync(testsSpecPath, contents); run('mocha ' + testsSpecPath, /*inheritStreams:*/true); } target.package = function() { // clean rm('-Rf', packagePath); // create the non-aggregated layout util.createNonAggregatedZip(buildPath, packagePath); // if task specified, create hotfix layout and short-circuit if (options.task) { util.createHotfixLayout(packagePath, options.task); return; } // create the aggregated tasks layout util.createAggregatedZip(packagePath); // nuspec var version = options.version; if (!version) { console.warn('Skipping nupkg creation. Supply version with --version.'); return; } if (!semver.valid(version)) { fail('invalid semver version: ' + version); } var pkgName = 'Mseng.MS.TF.Build.Tasks'; console.log(); console.log('> Generating .nuspec file'); var contents = '<?xml version="1.0" encoding="utf-8"?>' + os.EOL; contents += '<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">' + os.EOL; contents += ' <metadata>' + os.EOL; contents += ' <id>' + pkgName + '</id>' + os.EOL; contents += ' <version>' + version + '</version>' + os.EOL; contents += ' <authors>bigbldt</authors>' + os.EOL; contents += ' <owners>bigbldt,Microsoft</owners>' + os.EOL; contents += ' <requireLicenseAcceptance>false</requireLicenseAcceptance>' + os.EOL; contents += ' <description>For VSS internal use only</description>' + os.EOL; contents += ' <tags>VSSInternal</tags>' + os.EOL; contents += ' </metadata>' + os.EOL; contents += '</package>' + os.EOL; var nuspecPath = path.join(packagePath, 'pack-source', pkgName + '.nuspec'); fs.writeFileSync(nuspecPath, contents); // package ensureTool('nuget.exe'); var nupkgPath = path.join(packagePath, 'pack-target', `${pkgName}.${version}.nupkg`); mkdir('-p', path.dirname(nupkgPath)); run(`nuget.exe pack ${nuspecPath} -OutputDirectory ${path.dirname(nupkgPath)}`); } // used by CI that does official publish target.publish = function() { var server = options.server; assert(server, 'server'); // if task specified, skip if (options.task) { banner('Task parameter specified. Skipping publish.'); return; } // get the branch/commit info var refs = util.getRefs(); // test whether to publish the non-aggregated tasks zip // skip if not the tip of a release branch var release = refs.head.release; var commit = refs.head.commit; if (!release || !refs.releases[release] || commit != refs.releases[release].commit) { // warn not publishing the non-aggregated console.log(`##vso[task.logissue type=warning]Skipping publish for non-aggregated tasks zip. HEAD is not the tip of a release branch.`); } else { // store the non-aggregated tasks zip var nonAggregatedZipPath = path.join(packagePath, 'non-aggregated-tasks.zip'); util.storeNonAggregatedZip(nonAggregatedZipPath, release, commit); } // resolve the nupkg path var nupkgFile; var nupkgDir = path.join(packagePath, 'pack-target'); if (!test('-d', nupkgDir)) { fail('nupkg directory does not exist'); } var fileNames = fs.readdirSync(nupkgDir); if (fileNames.length != 1) { fail('Expected exactly one file under ' + nupkgDir); } nupkgFile = path.join(nupkgDir, fileNames[0]); // publish the package ensureTool('nuget3.exe'); run(`nuget3.exe push ${nupkgFile} -Source ${server} -apikey Skyrise`); } // used to bump the patch version in task.json files target.bump = function() { taskList.forEach(function (taskName) { var taskJsonPath = path.join(__dirname, 'Tasks', taskName, 'task.json'); var taskJson = JSON.parse(fs.readFileSync(taskJsonPath)); if (typeof taskJson.version.Patch != 'number') { fail(`Error processing '${taskName}'. version.Patch should be a number.`); } taskJson.version.Patch = taskJson.version.Patch + 1; fs.writeFileSync(taskJsonPath, JSON.stringify(taskJson, null, 4)); }); }
/* * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nvar lib_1 = __webpack_require__(/*! ./lib */ \"./lib/index.ts\");\nconsole.log(lib_1.lib.one, lib_1.lib.two, lib_1.lib.three, lib_1.lib.four, lib_1.lib.five); // consume new number\n\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }), /***/ "./lib/index.ts": /*!**********************!*\ !*** ./lib/index.ts ***! \**********************/ /***/ ((__unused_webpack_module, exports) => { eval("\nexports.__esModule = true;\nexports.lib = void 0;\nexports.lib = {\n one: 1,\n two: 2,\n three: 3,\n four: 4,\n five: 5\n};\n\n\n//# sourceURL=webpack:///./lib/index.ts?"); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module can't be inlined because the eval devtool is used. /******/ var __webpack_exports__ = __webpack_require__("./app.ts"); /******/ /******/ })() ;
var gulp = require('gulp'), connect = require('gulp-connect'), proxy = require('http-proxy-middleware'), minimist = require('minimist'); var defaultOptions = { default: { serverUrl: 'http://127.0.0.1:8081', connectPort: 8000, app: 'app/', output: 'app/', } }; var options = minimist(process.argv.slice(2), defaultOptions); gulp.task('watch', function() { gulp.watch([options.app + 'scripts/**/*.js', options.app + 'styles/**/*.css', options.app + 'views/**/*.html', options.app + 'index.html'], ['reload']); }); gulp.task('reload', function() { gulp.src(options.app + '**') .pipe(connect.reload()); }); gulp.task('default', ['watch', 'connect']); gulp.task('serve', ['watch', 'connect']); gulp.task('connect', function() { connect.server({ root: ['.'], livereload: true, port: options.connectPort, middleware: function(conn, opt) { return [ proxy('!/app/**', { target: options.serverUrl, changeOrigin : false, ws: true }) ]; } }); });
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present 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 path from 'path'; import express from 'express'; import browserSync from 'browser-sync'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import errorOverlayMiddleware from 'react-dev-utils/errorOverlayMiddleware'; import webpackConfig from './webpack.config'; import run, { format } from './run'; import clean from './clean'; const isDebug = !process.argv.includes('--release'); // https://webpack.js.org/configuration/watch/#watchoptions const watchOptions = { // Watching may not work with NFS and machines in VirtualBox // Uncomment next line if it is your case (use true or interval in milliseconds) // poll: true, // Decrease CPU or memory usage in some file systems // ignored: /node_modules/, }; function createCompilationPromise(name, compiler, config) { return new Promise((resolve, reject) => { let timeStart = new Date(); compiler.hooks.compile.tap(name, () => { timeStart = new Date(); console.info(`[${format(timeStart)}] Compiling '${name}'...`); }); compiler.hooks.done.tap(name, stats => { console.info(stats.toString(config.stats)); const timeEnd = new Date(); const time = timeEnd.getTime() - timeStart.getTime(); if (stats.hasErrors()) { console.info( `[${format(timeEnd)}] Failed to compile '${name}' after ${time} ms`, ); reject(new Error('Compilation failed!')); } else { console.info( `[${format( timeEnd, )}] Finished '${name}' compilation after ${time} ms`, ); resolve(stats); } }); }); } let server; /** * Launches a development web server with "live reload" functionality - * synchronizing URLs, interactions and code changes across multiple devices. */ async function start() { if (server) return server; server = express(); server.use(errorOverlayMiddleware()); server.use(express.static(path.resolve(__dirname, '../public'))); // Configure client-side hot module replacement const clientConfig = webpackConfig.find(config => config.name === 'client'); clientConfig.entry.client = ['./tools/lib/webpackHotDevClient'] .concat(clientConfig.entry.client) .sort((a, b) => b.includes('polyfill') - a.includes('polyfill')); clientConfig.output.filename = clientConfig.output.filename.replace( 'chunkhash', 'hash', ); clientConfig.output.chunkFilename = clientConfig.output.chunkFilename.replace( 'chunkhash', 'hash', ); clientConfig.module.rules = clientConfig.module.rules.filter( x => x.loader !== 'null-loader', ); clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); // Configure server-side hot module replacement const serverConfig = webpackConfig.find(config => config.name === 'server'); serverConfig.output.hotUpdateMainFilename = 'updates/[hash].hot-update.json'; serverConfig.output.hotUpdateChunkFilename = 'updates/[id].[hash].hot-update.js'; serverConfig.module.rules = serverConfig.module.rules.filter( x => x.loader !== 'null-loader', ); serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); // Configure compilation await run(clean); const multiCompiler = webpack(webpackConfig); const clientCompiler = multiCompiler.compilers.find( compiler => compiler.name === 'client', ); const serverCompiler = multiCompiler.compilers.find( compiler => compiler.name === 'server', ); const clientPromise = createCompilationPromise( 'client', clientCompiler, clientConfig, ); const serverPromise = createCompilationPromise( 'server', serverCompiler, serverConfig, ); // https://github.com/webpack/webpack-dev-middleware server.use( webpackDevMiddleware(clientCompiler, { publicPath: clientConfig.output.publicPath, logLevel: 'silent', watchOptions, }), ); // https://github.com/glenjamin/webpack-hot-middleware server.use(webpackHotMiddleware(clientCompiler, { log: false })); let appPromise; let appPromiseResolve; let appPromiseIsResolved = true; serverCompiler.hooks.compile.tap('server', () => { if (!appPromiseIsResolved) return; appPromiseIsResolved = false; // eslint-disable-next-line no-return-assign appPromise = new Promise(resolve => (appPromiseResolve = resolve)); }); let app; server.use((req, res) => { appPromise .then(() => app.handle(req, res)) .catch(error => console.error(error)); }); function checkForUpdate(fromUpdate) { const hmrPrefix = '[\x1b[35mHMR\x1b[0m] '; if (!app.hot) { throw new Error(`${hmrPrefix}Hot Module Replacement is disabled.`); } if (app.hot.status() !== 'idle') { return Promise.resolve(); } return app.hot .check(true) .then(updatedModules => { if (!updatedModules) { if (fromUpdate) { console.info(`${hmrPrefix}Update applied.`); } return; } if (updatedModules.length === 0) { console.info(`${hmrPrefix}Nothing hot updated.`); } else { console.info(`${hmrPrefix}Updated modules:`); updatedModules.forEach(moduleId => console.info(`${hmrPrefix} - ${moduleId}`), ); checkForUpdate(true); } }) .catch(error => { if (['abort', 'fail'].includes(app.hot.status())) { console.warn(`${hmrPrefix}Cannot apply update.`); delete require.cache[require.resolve('../build/server')]; // eslint-disable-next-line global-require, import/no-unresolved app = require('../build/server').default; console.warn(`${hmrPrefix}App has been reloaded.`); } else { console.warn( `${hmrPrefix}Update failed: ${error.stack || error.message}`, ); } }); } serverCompiler.watch(watchOptions, (error, stats) => { if (app && !error && !stats.hasErrors()) { checkForUpdate().then(() => { appPromiseIsResolved = true; appPromiseResolve(); }); } }); // Wait until both client-side and server-side bundles are ready await clientPromise; await serverPromise; const timeStart = new Date(); console.info(`[${format(timeStart)}] Launching server...`); // Load compiled src/server.js as a middleware // eslint-disable-next-line global-require, import/no-unresolved app = require('../build/server').default; appPromiseIsResolved = true; appPromiseResolve(); // Launch the development server with Browsersync and HMR await new Promise((resolve, reject) => browserSync.create().init( { // https://www.browsersync.io/docs/options server: 'src/server.js', middleware: [server], open: !process.argv.includes('--silent'), ...(isDebug ? {} : { notify: false, ui: false }), }, (error, bs) => (error ? reject(error) : resolve(bs)), ), ); const timeEnd = new Date(); const time = timeEnd.getTime() - timeStart.getTime(); console.info(`[${format(timeEnd)}] Server launched after ${time} ms`); return server; } export default start;
const hashFile = require('hash-file'); const nconf = require('nconf'); const isProduction = process.env.NODE_ENV === 'production'; // Specifying an env delimiter allows you to override below config when shipping // to production server. nconf.env('__'); function getAssetHash(filePath) { if (!isProduction) return ''; try { return hashFile.sync(filePath); } catch (e) { return ''; } } // Remember, never put production secrets in config. Use nconf. const config = { assetsHashes: { appCss: getAssetHash('build/app.css'), appJs: getAssetHash('build/app.js') }, isProduction: isProduction, googleAnalyticsId: 'UA-XXXXXXX-X', port: process.env.PORT || 8000, webpackStylesExtensions: ['css', 'less', 'sass', 'scss', 'styl'] }; // Use above config as a default one. Multiple other providers are available // like loading config from json and more. Check out nconf docs. nconf.defaults(config); module.exports = nconf.get();
"use strict"; const { collectDependents } = require("./collect-dependents"); module.exports.collectPackages = collectPackages; /** * @typedef {object} PackageCollectorOptions * @property {(node: import("@lerna/package-graph").PackageGraphNode, name: string) => boolean} [isCandidate] By default, all nodes passed in are candidates * @property {(name: string) => void} [onInclude] * @property {boolean} [excludeDependents] */ /** * Build a list of graph nodes, possibly including dependents, using predicate if available. * @param {Map<string, import("@lerna/package-graph").PackageGraphNode>} packages * @param {PackageCollectorOptions} options */ function collectPackages(packages, { isCandidate = () => true, onInclude, excludeDependents } = {}) { /** @type {Set<import("@lerna/package-graph").PackageGraphNode>} */ const candidates = new Set(); packages.forEach((node, name) => { if (isCandidate(node, name)) { candidates.add(node); } }); if (!excludeDependents) { collectDependents(candidates).forEach((node) => candidates.add(node)); } // The result should always be in the same order as the input /** @type {import("@lerna/package-graph").PackageGraphNode[]} */ const updates = []; packages.forEach((node, name) => { if (candidates.has(node)) { if (onInclude) { onInclude(name); } updates.push(node); } }); return updates; }
define(["require", "exports"], function (require, exports) { var App = (function () { function App() { } App.prototype.configureRouter = function (config, router) { config.title = 'Aurelia'; config.map([ { route: ['', 'welcome'], name: 'welcome', moduleId: './welcome', nav: true, title: 'Welcome' }, { route: 'flickr', name: 'flickr', moduleId: './flickr', nav: true, title: 'Flickr' }, { route: 'users', name: 'users', moduleId: './users', nav: true, title: 'Github Users' }, { route: 'child-router', name: 'child-router', moduleId: './child-router', nav: true, title: 'Child Router' } ]); this.router = router; }; return App; })(); exports.App = App; }); //# sourceMappingURL=app.js.map
import { TestModule, getContext } from 'ember-test-helpers'; import test from 'tests/test-support/qunit-test'; import qunitModuleFor from 'tests/test-support/qunit-module-for'; import { setResolverRegistry } from 'tests/test-support/resolver'; function moduleFor(fullName, description, callbacks) { var module = new TestModule(fullName, description, callbacks); qunitModuleFor(module); } function setupRegistry() { setResolverRegistry({ 'component:x-foo': Ember.Component.extend(), 'component:not-the-subject': Ember.Component.extend(), 'foo:thing': Ember.Object.extend({ fromDefaultRegistry: true }) }); } var a = 0; var b = 0; var beforeSetupOk = false; var afterTeardownOk = false; var callbackOrder, setupContext, teardownContext, beforeSetupContext, afterTeardownContext; moduleFor('component:x-foo', 'TestModule callbacks', { beforeSetup: function() { beforeSetupContext = this; callbackOrder = [ 'beforeSetup' ]; setupRegistry(); }, setup: function() { setupContext = this; callbackOrder.push('setup'); ok(setupContext !== beforeSetupContext); }, teardown: function() { teardownContext = this; callbackOrder.push('teardown'); deepEqual(callbackOrder, [ 'beforeSetup', 'setup', 'teardown']); equal(setupContext, teardownContext); }, afterTeardown: function() { afterTeardownContext = this; callbackOrder.push('afterTeardown'); equal(this.context, undefined, "don't leak the this.context"); equal(getContext(), undefined, "don't leak the internal context"); deepEqual(callbackOrder, [ 'beforeSetup', 'setup', 'teardown', 'afterTeardown']); equal(afterTeardownContext, beforeSetupContext); ok(afterTeardownContext !== teardownContext); } }); test("setup callbacks called in the correct order", function() { deepEqual(callbackOrder, [ 'beforeSetup', 'setup' ]); }); moduleFor('component:x-foo', 'component:x-foo -- setup context', { beforeSetup: function() { setupRegistry(); }, setup: function() { this.subject({ name: 'Max' }); var thingToRegisterWith = this.registry || this.container; thingToRegisterWith.register('service:blah', Ember.Object.extend({ purpose: 'blabering' })); } }); test("subject can be initialized in setup", function() { equal(this.subject().name, 'Max'); }); test("can lookup factory registered in setup", function() { var service = this.container.lookup('service:blah'); equal(service.get('purpose'), 'blabering'); }); moduleFor('component:x-foo', 'component:x-foo -- callback context', { beforeSetup: function() { setupRegistry(); }, getSubjectName: function() { return this.subjectName; } }); test("callbacks are called in the context of the module", function() { equal(this.getSubjectName(), 'component:x-foo'); }); moduleFor('component:x-foo', 'component:x-foo -- created subjects are cleaned up', { beforeSetup: function() { setupRegistry(); }, afterTeardown: function() { var subject = this.cache.subject; ok(subject.isDestroyed); } }); test("subject's created in a test are destroyed", function() { this.subject(); }); moduleFor('component:x-foo', 'component:x-foo -- uncreated subjects do not error', { beforeSetup: function() { setupRegistry(); } }); test("subject's created in a test are destroyed", function() { expect(0); }); moduleFor('component:x-foo', 'component:x-foo -- without needs or `integration: true`', { beforeSetup: setupRegistry() }); test("knows nothing about our non-subject component", function() { var otherComponent = this.container.lookup('component:not-the-subject'); equal(null, otherComponent, "We shouldn't know about a non-subject component"); }); moduleFor('component:x-foo', 'component:x-foo -- when needing another component', { beforeSetup: setupRegistry(), needs: ['component:not-the-subject'] }); test("needs gets us the component we need", function() { var otherComponent = this.container.lookup('component:not-the-subject'); ok(otherComponent, "another component can be resolved when it's in our needs array"); }); moduleFor('component:x-foo', 'component:x-foo -- `integration: true`', { beforeSetup: function() { setupRegistry(); ok(!this.callbacks.integration, "integration property should be removed from callbacks"); ok(this.isIntegration, "isIntegration should be set when we set `integration: true` in callbacks"); }, integration: true }); test("needs is not needed (pun intended) when integration is true", function() { var otherComponent = this.container.lookup('component:not-the-subject'); ok(otherComponent, 'another component can be resolved when integration is true'); }); test("throws an error when declaring integration: true and needs in the same module", function() { expect(3); var result = false; try { moduleFor('component:x-foo', { integration: true, needs: ['component:x-bar'] }); } catch(err) { result = true; } ok(result, "should throw an Error when integration: true and needs are provided"); }); moduleFor('component:x-foo', 'should be able to override factories in integration mode', { beforeSetup: function() { setupRegistry(); }, integration: true }); test('gets the default by default', function() { var thing = this.container.lookup('foo:thing'); ok(thing.fromDefaultRegistry, 'found from the default registry'); }); test('can override the default', function() { this.registry.register('foo:thing', Ember.Object.extend({ notTheDefault: true })); var thing = this.container.lookup('foo:thing'); ok(!thing.fromDefaultRegistry, 'should not be found from the default registry'); ok(thing.notTheDefault, 'found from the overridden factory'); });
/** * @file DevTools Author Settings panel */ (function( w, // Window ga, // Google Analytics $, // document.querySelectorAll storage // Chrome Storage API ){ 'use strict'; /** * Panel module * @namespace panel * @global */ var panel = (function(){ /** @private */ var $select = $('#theme-options')[0]; /** @private */ var $range = $('#font-size-input')[0]; /** @private */ var $output = $('#font-size-output')[0]; /** @private */ var $fontInput = $('#font-family-input')[0]; /** @private */ var $palette = $('.palette')[0]; /** @private */ var $themeTitle = $('#currentTheme')[0]; /** @private */ var $footerLink = $('.footer a')[0]; /** @private */ var $alert = $('.alert')[0]; /** @private */ var _panel = _panel || {}; /** @private */ var _themeJSON = '/dist/scripts/themes.json'; /** @private */ var _defaultTheme = '3024'; /** @private */ var _defaultFontSize = 14; /** @private */ var _defaultFontFamily = 'Hack'; /** @private */ var _currentTheme = null; /** @private */ var _currentFontSize = null; /** @private */ var _currentFontFamily = null; /** * Creates HTML list of colors * @function _createLI * @param {Array} palette - List of theme colors in hex */ function _createLI(palette){ /** Filter palette to remove duplicate colors */ palette = palette.filter(function(item, pos, self) { return self.indexOf(item) === pos; }); for (var i = 0; i < palette.length; i++){ /** Create list item */ var item = document.createElement('li'); /** Style list item */ item.style.backgroundColor = palette[i]; item.style.width = (100 / palette.length) + '%'; /** Add item to the list */ $palette.appendChild(item); } } /** * Find theme colors * @function _themeLookUp * @param {String} theme - Theme name * @returns {Array} List of theme colors in hex */ function _themeLookUp(theme){ for (var i = 0; i < _panel.themes.length; i++){ if (_panel.themes[i].name === theme) { return _panel.themes[i].colors; } } } /** * Recreate $palette using current theme * @function _updatePalette * @param {String} theme - Currently selected theme name */ function _updatePalette(theme){ var children = $palette.querySelectorAll('li'); if (children.length){ for (var i = 0; i < children.length; i++){ $palette.removeChild(children[i]); } } _createLI(_themeLookUp(theme)); } /** * Build select menus like ngOptions * @function _buildSelectMenu * @param {HTMLElement} menu - Theme select menu element (empty) * @param {Object} model - Panel model containing available themes and current settings * @returns {HTMLElement} menu - Theme select menu element, with available themes appended */ function _buildSelectMenu(menu, model){ var options, array; /** Get the data attribute value */ options = menu.dataset.options; /** Clean string and create array */ options = options.replace(/in\s/g, '').split(' '); /** * Assign array from model by property name * using the value from the last item in options */ array = model[options[options.length - 1]]; for (var j = 0; j < array.length; j++){ var option = document.createElement('option'); /** Assign option value & text from array */ option.value = array[j].name.replace(/\s+/g, '-').toLowerCase(); option.text = array[j].name; /** Select currentTheme option */ if (model.currentTheme === array[j].name){ option.selected = 'selected'; } menu.add(option, null); } return menu; } /** * Alert notification test * @function _notification * @param {String} oldValue - Original value for alert notification test * @param {String} newValue - New value for alert notification test */ function _notification(oldValue, newValue){ if (oldValue !== newValue){ $alert.style.display = 'block'; } } /** * Object.defineProperty custom setters and getters for _panel model * @function _panelModelSetup */ function _panelModelSetup(){ /** Observe changes to _panel.currentTheme */ Object.defineProperty(_panel, 'currentTheme', { enumerable: true, configurable: true, get: function() { return _currentTheme; }, set: function(newValue) { _notification(_currentTheme, newValue); $themeTitle.innerHTML = _currentTheme = newValue; _updatePalette(_currentTheme); } }); /** Observe changes to _panel.currentFontSize */ Object.defineProperty(_panel, 'currentFontSize', { enumerable: true, configurable: true, get: function() { return _currentFontSize; }, set: function(newValue) { _notification(_currentFontSize, newValue); $range.value = $output.value = _currentFontSize = newValue; } }); /** Observe changes to _panel.currentFontFamily */ Object.defineProperty(_panel, 'currentFontFamily', { enumerable: true, configurable: true, get: function() { return _currentFontFamily; }, set: function(newValue) { _notification(_currentFontFamily, newValue); $fontInput.value = _currentFontFamily = newValue; } }); } /** * Setup event listeners and get settings from storage * @function _panelSetup */ function _panelSetup(){ /** Observe changes to _panel model */ _panelModelSetup(); /** Listen for changes to the select menu */ $select.addEventListener('change', setTheme); /** Listen for changes to the text input */ $fontInput.addEventListener('change', setFontFamily); /** Listen for changes to the range input */ $range.addEventListener('change', setFontSize); /** Listen for click on footer element */ $footerLink.addEventListener('click', function(){ ga('send', 'event', 'Link', 'Click', 'Mike King on GitHub'); }); /** Get current theme setting from storage */ storage.get('devtools-theme', function(object){ _panel.currentTheme = _currentTheme = getTheme( _panel.themes, object['devtools-theme'] ); _buildSelectMenu($select, _panel); /** Send Google Analytics 'Install' event on initial install */ if (!object['devtools-theme'] && _panel.currentTheme === _defaultTheme){ ga('send', 'event', 'Install', 'Install', 'Devtools Author', 1); } }); /** Get current `font-family` setting from storage */ storage.get('devtools-fontFamily', function(object){ _panel.currentFontFamily = _currentFontFamily = getFontFamily(object['devtools-fontFamily']); }); /** Get current `font-size` setting from storage */ storage.get('devtools-fontSize', function(object){ _panel.currentFontSize = _currentFontSize = getFontSize(object['devtools-fontSize']); }); } /** * Set & save theme based on select menu change event * @function setTheme * @memberof! app * @param {Event} event - Event object * @param {Object} obj - Object for theme settings defaults */ function setTheme(event, obj){ function save(theme){ storage.set({ 'devtools-theme': theme.value }, function(){ _panel.currentTheme = theme.text; }); return theme.value; } if (event && event.type === 'change'){ var el = event.target || event.srcElement; var option = el.options[el.selectedIndex]; return save(option); } else if (event === null && obj){ return save(obj); } } /** * Set & save `font-family` based on input change event * @function setFontFamily * @memberof! app * @param {Event} event - Event object * @param {Object} value - Value for `font-family` settings */ function setFontFamily(event, value){ function save(fontFamily){ storage.set({ 'devtools-fontFamily': fontFamily }, function(){ _panel.currentFontFamily = fontFamily; }); return fontFamily; } if (event && event.type === 'change'){ var el = event.target || event.srcElement; return save(el.value); } else if (event === null && value){ return save(value); } } /** * Set & save `font-size` based on input menu change event * @function setFontSize * @memberof! app * @param {Event} event - Event object * @param {Object} value - Value for `font-size` settings */ function setFontSize(event, value){ function save(fontSize){ storage.set({ 'devtools-fontSize': fontSize }, function(){ _panel.currentFontSize = fontSize; }); return fontSize; } if (event && event.type === 'change'){ var el = event.target || event.srcElement; return save(el.value); } else if (event === null && value){ return save(value); } } /** * Get theme settings * @function getTheme * @memberof! app * @param {Array} array - List of themes * @param {String} string - Value for theme settings * @returns {String} Theme name */ function getTheme(array, string){ if (!array || !string){ setTheme(null, { value: _defaultTheme.replace(/\s+/g, '-').toLowerCase(), text: _defaultTheme }); return _defaultTheme; } for (var i = 0; i < array.length; i++){ if (array[i].name.replace(/\s+/g, '-').toLowerCase() === string){ return array[i].name; } } } /** * Get `font-family` settings * @function getFontFamily * @memberof! app * @param {String} value - Value for `font-family` settings * @returns {String} value - Value for `font-family` settings */ function getFontFamily(value){ if (!value){ setFontFamily(null, _defaultFontFamily); return _defaultFontFamily; } else { return value; } } /** * Get `font-size` settings * @function getFontSize * @memberof! app * @param {String} value - Value for `font-size` settings * @returns {String} value - Value for `font-size` settings */ function getFontSize(value){ if (!value){ setFontSize(null, _defaultFontSize); return _defaultFontSize; } else { return value; } } /** * GET themes JSON and setup panel settings * @function init * @memberof! app */ function init(){ var ajax = new XMLHttpRequest(); ajax.open('GET', _themeJSON); ajax.send(null); ajax.onreadystatechange = function(){ if (ajax.readyState === 4) { if (ajax.status === 200) { _panel.themes = JSON.parse(ajax.responseText); _panel.themes.sort(function(a, b){ if(a.name < b.name) { return -1; } if(a.name > b.name) { return 1; } return 0; }); return _panelSetup(); } else { return console.log('Status Code: ' + ajax.status + '\nThere was an error with your request'); } } }; } /** Public methods */ return { init: init, getTheme: getTheme, setTheme: setTheme, getFontSize: getFontSize, setFontSize: setFontSize, getFontFamily: getFontFamily, setFontFamily: setFontFamily }; })(); /** Initialize panel */ panel.init(); /** Export as global */ w.panel = panel; })( /** Globals */ window, window.ga, document.querySelectorAll.bind(document), chrome.storage.sync );
import React from 'react'; /* eslint-disable */ const Open = (props) => ( <svg {...props} width="148" height="148" viewBox="0 0 148 148"> <g transform="translate(41.625 46.25)"> <polygon points="27.75 0 27.75 60.125 37 60.125 37 0"/> <polygon points="62.438 25.438 2.313 25.438 2.313 34.688 62.438 34.688"/> </g> </svg> ); /* eslint-enable */ export default Open;
// Note: You must restart bin/webpack-watcher for changes to take effect /* eslint global-require: 0 */ /* eslint import/no-dynamic-require: 0 */ const webpack = require('webpack') const { basename, join, resolve } = require('path') const { sync } = require('glob') const { readdirSync } = require('fs') const ExtractTextPlugin = require('extract-text-webpack-plugin') const ManifestPlugin = require('webpack-manifest-plugin') const extname = require('path-complete-extname') const { env, paths, publicPath, loadersDir } = require('./configuration.js') const extensionGlob = `*{${paths.extensions.join(',')}}*` const packPaths = sync(join(paths.source, paths.entry, extensionGlob)) module.exports = { entry: packPaths.reduce( (map, entry) => { const localMap = map localMap[basename(entry, extname(entry))] = resolve(entry) return localMap }, {} ), output: { filename: '[name].js', path: resolve(paths.output, paths.entry) }, module: { rules: readdirSync(loadersDir).map(file => ( require(join(loadersDir, file)) )) }, plugins: [ new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(env))), new ExtractTextPlugin(env.NODE_ENV === 'production' ? '[name]-[hash].css' : '[name].css'), new ManifestPlugin({ fileName: 'manifest.json', publicPath, writeToFileEmit: true }) ], resolve: { extensions: paths.extensions, modules: [ resolve(paths.source), resolve(paths.node_modules) ] }, resolveLoader: { modules: [paths.node_modules] } }
/*! * chessboard.js v0.3.0 * * Copyright 2013 Chris Oakman * Released under the MIT license * http://chessboardjs.com/license * * Date: 10 Aug 2013 */ // start anonymous scope ;(function() { 'use strict'; //------------------------------------------------------------------------------ // Chess Util Functions //------------------------------------------------------------------------------ var COLUMNS = 'abcdefgh'.split(''); function validMove(move) { // move should be a string if (typeof move !== 'string') return false; // move should be in the form of "e2-e4", "f6-d5" var tmp = move.split('-'); if (tmp.length !== 2) return false; return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true); } function validSquare(square) { if (typeof square !== 'string') return false; return (square.search(/^[a-h][1-8]$/) !== -1); } function validPieceCode(code) { if (typeof code !== 'string') return false; return (code.search(/^[bw][KQRNBP]$/) !== -1); } // TODO: this whole function could probably be replaced with a single regex function validFen(fen) { if (typeof fen !== 'string') return false; // cut off any move, castling, etc info from the end // we're only interested in position information fen = fen.replace(/ .+$/, ''); // FEN should be 8 sections separated by slashes var chunks = fen.split('/'); if (chunks.length !== 8) return false; // check the piece sections for (var i = 0; i < 8; i++) { if (chunks[i] === '' || chunks[i].length > 8 || chunks[i].search(/[^kqrbnpKQRNBP1-8]/) !== -1) { return false; } } return true; } function validPositionObject(pos) { if (typeof pos !== 'object') return false; for (var i in pos) { if (pos.hasOwnProperty(i) !== true) continue; if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) { return false; } } return true; } // convert FEN piece code to bP, wK, etc function fenToPieceCode(piece) { // black piece if (piece.toLowerCase() === piece) { return 'b' + piece.toUpperCase(); } // white piece return 'w' + piece.toUpperCase(); } // convert bP, wK, etc code to FEN structure function pieceCodeToFen(piece) { var tmp = piece.split(''); // white piece if (tmp[0] === 'w') { return tmp[1].toUpperCase(); } // black piece return tmp[1].toLowerCase(); } // convert FEN string to position object // returns false if the FEN string is invalid function fenToObj(fen) { if (validFen(fen) !== true) { return false; } // cut off any move, castling, etc info from the end // we're only interested in position information fen = fen.replace(/ .+$/, ''); var rows = fen.split('/'); var position = {}; var currentRow = 8; for (var i = 0; i < 8; i++) { var row = rows[i].split(''); var colIndex = 0; // loop through each character in the FEN section for (var j = 0; j < row.length; j++) { // number / empty squares if (row[j].search(/[1-8]/) !== -1) { var emptySquares = parseInt(row[j], 10); colIndex += emptySquares; } // piece else { var square = COLUMNS[colIndex] + currentRow; position[square] = fenToPieceCode(row[j]); colIndex++; } } currentRow--; } return position; } // position object to FEN string // returns false if the obj is not a valid position object function objToFen(obj) { if (validPositionObject(obj) !== true) { return false; } var fen = ''; var currentRow = 8; for (var i = 0; i < 8; i++) { for (var j = 0; j < 8; j++) { var square = COLUMNS[j] + currentRow; // piece exists if (obj.hasOwnProperty(square) === true) { fen += pieceCodeToFen(obj[square]); } // empty space else { fen += '1'; } } if (i !== 7) { fen += '/'; } currentRow--; } // squeeze the numbers together // haha, I love this solution... fen = fen.replace(/11111111/g, '8'); fen = fen.replace(/1111111/g, '7'); fen = fen.replace(/111111/g, '6'); fen = fen.replace(/11111/g, '5'); fen = fen.replace(/1111/g, '4'); fen = fen.replace(/111/g, '3'); fen = fen.replace(/11/g, '2'); return fen; } window['ChessBoard'] = window['ChessBoard'] || function(containerElOrId, cfg) { 'use strict'; cfg = cfg || {}; //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ var MINIMUM_JQUERY_VERSION = '1.7.0', START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR', START_POSITION = fenToObj(START_FEN); // use unique class names to prevent clashing with anything else on the page // and simplify selectors var CSS = { alpha: 'alpha-d2270', black: 'black-3c85d', board: 'board-b72b1', chessboard: 'chessboard-63f37', clearfix: 'clearfix-7da63', highlight1: 'highlight1-32417', highlight2: 'highlight2-9c5d2', notation: 'notation-322f9', numeric: 'numeric-fc462', piece: 'piece-417db', row: 'row-5277c', sparePieces: 'spare-pieces-7492f', sparePiecesBottom: 'spare-pieces-bottom-ae20f', sparePiecesTop: 'spare-pieces-top-4028b', square: 'square-55d63', white: 'white-1e1d7' }; //------------------------------------------------------------------------------ // Module Scope Variables //------------------------------------------------------------------------------ // DOM elements var containerEl, boardEl, draggedPieceEl, sparePiecesTopEl, sparePiecesBottomEl; // constructor return object var widget = {}; //------------------------------------------------------------------------------ // Stateful //------------------------------------------------------------------------------ var ANIMATION_HAPPENING = false, BOARD_BORDER_SIZE = 2, CURRENT_ORIENTATION = 'white', CURRENT_POSITION = {}, SQUARE_SIZE, DRAGGED_PIECE, DRAGGED_PIECE_LOCATION, DRAGGED_PIECE_SOURCE, DRAGGING_A_PIECE = false, SPARE_PIECE_ELS_IDS = {}, SQUARE_ELS_IDS = {}, SQUARE_ELS_OFFSETS; //------------------------------------------------------------------------------ // JS Util Functions //------------------------------------------------------------------------------ // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript function createId() { return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function(c) { var r = Math.random() * 16 | 0; return r.toString(16); }); } function deepCopy(thing) { return JSON.parse(JSON.stringify(thing)); } function parseSemVer(version) { var tmp = version.split('.'); return { major: parseInt(tmp[0], 10), minor: parseInt(tmp[1], 10), patch: parseInt(tmp[2], 10) }; } // returns true if version is >= minimum function compareSemVer(version, minimum) { version = parseSemVer(version); minimum = parseSemVer(minimum); var versionNum = (version.major * 10000 * 10000) + (version.minor * 10000) + version.patch; var minimumNum = (minimum.major * 10000 * 10000) + (minimum.minor * 10000) + minimum.patch; return (versionNum >= minimumNum); } //------------------------------------------------------------------------------ // Validation / Errors //------------------------------------------------------------------------------ function error(code, msg, obj) { // do nothing if showErrors is not set if (cfg.hasOwnProperty('showErrors') !== true || cfg.showErrors === false) { return; } var errorText = 'ChessBoard Error ' + code + ': ' + msg; // print to console if (cfg.showErrors === 'console' && typeof console === 'object' && typeof console.log === 'function') { console.log(errorText); if (arguments.length >= 2) { console.log(obj); } return; } // alert errors if (cfg.showErrors === 'alert') { if (obj) { errorText += '\n\n' + JSON.stringify(obj); } window.alert(errorText); return; } // custom function if (typeof cfg.showErrors === 'function') { cfg.showErrors(code, msg, obj); } } // check dependencies function checkDeps() { // if containerId is a string, it must be the ID of a DOM node if (typeof containerElOrId === 'string') { // cannot be empty if (containerElOrId === '') { window.alert('ChessBoard Error 1001: ' + 'The first argument to ChessBoard() cannot be an empty string.' + '\n\nExiting...'); return false; } // make sure the container element exists in the DOM var el = $(containerElOrId); if (! el) { window.alert('ChessBoard Error 1002: Element with id "' + containerElOrId + '" does not exist in the DOM.' + '\n\nExiting...'); return false; } // set the containerEl containerEl = $(el); } // else it must be something that becomes a jQuery collection // with size 1 // ie: a single DOM node or jQuery object else { containerEl = $(containerElOrId); if (containerEl.length !== 1) { window.alert('ChessBoard Error 1003: The first argument to ' + 'ChessBoard() must be an ID or a single DOM node.' + '\n\nExiting...'); return false; } } // JSON must exist if (! window.JSON || typeof JSON.stringify !== 'function' || typeof JSON.parse !== 'function') { window.alert('ChessBoard Error 1004: JSON does not exist. ' + 'Please include a JSON polyfill.\n\nExiting...'); return false; } // check for a compatible version of jQuery if (! (typeof window.$ && $.fn && $.fn.jquery && compareSemVer($.fn.jquery, MINIMUM_JQUERY_VERSION) === true)) { window.alert('ChessBoard Error 1005: Unable to find a valid version ' + 'of jQuery. Please include jQuery ' + MINIMUM_JQUERY_VERSION + ' or ' + 'higher on the page.\n\nExiting...'); return false; } return true; } function validAnimationSpeed(speed) { if (speed === 'fast' || speed === 'slow') { return true; } if ((parseInt(speed, 10) + '') !== (speed + '')) { return false; } return (speed >= 0); } // validate config / set default options function expandConfig() { if (typeof cfg === 'string' || validPositionObject(cfg) === true) { cfg = { position: cfg }; } // default for orientation is white if (cfg.orientation !== 'black') { cfg.orientation = 'white'; } CURRENT_ORIENTATION = cfg.orientation; // default for showNotation is true if (cfg.showNotation !== false) { cfg.showNotation = true; } // default for draggable is false if (cfg.draggable !== true) { cfg.draggable = false; } // default for dropOffBoard is 'snapback' if (cfg.dropOffBoard !== 'trash') { cfg.dropOffBoard = 'snapback'; } // default for sparePieces is false if (cfg.sparePieces !== true) { cfg.sparePieces = false; } // draggable must be true if sparePieces is enabled if (cfg.sparePieces === true) { cfg.draggable = true; } // default piece theme is wikipedia if (cfg.hasOwnProperty('pieceTheme') !== true || (typeof cfg.pieceTheme !== 'string' && typeof cfg.pieceTheme !== 'function')) { cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png'; } // animation speeds if (cfg.hasOwnProperty('appearSpeed') !== true || validAnimationSpeed(cfg.appearSpeed) !== true) { cfg.appearSpeed = 200; } if (cfg.hasOwnProperty('moveSpeed') !== true || validAnimationSpeed(cfg.moveSpeed) !== true) { cfg.moveSpeed = 200; } if (cfg.hasOwnProperty('snapbackSpeed') !== true || validAnimationSpeed(cfg.snapbackSpeed) !== true) { cfg.snapbackSpeed = 50; } if (cfg.hasOwnProperty('snapSpeed') !== true || validAnimationSpeed(cfg.snapSpeed) !== true) { cfg.snapSpeed = 25; } if (cfg.hasOwnProperty('trashSpeed') !== true || validAnimationSpeed(cfg.trashSpeed) !== true) { cfg.trashSpeed = 100; } // make sure position is valid if (cfg.hasOwnProperty('position') === true) { if (cfg.position === 'start') { CURRENT_POSITION = deepCopy(START_POSITION); } else if (validFen(cfg.position) === true) { CURRENT_POSITION = fenToObj(cfg.position); } else if (validPositionObject(cfg.position) === true) { CURRENT_POSITION = deepCopy(cfg.position); } else { error(7263, 'Invalid value passed to config.position.', cfg.position); } } return true; } //------------------------------------------------------------------------------ // DOM Misc //------------------------------------------------------------------------------ // calculates square size based on the width of the container // got a little CSS black magic here, so let me explain: // get the width of the container element (could be anything), reduce by 1 for // fudge factor, and then keep reducing until we find an exact mod 8 for // our square size function calculateSquareSize() { var containerWidth = parseInt(containerEl.css('width'), 10); // defensive, prevent infinite loop if (! containerWidth || containerWidth <= 0) { return 0; } var boardWidth = containerWidth; while (boardWidth % 8 !== 0 && boardWidth > 0) { boardWidth--; } return (boardWidth / 8); } // create random IDs for elements function createElIds() { // squares on the board for (var i = 0; i < COLUMNS.length; i++) { for (var j = 1; j <= 8; j++) { var square = COLUMNS[i] + j; SQUARE_ELS_IDS[square] = square + '-' + createId(); } } // spare pieces var pieces = 'KQRBNP'.split(''); for (var i = 0; i < pieces.length; i++) { var whitePiece = 'w' + pieces[i]; var blackPiece = 'b' + pieces[i]; SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId(); SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId(); } } //------------------------------------------------------------------------------ // Markup Building //------------------------------------------------------------------------------ function buildBoardContainer() { var html = '<div class="' + CSS.chessboard + '">'; if (cfg.sparePieces === true) { html += '<div class="' + CSS.sparePieces + ' ' + CSS.sparePiecesTop + '"></div>'; } html += '<div class="' + CSS.board + '"></div>'; if (cfg.sparePieces === true) { html += '<div class="' + CSS.sparePieces + ' ' + CSS.sparePiecesBottom + '"></div>'; } html += '</div>'; return html; } /* var buildSquare = function(color, size, id) { var html = '<div class="' + CSS.square + ' ' + CSS[color] + '" ' + 'style="width: ' + size + 'px; height: ' + size + 'px" ' + 'id="' + id + '">'; if (cfg.showNotation === true) { } html += '</div>'; return html; }; */ function buildBoard(orientation) { if (orientation !== 'black') { orientation = 'white'; } var html = ''; // algebraic notation / orientation var alpha = deepCopy(COLUMNS); var row = 8; if (orientation === 'black') { alpha.reverse(); row = 1; } var squareColor = 'white'; for (var i = 0; i < 8; i++) { html += '<div class="' + CSS.row + '">'; for (var j = 0; j < 8; j++) { var square = alpha[j] + row; html += '<div class="' + CSS.square + ' ' + CSS[squareColor] + ' ' + 'square-' + square + '" ' + 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' + 'id="' + SQUARE_ELS_IDS[square] + '" ' + 'data-square="' + square + '">'; html += '</div>'; // end .square squareColor = (squareColor === 'white' ? 'black' : 'white'); } html += '<div class="' + CSS.clearfix + '"></div></div>'; squareColor = (squareColor === 'white' ? 'black' : 'white'); if (orientation === 'white') { row--; } else { row++; } } return html; } function buildPieceImgSrc(piece) { if (typeof cfg.pieceTheme === 'function') { return cfg.pieceTheme(piece); } if (typeof cfg.pieceTheme === 'string') { return cfg.pieceTheme.replace(/{piece}/g, piece); } // NOTE: this should never happen error(8272, 'Unable to build image source for cfg.pieceTheme.'); return ''; } function buildPiece(piece, hidden, id) { var html = '<img src="' + buildPieceImgSrc(piece) + '" '; if (id && typeof id === 'string') { html += 'id="' + id + '" '; } html += 'alt="" ' + 'class="' + CSS.piece + '" ' + 'data-piece="' + piece + '" ' + 'style="width: ' + SQUARE_SIZE + 'px;' + 'height: ' + SQUARE_SIZE + 'px;'; if (hidden === true) { html += 'display:none;'; } html += '" />'; return html; } function buildSparePieces(color) { var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP']; if (color === 'black') { pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP']; } var html = ''; for (var i = 0; i < pieces.length; i++) { html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]); } return html; } //------------------------------------------------------------------------------ // Animations //------------------------------------------------------------------------------ function animateSquareToSquare(src, dest, piece, completeFn) { // get information about the source and destination squares var srcSquareEl = $('#' + SQUARE_ELS_IDS[src]); var srcSquarePosition = srcSquareEl.offset(); var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]); var destSquarePosition = destSquareEl.offset(); // create the animated piece and absolutely position it // over the source square var animatedPieceId = createId(); $('body').append(buildPiece(piece, true, animatedPieceId)); var animatedPieceEl = $('#' + animatedPieceId); animatedPieceEl.css({ display: '', position: 'absolute', top: srcSquarePosition.top, left: srcSquarePosition.left }); // remove original piece from source square srcSquareEl.find('.' + CSS.piece).remove(); // on complete var complete = function() { // add the "real" piece to the destination square destSquareEl.append(buildPiece(piece)); // remove the animated piece animatedPieceEl.remove(); // run complete function if (typeof completeFn === 'function') { completeFn(); } }; // animate the piece to the destination square var opts = { duration: cfg.moveSpeed, complete: complete }; animatedPieceEl.animate(destSquarePosition, opts); } function animateSparePieceToSquare(piece, dest, completeFn) { var srcOffset = $('#' + SPARE_PIECE_ELS_IDS[piece]).offset(); var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]); var destOffset = destSquareEl.offset(); // create the animate piece var pieceId = createId(); $('body').append(buildPiece(piece, true, pieceId)); var animatedPieceEl = $('#' + pieceId); animatedPieceEl.css({ display: '', position: 'absolute', left: srcOffset.left, top: srcOffset.top }); // on complete var complete = function() { // add the "real" piece to the destination square destSquareEl.find('.' + CSS.piece).remove(); destSquareEl.append(buildPiece(piece)); // remove the animated piece animatedPieceEl.remove(); // run complete function if (typeof completeFn === 'function') { completeFn(); } }; // animate the piece to the destination square var opts = { duration: cfg.moveSpeed, complete: complete }; animatedPieceEl.animate(destOffset, opts); } // execute an array of animations function doAnimations(a, oldPos, newPos) { ANIMATION_HAPPENING = true; var numFinished = 0; function onFinish() { numFinished++; // exit if all the animations aren't finished if (numFinished !== a.length) return; drawPositionInstant(); ANIMATION_HAPPENING = false; // run their onMoveEnd function if (cfg.hasOwnProperty('onMoveEnd') === true && typeof cfg.onMoveEnd === 'function') { cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos)); } } for (var i = 0; i < a.length; i++) { // clear a piece if (a[i].type === 'clear') { $('#' + SQUARE_ELS_IDS[a[i].square] + ' .' + CSS.piece) .fadeOut(cfg.trashSpeed, onFinish); } // add a piece (no spare pieces) if (a[i].type === 'add' && cfg.sparePieces !== true) { $('#' + SQUARE_ELS_IDS[a[i].square]) .append(buildPiece(a[i].piece, true)) .find('.' + CSS.piece) .fadeIn(cfg.appearSpeed, onFinish); } // add a piece from a spare piece if (a[i].type === 'add' && cfg.sparePieces === true) { animateSparePieceToSquare(a[i].piece, a[i].square, onFinish); } // move a piece if (a[i].type === 'move') { animateSquareToSquare(a[i].source, a[i].destination, a[i].piece, onFinish); } } } // returns the distance between two squares function squareDistance(s1, s2) { s1 = s1.split(''); var s1x = COLUMNS.indexOf(s1[0]) + 1; var s1y = parseInt(s1[1], 10); s2 = s2.split(''); var s2x = COLUMNS.indexOf(s2[0]) + 1; var s2y = parseInt(s2[1], 10); var xDelta = Math.abs(s1x - s2x); var yDelta = Math.abs(s1y - s2y); if (xDelta >= yDelta) return xDelta; return yDelta; } // returns an array of closest squares from square function createRadius(square) { var squares = []; // calculate distance of all squares for (var i = 0; i < 8; i++) { for (var j = 0; j < 8; j++) { var s = COLUMNS[i] + (j + 1); // skip the square we're starting from if (square === s) continue; squares.push({ square: s, distance: squareDistance(square, s) }); } } // sort by distance squares.sort(function(a, b) { return a.distance - b.distance; }); // just return the square code var squares2 = []; for (var i = 0; i < squares.length; i++) { squares2.push(squares[i].square); } return squares2; } // returns the square of the closest instance of piece // returns false if no instance of piece is found in position function findClosestPiece(position, piece, square) { // create array of closest squares from square var closestSquares = createRadius(square); // search through the position in order of distance for the piece for (var i = 0; i < closestSquares.length; i++) { var s = closestSquares[i]; if (position.hasOwnProperty(s) === true && position[s] === piece) { return s; } } return false; } // calculate an array of animations that need to happen in order to get // from pos1 to pos2 function calculateAnimations(pos1, pos2) { // make copies of both pos1 = deepCopy(pos1); pos2 = deepCopy(pos2); var animations = []; var squaresMovedTo = {}; // remove pieces that are the same in both positions for (var i in pos2) { if (pos2.hasOwnProperty(i) !== true) continue; if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) { delete pos1[i]; delete pos2[i]; } } // find all the "move" animations for (var i in pos2) { if (pos2.hasOwnProperty(i) !== true) continue; var closestPiece = findClosestPiece(pos1, pos2[i], i); if (closestPiece !== false) { animations.push({ type: 'move', source: closestPiece, destination: i, piece: pos2[i] }); delete pos1[closestPiece]; delete pos2[i]; squaresMovedTo[i] = true; } } // add pieces to pos2 for (var i in pos2) { if (pos2.hasOwnProperty(i) !== true) continue; animations.push({ type: 'add', square: i, piece: pos2[i] }) delete pos2[i]; } // clear pieces from pos1 for (var i in pos1) { if (pos1.hasOwnProperty(i) !== true) continue; // do not clear a piece if it is on a square that is the result // of a "move", ie: a piece capture if (squaresMovedTo.hasOwnProperty(i) === true) continue; animations.push({ type: 'clear', square: i, piece: pos1[i] }); delete pos1[i]; } return animations; } //------------------------------------------------------------------------------ // Control Flow //------------------------------------------------------------------------------ function drawPositionInstant() { // add the pieces for (var i in CURRENT_POSITION) { if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue; if (DRAGGING_A_PIECE && DRAGGED_PIECE_SOURCE === i) continue; $('#' + SQUARE_ELS_IDS[i]).html(buildPiece(CURRENT_POSITION[i])); } } function drawBoard() { boardEl.html(buildBoard(CURRENT_ORIENTATION)); drawPositionInstant(); if (cfg.sparePieces === true) { if (CURRENT_ORIENTATION === 'white') { sparePiecesTopEl.html(buildSparePieces('black')); sparePiecesBottomEl.html(buildSparePieces('white')); } else { sparePiecesTopEl.html(buildSparePieces('white')); sparePiecesBottomEl.html(buildSparePieces('black')); } } } // given a position and a set of moves, return a new position // with the moves executed function calculatePositionFromMoves(position, moves) { position = deepCopy(position); for (var i in moves) { if (moves.hasOwnProperty(i) !== true) continue; // skip the move if the position doesn't have a piece on the source square if (position.hasOwnProperty(i) !== true) continue; var piece = position[i]; delete position[i]; position[moves[i]] = piece; } return position; } function setCurrentPosition(position) { var oldPos = deepCopy(CURRENT_POSITION); var newPos = deepCopy(position); var oldFen = objToFen(oldPos); var newFen = objToFen(newPos); // do nothing if no change in position if (oldFen === newFen) return; // run their onChange function if (cfg.hasOwnProperty('onChange') === true && typeof cfg.onChange === 'function') { cfg.onChange(oldPos, newPos); } // update state CURRENT_POSITION = position; } function isXYOnSquare(x, y) { for (var i in SQUARE_ELS_OFFSETS) { if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue; var s = SQUARE_ELS_OFFSETS[i]; if (x >= s.left && x < s.left + SQUARE_SIZE && y >= s.top && y < s.top + SQUARE_SIZE) { return i; } } return 'offboard'; } // records the XY coords of every square into memory function captureSquareOffsets() { SQUARE_ELS_OFFSETS = {}; for (var i in SQUARE_ELS_IDS) { if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue; SQUARE_ELS_OFFSETS[i] = $('#' + SQUARE_ELS_IDS[i]).offset(); } } function removeSquareHighlights() { boardEl.find('.' + CSS.square) .removeClass(CSS.highlight1 + ' ' + CSS.highlight2); } function snapbackDraggedPiece() { // there is no "snapback" for spare pieces if (DRAGGED_PIECE_SOURCE === 'spare') { trashDraggedPiece(); return; } removeSquareHighlights(); // animation complete function complete() { drawPositionInstant(); draggedPieceEl.css('display', 'none'); // run their onSnapbackEnd function if (cfg.hasOwnProperty('onSnapbackEnd') === true && typeof cfg.onSnapbackEnd === 'function') { cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION); } } // get source square position var sourceSquarePosition = $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]).offset(); // animate the piece to the target square var opts = { duration: cfg.snapbackSpeed, complete: complete }; draggedPieceEl.animate(sourceSquarePosition, opts); // set state DRAGGING_A_PIECE = false; } function trashDraggedPiece() { removeSquareHighlights(); // remove the source piece var newPosition = deepCopy(CURRENT_POSITION); delete newPosition[DRAGGED_PIECE_SOURCE]; setCurrentPosition(newPosition); // redraw the position drawPositionInstant(); // hide the dragged piece draggedPieceEl.fadeOut(cfg.trashSpeed); // set state DRAGGING_A_PIECE = false; } function dropDraggedPieceOnSquare(square) { removeSquareHighlights(); // update position var newPosition = deepCopy(CURRENT_POSITION); delete newPosition[DRAGGED_PIECE_SOURCE]; newPosition[square] = DRAGGED_PIECE; setCurrentPosition(newPosition); // get target square information var targetSquarePosition = $('#' + SQUARE_ELS_IDS[square]).offset(); // animation complete var complete = function() { drawPositionInstant(); draggedPieceEl.css('display', 'none'); // execute their onSnapEnd function if (cfg.hasOwnProperty('onSnapEnd') === true && typeof cfg.onSnapEnd === 'function') { cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE); } }; // snap the piece to the target square var opts = { duration: cfg.snapSpeed, complete: complete }; draggedPieceEl.animate(targetSquarePosition, opts); // set state DRAGGING_A_PIECE = false; } function beginDraggingPiece(source, piece, x, y) { // run their custom onDragStart function // their custom onDragStart function can cancel drag start if (typeof cfg.onDragStart === 'function' && cfg.onDragStart(source, piece, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) { return; } // set state DRAGGING_A_PIECE = true; DRAGGED_PIECE = piece; DRAGGED_PIECE_SOURCE = source; // if the piece came from spare pieces, location is offboard if (source === 'spare') { DRAGGED_PIECE_LOCATION = 'offboard'; } else { DRAGGED_PIECE_LOCATION = source; } // capture the x, y coords of all squares in memory captureSquareOffsets(); // create the dragged piece draggedPieceEl.attr('src', buildPieceImgSrc(piece)) .css({ display: '', position: 'absolute', left: x - (SQUARE_SIZE / 2), top: y - (SQUARE_SIZE / 2) }); if (source !== 'spare') { // highlight the source square and hide the piece $('#' + SQUARE_ELS_IDS[source]).addClass(CSS.highlight1) .find('.' + CSS.piece).css('display', 'none'); } } function updateDraggedPiece(x, y) { // put the dragged piece over the mouse cursor draggedPieceEl.css({ left: x - (SQUARE_SIZE / 2), top: y - (SQUARE_SIZE / 2) }); // get location var location = isXYOnSquare(x, y); // do nothing if the location has not changed if (location === DRAGGED_PIECE_LOCATION) return; // remove highlight from previous square if (validSquare(DRAGGED_PIECE_LOCATION) === true) { $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION]) .removeClass(CSS.highlight2); } // add highlight to new square if (validSquare(location) === true) { $('#' + SQUARE_ELS_IDS[location]).addClass(CSS.highlight2); } // run onDragMove if (typeof cfg.onDragMove === 'function') { cfg.onDragMove(location, DRAGGED_PIECE_LOCATION, DRAGGED_PIECE_SOURCE, DRAGGED_PIECE, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION); } // update state DRAGGED_PIECE_LOCATION = location; } function stopDraggedPiece(location) { // determine what the action should be var action = 'drop'; if (location === 'offboard' && cfg.dropOffBoard === 'snapback') { action = 'snapback'; } if (location === 'offboard' && cfg.dropOffBoard === 'trash') { action = 'trash'; } // run their onDrop function, which can potentially change the drop action if (cfg.hasOwnProperty('onDrop') === true && typeof cfg.onDrop === 'function') { var newPosition = deepCopy(CURRENT_POSITION); // source piece is a spare piece and position is off the board //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...} // position has not changed; do nothing // source piece is a spare piece and position is on the board if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) { // add the piece to the board newPosition[location] = DRAGGED_PIECE; } // source piece was on the board and position is off the board if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') { // remove the piece from the board delete newPosition[DRAGGED_PIECE_SOURCE]; } // source piece was on the board and position is on the board if (validSquare(DRAGGED_PIECE_SOURCE) === true && validSquare(location) === true) { // move the piece delete newPosition[DRAGGED_PIECE_SOURCE]; newPosition[location] = DRAGGED_PIECE; } var oldPosition = deepCopy(CURRENT_POSITION); var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE, newPosition, oldPosition, CURRENT_ORIENTATION); if (result === 'snapback' || result === 'trash') { action = result; } } // do it! if (action === 'snapback') { snapbackDraggedPiece(); } else if (action === 'trash') { trashDraggedPiece(); } else if (action === 'drop') { dropDraggedPieceOnSquare(location); } } //------------------------------------------------------------------------------ // Public Methods //------------------------------------------------------------------------------ // clear the board widget.clear = function(useAnimation) { widget.position({}, useAnimation); }; /* // get or set config properties // TODO: write this, GitHub Issue #1 widget.config = function(arg1, arg2) { // get the current config if (arguments.length === 0) { return deepCopy(cfg); } }; */ widget.set = function(key, value) { if (cfg.hasOwnProperty(key)) { cfg[key] = value; } else { error(1000, 'Invalid config key.', key); } }; // remove the widget from the page widget.destroy = function() { // remove markup containerEl.html(''); draggedPieceEl.remove(); // remove event handlers containerEl.unbind(); }; // shorthand method to get the current FEN widget.fen = function() { return widget.position('fen'); }; // flip orientation widget.flip = function() { widget.orientation('flip'); }; /* // TODO: write this, GitHub Issue #5 widget.highlight = function() { }; */ // move pieces widget.move = function() { // no need to throw an error here; just do nothing if (arguments.length === 0) return; var useAnimation = true; // collect the moves into an object var moves = {}; for (var i = 0; i < arguments.length; i++) { // any "false" to this function means no animations if (arguments[i] === false) { useAnimation = false; continue; } // skip invalid arguments if (validMove(arguments[i]) !== true) { error(2826, 'Invalid move passed to the move method.', arguments[i]); continue; } var tmp = arguments[i].split('-'); moves[tmp[0]] = tmp[1]; } // calculate position from moves var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves); // update the board widget.position(newPos, useAnimation); // return the new position object return newPos; }; widget.orientation = function(arg) { // no arguments, return the current orientation if (arguments.length === 0) { return CURRENT_ORIENTATION; } // set to white or black if (arg === 'white' || arg === 'black') { CURRENT_ORIENTATION = arg; drawBoard(); return; } // flip orientation if (arg === 'flip') { CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white'; drawBoard(); return; } error(5482, 'Invalid value passed to the orientation method.', arg); }; widget.position = function(position, useAnimation) { // no arguments, return the current position if (arguments.length === 0) { return deepCopy(CURRENT_POSITION); } // get position as FEN if (typeof position === 'string' && position.toLowerCase() === 'fen') { return objToFen(CURRENT_POSITION); } // default for useAnimations is true if (useAnimation !== false) { useAnimation = true; } // start position if (typeof position === 'string' && position.toLowerCase() === 'start') { position = deepCopy(START_POSITION); } // convert FEN to position object if (validFen(position) === true) { position = fenToObj(position); } // validate position object if (validPositionObject(position) !== true) { error(6482, 'Invalid value passed to the position method.', position); return; } if (useAnimation === true) { // start the animations doAnimations(calculateAnimations(CURRENT_POSITION, position), CURRENT_POSITION, position); // set the new position setCurrentPosition(position); } // instant update else { setCurrentPosition(position); drawPositionInstant(); } }; widget.resize = function() { // calulate the new square size SQUARE_SIZE = calculateSquareSize(); // set board width boardEl.css('width', (SQUARE_SIZE * 8) + 'px'); // set drag piece size draggedPieceEl.css({ height: SQUARE_SIZE, width: SQUARE_SIZE }); // spare pieces if (cfg.sparePieces === true) { containerEl.find('.' + CSS.sparePieces) .css('paddingLeft', (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px'); } // redraw the board drawBoard(); }; // set the starting position widget.start = function(useAnimation) { widget.position('start', useAnimation); }; //------------------------------------------------------------------------------ // Browser Events //------------------------------------------------------------------------------ function isTouchDevice() { return ('ontouchstart' in document.documentElement); } // reference: http://www.quirksmode.org/js/detect.html function isMSIE() { return (navigator && navigator.userAgent && navigator.userAgent.search(/MSIE/) !== -1); } function stopDefault(e) { e.preventDefault(); } function mousedownSquare(e) { // do nothing if we're not draggable if (cfg.draggable !== true) return; var square = $(this).attr('data-square'); // no piece on this square if (validSquare(square) !== true || CURRENT_POSITION.hasOwnProperty(square) !== true) { return; } beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY); } function touchstartSquare(e) { // do nothing if we're not draggable if (cfg.draggable !== true) return; var square = $(this).attr('data-square'); // no piece on this square if (validSquare(square) !== true || CURRENT_POSITION.hasOwnProperty(square) !== true) { return; } e = e.originalEvent; beginDraggingPiece(square, CURRENT_POSITION[square], e.changedTouches[0].pageX, e.changedTouches[0].pageY); } function mousedownSparePiece(e) { // do nothing if sparePieces is not enabled if (cfg.sparePieces !== true) return; var piece = $(this).attr('data-piece'); beginDraggingPiece('spare', piece, e.pageX, e.pageY); } function touchstartSparePiece(e) { // do nothing if sparePieces is not enabled if (cfg.sparePieces !== true) return; var piece = $(this).attr('data-piece'); e = e.originalEvent; beginDraggingPiece('spare', piece, e.changedTouches[0].pageX, e.changedTouches[0].pageY); } function mousemoveWindow(e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return; updateDraggedPiece(e.pageX, e.pageY); } function touchmoveWindow(e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return; // prevent screen from scrolling e.preventDefault(); updateDraggedPiece(e.originalEvent.changedTouches[0].pageX, e.originalEvent.changedTouches[0].pageY); } function mouseupWindow(e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return; // get the location var location = isXYOnSquare(e.pageX, e.pageY); stopDraggedPiece(location); } function touchendWindow(e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return; // get the location var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX, e.originalEvent.changedTouches[0].pageY); stopDraggedPiece(location); } function mouseenterSquare(e) { // do not fire this event if we are dragging a piece // NOTE: this should never happen, but it's a safeguard if (DRAGGING_A_PIECE !== false) return; if (cfg.hasOwnProperty('onMouseoverSquare') !== true || typeof cfg.onMouseoverSquare !== 'function') return; // get the square var square = $(e.currentTarget).attr('data-square'); // NOTE: this should never happen; defensive if (validSquare(square) !== true) return; // get the piece on this square var piece = false; if (CURRENT_POSITION.hasOwnProperty(square) === true) { piece = CURRENT_POSITION[square]; } // execute their function cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION); } function mouseleaveSquare(e) { // do not fire this event if we are dragging a piece // NOTE: this should never happen, but it's a safeguard if (DRAGGING_A_PIECE !== false) return; if (cfg.hasOwnProperty('onMouseoutSquare') !== true || typeof cfg.onMouseoutSquare !== 'function') return; // get the square var square = $(e.currentTarget).attr('data-square'); // NOTE: this should never happen; defensive if (validSquare(square) !== true) return; // get the piece on this square var piece = false; if (CURRENT_POSITION.hasOwnProperty(square) === true) { piece = CURRENT_POSITION[square]; } // execute their function cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION); } //------------------------------------------------------------------------------ // Initialization //------------------------------------------------------------------------------ function addEvents() { // prevent browser "image drag" $('body').on('mousedown mousemove', '.' + CSS.piece, stopDefault); // mouse drag pieces boardEl.on('mousedown', '.' + CSS.square, mousedownSquare); containerEl.on('mousedown', '.' + CSS.sparePieces + ' .' + CSS.piece, mousedownSparePiece); // mouse enter / leave square boardEl.on('mouseenter', '.' + CSS.square, mouseenterSquare); boardEl.on('mouseleave', '.' + CSS.square, mouseleaveSquare); // IE doesn't like the events on the window object, but other browsers // perform better that way if (isMSIE() === true) { // IE-specific prevent browser "image drag" document.ondragstart = function() { return false; }; $('body').on('mousemove', mousemoveWindow); $('body').on('mouseup', mouseupWindow); } else { $(window).on('mousemove', mousemoveWindow); $(window).on('mouseup', mouseupWindow); } // touch drag pieces if (isTouchDevice() === true) { boardEl.on('touchstart', '.' + CSS.square, touchstartSquare); containerEl.on('touchstart', '.' + CSS.sparePieces + ' .' + CSS.piece, touchstartSparePiece); $(window).on('touchmove', touchmoveWindow); $(window).on('touchend', touchendWindow); } } function initDom() { // build board and save it in memory containerEl.html(buildBoardContainer()); boardEl = containerEl.find('.' + CSS.board); if (cfg.sparePieces === true) { sparePiecesTopEl = containerEl.find('.' + CSS.sparePiecesTop); sparePiecesBottomEl = containerEl.find('.' + CSS.sparePiecesBottom); } // create the drag piece var draggedPieceId = createId(); $('body').append(buildPiece('wP', true, draggedPieceId)); draggedPieceEl = $('#' + draggedPieceId); // get the border size BOARD_BORDER_SIZE = parseInt(boardEl.css('borderLeftWidth'), 10); // set the size and draw the board widget.resize(); } function init() { if (checkDeps() !== true || expandConfig() !== true) return; // create unique IDs for all the elements we will create createElIds(); initDom(); addEvents(); } // go time init(); // return the widget object return widget; }; // end window.ChessBoard // expose util functions window.ChessBoard.fenToObj = fenToObj; window.ChessBoard.objToFen = objToFen; })(); // end anonymous wrapper
'use strict'; var context = require.context('./components/', true, /-test\.(js|jsx)$/); context.keys().forEach(context);
/** * @author TristanVALCKE / https://github.com/Itee */
infinispan.plusMinus = function(num) { if (num > 0) return 1; else if (num < 0) return -1; else return 1; }; infinispan.errorState = {}; infinispan.errorState.rate = 0.5; infinispan.errorXOffset = 5; infinispan.addMouseover = function(errorElement) { if ($.isArray(errorElement)) { for ( var i = 0; i < errorElement.length; i++) { errorElement[i].object.mouseover(function() { }); } } else { errorElement.object.mouseover(function() { }); } }; infinispan.ErrorStateElementView = Backbone.View.extend({ // /stateを渡す。NORMAL or ERROR or WARN initialize : function(argument) { _.bindAll(); this.model.set({ state : argument.state }); // console.log(argument.state); this._paper = argument.paper; if (this._paper == null) { alert("paper is not exist"); return; } this.taskInfo = argument.info; this.id = this.model.get("objectId"); this.render(); // console.log("errorState is called"); }, render : function() { var color = this.getStateColor(); this.model.set({ "attributes" : { fill : color, stroke : color } }, { silent : true }); if (this.model.attributes.width == null) { this.model.attributes.width = 10; } if (this.model.attributes.height == null) { this.model.attributes.height = 10; } this.model.attributes.width = this.model.attributes.width * infinispan.errorState.rate; this.model.attributes.height = this.model.attributes.height * infinispan.errorState.rate; var lengthOfArrow = Math.sqrt(this.model.attributes.width * this.model.attributes.width + this.model.attributes.height * this.model.attributes.height); var rightDownData = new wgp.MapElement({ objectId : 102, objectName : null, height : this.model.attributes.height * infinispan.plusMinus(this.model.attributes.height), width : -this.model.attributes.width * infinispan.plusMinus(this.model.attributes.width), pointX : this.model.attributes.pointX + this.model.attributes.width / 2 + infinispan.errorXOffset, pointY : this.model.attributes.pointY - this.model.attributes.height / 2 }); var rightUpData = new wgp.MapElement({ objectId : 103, objectName : null, height : -this.model.attributes.height * infinispan.plusMinus(this.model.attributes.height), width : -this.model.attributes.width * infinispan.plusMinus(this.model.attributes.width), pointX : this.model.attributes.pointX + this.model.attributes.width / 2 + infinispan.errorXOffset, pointY : this.model.attributes.pointY + this.model.attributes.height / 2 }); rightDownData.set({ "attributes" : { fill : color, stroke : color, "stroke-width" : 10 } }, { silent : true }); rightUpData.set({ "attributes" : { fill : color, stroke : color, "stroke-width" : 10 } }, { silent : true }); this.element = []; this.element[0] = new line(rightDownData.attributes, this._paper); this.element[1] = new line(rightUpData.attributes, this._paper); var anim2 = Raphael.animation({ "stroke-opacity" : 1 }, 1500, "easeIn",function(){this.animate(anim1);}); var anim1 = Raphael.animation({ "stroke-opacity" : 0 }, 1500, "easeOut",function(){this.animate(anim2);}); this.element[0].object.animate(anim1); this.element[1].object.animate(anim1); //this.element[1].object.animate(anim1); infinispan.addMouseover(this.element); }, update : function(model) { var instance = this; var color = this.getStateColor(); this.model.set({ "fill" : color }, { silent : true }); this.element[0].setAttributes(model); this.element[1].setAttributes(model); }, remove : function(property) { this.element[0].hide(); this.element[1].hide(); }, getStateColor : function() { var state = this.model.get("state"); var color = infinispan.constants.STATE_COLOR[state]; if (color == null) { color = infinispan.constants.STATE_COLOR[infinispan.constants.STATE.NORMAL]; } return color; } });
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: ``, frameworks: [`jasmine`, `@angular/cli`], plugins: [ require(`karma-jasmine`), require(`karma-chrome-launcher`), require(`karma-jasmine-html-reporter`), require(`karma-coverage-istanbul-reporter`), require(`@angular/cli/plugins/karma`) ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, files: [ {pattern: `./src/test.ts`, watched: false} ], preprocessors: { './src/test.ts': [`@angular/cli`] }, mime: { 'text/x-typescript': [`ts`, `tsx`] }, coverageIstanbulReporter: { reports: [`html`, `lcovonly`], fixWebpackSourcePaths: true }, angularCli: { environment: `dev` }, reporters: config.angularCli && config.angularCli.codeCoverage ? [`progress`, `coverage-istanbul`] : [`progress`, `kjhtml`], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: [`Chrome`], singleRun: false }); };
'use strict'; function committeeContributorsPageController($scope, contributors) { $scope.contributors = contributors; } module.exports = committeeContributorsPageController;
YUI.add("gallery-outside-events",function(B){var A=["blur","change","click","dblclick","focus","keydown","keypress","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","select","submit"];B.Event.defineOutside=function(D,C){C=C||D+"outside";B.Event.define(C,{on:function(G,E,F){E.onHandle=B.one("doc").on(D,function(H){if(this.isOutside(G,H.target)){F.fire(H);}},this);},detach:function(G,E,F){E.onHandle.detach();},delegate:function(H,F,G,E){F.delegateHandle=B.one("doc").delegate(D,function(I){if(this.isOutside(H,I.target)){G.fire(I);}},E,this);},detachDelegate:function(H,F,G,E){F.delegateHandle.detach();},isOutside:function(E,F){return F!==E&&!F.ancestor(function(G){return G===E;});}});};B.each(A,function(C){B.Event.defineOutside(C);});},"gallery-2010.08.18-17-12",{requires:["event-focus","event-synthetic"]});
import {assert} from '@webex/test-helper-chai'; import RoapUtil from '@webex/plugin-meetings/src/roap/util'; import PeerConnectionManager from '@webex/plugin-meetings/src/peer-connection-manager/index.js'; import sinon from 'sinon'; describe('RoapUtil', () => { describe('updatePeerConnection', () => { let meeting, session; beforeEach('stub PeerConnectionManager', () => { meeting = { mediaProperties: { peerConnection: {name: 'peer-connection'} }, roap: { lastRoapOffer: 'lastRoapOffer' } }; session = {OFFER: {sdps: ['sdp1', 'sdp2']}}; PeerConnectionManager.updatePeerConnection = sinon.stub().returns(Promise.resolve()); }); it('should just call PeerConnection.updatePeerConnection', async () => { await RoapUtil.updatePeerConnection(meeting, session); assert.calledOnce(PeerConnectionManager.updatePeerConnection); }); }); });
require('./camera'); require('./geometry'); require('./material'); require('./light');
var Promise = require('bluebird'); var util = require(__dirname+'/util.js'); var Errors = require(__dirname+'/errors.js'); var schemaUtil = require(__dirname+'/schema.js'); var Feed = require(__dirname+'/feed.js'); /** * Constructor for a Query. A Query basically wraps a ReQL queries to keep track * of the model returned and if a post-query validation is required. * @param {Function=} model Model of the documents returned * @param {ReQLQuery=} current ReQL query (rethinkdbdash) * @param {boolean=} postValidation whether post query validation should be performed */ function Query(model, query, postValidation, error) { var self = this; this._model = model; // constructor of the model we should use for the results. if (model !== undefined) { this._r = model._getModel()._thinky.r; util.loopKeys(model._getModel()._staticMethods, function(staticMethods, key) { (function(_key) { self[_key] = function() { return staticMethods[_key].apply(self, arguments); }; })(key); }); } if (query !== undefined) { this._query = query; } else if (model !== undefined) { // By default, we initialize the query to `r.table(<tableName>)`. this._query = this._r.table(model.getTableName()); } if (postValidation) { this._postValidation = postValidation === true; } if (error) { // Note `Query.prototype.error` is defined because of `r.error`, so we shouldn't // defined this.error. this._error = error; } } /** * Execute a Query and expect the results to be object(s) that can be converted * to instances of the model. * @param {Object=} options The options passed to the driver's method `run` * @param {Function=} callback * @return {Promise} return a promise that will be resolved when the query and * the instances of the models will be created (include the potential * asynchronous hooks). */ Query.prototype.run = function(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } return this._execute(options, true).nodeify(callback); } /** * Execute a Query * @param {Object=} options The options passed to the driver's method `run` * @param {Function=} callback * @return {Promise} return a promise that will be resolved with the results * of the query. */ Query.prototype.execute = function(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } return this._execute(options, false).nodeify(callback); } /** * Internal method to execute a query. Called by `run` and `execute`. * @param {Object} options The options passed to the driver's method `run` * @param {boolean} parse Whether the results should be converted as instance(s) of the model * @param {Function=} callback * @return {Promise} return a promise that will be resolved with the results * of the query. * @private */ Query.prototype._execute = function(options, parse) { var self = this; options = options || {}; var fullOptions = {groupFormat: 'raw'} util.loopKeys(options, function(options, key) { fullOptions[key] = options[key] }); if (parse !== true) { fullOptions.cursor = true; } if (self._model._error !== null) { return Promise.reject(self._model._error); } return self._model.tableReady().then(function() { return self._executeCallback(fullOptions, parse, options.groupFormat); }); } Query.prototype._executeCallback = function(fullOptions, parse, groupFormat) { var self = this; if (self._error !== undefined) { return Promise.reject(new Error("The partial value is not valid, so the write was not executed. The original error was:\n"+self._error.message)); } return self._query.run(fullOptions).then(function(result) { if (result === null && parse) { throw new Errors.DocumentNotFound(); } // Expect a write result from RethinkDB if (self._postValidation === true) { return self._validateQueryResult(result); } if (result != null && typeof result.getType === 'function') { var resultType = result.getType(); if (resultType === 'Feed' || resultType === 'OrderByLimitFeed' || resultType === 'UnionedFeed' ) { var feed = new Feed(result, self._model); return feed; } if (resultType === 'AtomFeed') { return result.next().then(function(initial) { var value = initial.new_val || {}; return self._model._parse(value).then(function(doc) { doc._setFeed(result); return doc; }); }); } } if (parse === true) { return self._model._parse(result); } if (groupFormat !== 'raw') { return Query.prototype._convertGroupedData(result); } return result; }).catch(function(err) { var notFoundRegex = new RegExp('^' + new Errors.DocumentNotFound().message); if (err.message.match(notFoundRegex)) { //Reject with an instance of Errors.DocumentNotFound err = new Errors.DocumentNotFound(err.message); } return Promise.reject(err); }) }; Query.prototype._validateQueryResult = function(result) { var self = this; if (result.errors > 0) { return Promise.reject(new Errors.InvalidWrite("An error occured during the write", result)); } if (!Array.isArray(result.changes)) { if (self._isPointWrite()) { return Promise.resolve(); } return Promise.resolve([]); } var promises = []; for(var i=0; i<result.changes.length; i++) { (function(i) { if (result.changes[i].new_val !== null) { promises.push(self._model._parse(result.changes[i].new_val)); } })(i) } return Promise.all(promises).then(function(result) { if (self._isPointWrite()) { return result[0]; } return result; }).error(function(error) { if (error instanceof Errors.DocumentNotFound) { // Should we send back null? } else { var revertPromises = []; var primaryKeys = []; var keysToValues = {}; var r = self._model._thinky.r; for(var p=0; p<result.changes.length; p++) { // Extract the primary key of the document saved in the database var primaryKey = util.extractPrimaryKey( result.changes[p].old_val, result.changes[p].new_val, self._model._pk) if (primaryKey === undefined) { continue; } if (typeof primaryKey === "string") { keysToValues[primaryKey] = result.changes[p].old_val; primaryKeys.push(primaryKey); } else { // Replace documents with non-string type primary keys // one by one. revertPromises.push(r.table(self._model.getTableName()) .get(primaryKey) .replace(result.changes[p].old_val) .run()); } } // Replace all documents with string-type primary keys // in a single replace() operation. if (primaryKeys.length) { revertPromises.push( r.table(self._model.getTableName()).getAll(r.args(primaryKeys)).replace(function(doc) { return r.expr(keysToValues)(doc(self._model._pk)); }).run() ); } return Promise.all(revertPromises).then(function(result) { throw new Error("The write failed, and the changes were reverted."); }).error(function(error) { throw new Error("The write failed, and the attempt to revert the changes failed with the error:\n"+error.message); }); } }) }; /** * Convert GROUPED_DATA results to [group: <group>, reduction: <reduction>] * This does the same as the driver. The reduction is not converted to * instances of the model. */ Query.prototype._convertGroupedData = function(data) { if (util.isPlainObject(data) && (data.$reql_type$ === "GROUPED_DATA")) { var result = []; var reduction; for(var i=0; i<data.data.length; i++) { result.push({ group: data.data[i][0], reduction: data.data[i][1] }); } return result; } else { return data; } } /** * Perform a join given the relations on this._model * @param {Object=} modelToGet explicit joined documents to retrieve * @param {boolean} getAll Internal argument, if `modelToGet` is undefined, `getAll` will * be set to `true` and `getJoin` will be greedy and keep recursing as long as it does not * hit a circular reference * @param {Object=} gotModel Internal argument, the model we are already fetching. * @return {Query} */ Query.prototype.getJoin = function(modelToGet, getAll, gotModel) { var self = this; var r = self._model._getModel()._thinky.r; var model = this._model; var joins = this._model._getModel()._joins; var getAll = modelToGet === undefined; if (util.isPlainObject(modelToGet) === false) { modelToGet = {}; } var innerQuery; gotModel = gotModel || {}; gotModel[model.getTableName()] = true; util.loopKeys(joins, function(joins, key) { if (util.recurse(key, joins, modelToGet, getAll, gotModel)) { switch (joins[key].type) { case 'hasOne': case 'belongsTo': self._query = self._query.merge(function(doc) { return r.branch( doc.hasFields(joins[key].leftKey), r.table(joins[key].model.getTableName()).getAll(doc(joins[key].leftKey), {index: joins[key].rightKey}).coerceTo("ARRAY").do(function(result) { innerQuery = new Query(joins[key].model, result.nth(0)); if ((modelToGet[key] != null) && (typeof modelToGet[key]._apply === 'function')) { innerQuery = modelToGet[key]._apply(innerQuery); } innerQuery = innerQuery.getJoin(modelToGet[key], getAll, gotModel)._query; return r.branch( result.count().eq(1), r.object(key, innerQuery), r.branch( result.count().eq(0), {}, r.error(r.expr("More than one element found for ").add(doc.coerceTo("STRING")).add(r.expr("for the field ").add(key))) ) ) }), {} ) }); break; case 'hasMany': self._query = self._query.merge(function(doc) { innerQuery = new Query(joins[key].model, r.table(joins[key].model.getTableName()) .getAll(doc(joins[key].leftKey), {index: joins[key].rightKey})) if ((modelToGet[key] != null) && (typeof modelToGet[key]._apply === 'function')) { innerQuery = modelToGet[key]._apply(innerQuery); } innerQuery = innerQuery.getJoin(modelToGet[key], getAll, gotModel); if ((modelToGet[key] == null) || (modelToGet[key]._array !== false)) { innerQuery = innerQuery.coerceTo("ARRAY"); } innerQuery = innerQuery._query; return r.branch( doc.hasFields(joins[key].leftKey), r.object(key, innerQuery), {} ) }); break; case 'hasAndBelongsToMany': self._query = self._query.merge(function(doc) { if ((model.getTableName() === joins[key].model.getTableName()) && (joins[key].leftKey === joins[key].rightKey)) { // In case the model is linked with itself on the same key innerQuery = r.table(joins[key].link).getAll(doc(joins[key].leftKey), {index: joins[key].leftKey+"_"+joins[key].leftKey}).concatMap(function(link) { return r.table(joins[key].model.getTableName()).getAll( r.branch( doc(joins[key].leftKey).eq(link(joins[key].leftKey+"_"+joins[key].leftKey).nth(0)), link(joins[key].leftKey+"_"+joins[key].leftKey).nth(1), link(joins[key].leftKey+"_"+joins[key].leftKey).nth(0) ) , {index: joins[key].rightKey}) }); if ((modelToGet[key] != null) && (typeof modelToGet[key]._apply === 'function')) { innerQuery = modelToGet[key]._apply(innerQuery); } if ((modelToGet[key] == null) || (modelToGet[key]._array !== false)) { innerQuery = innerQuery.coerceTo("ARRAY"); } return r.branch( doc.hasFields(joins[key].leftKey), r.object(key, new Query(joins[key].model, innerQuery).getJoin(modelToGet[key], getAll, gotModel)._query), {} ) } else { innerQuery = r.table(joins[key].link).getAll(doc(joins[key].leftKey), {index: model.getTableName()+"_"+joins[key].leftKey}).concatMap(function(link) { return r.table(joins[key].model.getTableName()).getAll(link(joins[key].model.getTableName()+"_"+joins[key].rightKey), {index: joins[key].rightKey}) }); if ((modelToGet[key] != null) && (typeof modelToGet[key]._apply === 'function')) { innerQuery = modelToGet[key]._apply(innerQuery) } if ((modelToGet[key] == null) || (modelToGet[key]._array !== false)) { innerQuery = innerQuery.coerceTo("ARRAY"); } return r.branch( doc.hasFields(joins[key].leftKey), r.object(key, new Query(joins[key].model, innerQuery).getJoin(modelToGet[key], getAll, gotModel)._query), {} ) } }); break; } } }); return self; }; /** * Remove the provided relation * @param {Object=} relationsToRemove explicit joined documents to retrieve * @return {Query} */ Query.prototype.removeRelations = function(relationsToRemove) { var self = this; var queries = []; var originalQuery = self._query; util.loopKeys(relationsToRemove, function(joins, key) { var join = self._model._getModel()._joins[key]; if (join === undefined) { return; } switch (join.type) { case 'hasOne': case 'hasMany': queries.push(self._query(join.leftKey).do(function(keys) { return self._r.branch( self._r.expr(["ARRAY", "STREAM", "TABLE_SLICE"]).contains(keys.typeOf()).not(), // keys is a single value join.model.getAll(keys, {index: join.rightKey}).replace(function(row) { return row.without(join.rightKey) })._query, self._r.branch( // keys.typeOf().eq("ARRAY") keys.isEmpty(), {errors: 0}, join.model.getAll(self._r.args(keys), {index: join.rightKey}).replace(function(row) { return row.without(join.rightKey) })._query ) ) })) break; case 'belongsTo': queries.push(self._query.replace(function(row) { return row.without(join.leftKey) })); break; case 'hasAndBelongsToMany': queries.push(self._query(join.leftKey).do(function(keys) { return self._r.branch( self._r.expr(["ARRAY", "STREAM", "TABLE_SLICE"]).contains(keys.typeOf()).not(), // keys is a single value self._r.table(join.link).getAll(keys, {index: self._model.getTableName()+"_"+join.leftKey}).delete(), self._r.branch( // keys.typeOf().eq("ARRAY") keys.isEmpty(), {errors: 0}, self._r.table(join.link).getAll(self._r.args(keys), {index: self._model.getTableName()+"_"+join.leftKey}).delete() ) ) })); break; } }); if (queries.length > 0) { self._query = self._r.expr(queries).forEach(function(result) { return result; }) } else { self._query = self._r.expr({errors: 0}); } self._query = self._query.do(function(results) { return self._r.branch( results('errors').eq(0), originalQuery, self._r.error(results('errors')) ) }); return self; }; /** * Import all the methods from rethinkdbdash, expect the private one (the one * starting with an underscore). * Some method are slightly changed: `get`, `update`, `replace`. */ (function() { var Term = require('rethinkdbdash')({pool: false}).expr(1).__proto__; util.loopKeys(Term, function(Term, key) { if (key === 'run' || key[0] === '_') return; // Note: We suppose that no method has an empty name switch (key) { case 'get': // `get` in thinky returns an error if the document is not found. // The driver currently just returns `null`. (function(key) { Query.prototype[key] = function() { return new Query(this._model, this._query[key].apply(this._query, arguments)).default(this._r.error(new Errors.DocumentNotFound().message)); } })(key); break; case 'update': case 'replace': // `update` and `replace` can be used. A partial validation is performed before // sending the query, and a full validation is performed after the query. If the // validation fails, the document(s) will be reverted. (function(key) { Query.prototype[key] = function(value, options) { options = options || {}; options.returnChanges = true; var error = null; var self = this; util.tryCatch(function() { if (util.isPlainObject(value)) { schemaUtil.validate(value, self._model._schema, '', {enforce_missing: false}); } }, function(err) { error = err; }); return new Query(this._model, this._query[key].call(this._query, value, options), true, error); } })(key); break; case 'changes': (function(key) { Query.prototype[key] = function() { // In case of `get().changes()` we want to remove the default(r.errror(...)) // TODO: Do not hardcode this? if ((typeof this._query === 'function') && (this._query._query[0] === 92)) { this._query._query = this._query._query[1][0]; } return new Query(this._model, this._query[key].apply(this._query, arguments)); } })(key); break; case 'then': case 'error': case 'catch': case 'finally': (function(key) { Query.prototype[key] = function() { var promise = this.run(); return promise[key].apply(promise, arguments); } })(key); break; default: (function(key) { Query.prototype[key] = function() { // Create a new query to let people fork it return new Query(this._model, this._query[key].apply(this._query, arguments)); } })(key); break; } }); })(); Query.prototype._isPointWrite = function() { return Array.isArray(this._query._query) && (this._query._query.length > 1) && Array.isArray(this._query._query[1]) && (this._query._query[1].length > 0) && Array.isArray(this._query._query[1][0]) && (this._query._query[1][0].length > 1) && Array.isArray(this._query._query[1][0][1]) && (this._query._query[1][0][1].length > 0) && Array.isArray(this._query._query[1][0][1][0]) && (this._query._query[1][0][1][0][0] === 16) } /** * Convert the query to its string representation. * @return {string} */ Query.prototype.toString = function() { return this._query.toString(); } module.exports = Query;
function WorldEditorOrthographicCamera(domElement) { this.domElement = domElement this.camera = new THREE.OrthographicCamera( -1, 1, 1, -1, -10000, 10000) this.camera.zoom = 10 this.aspect = 1 this.camera.layers.enable(1) E2.core.on('resize', this.resize.bind(this)) } WorldEditorOrthographicCamera.prototype.resize = function() { var isFullscreen = E2.util.isFullscreen() var wh = { width: window.innerWidth, height: window.innerHeight } if (!isFullscreen) { wh.width = this.domElement.clientWidth wh.height = this.domElement.clientHeight if (typeof(E2.app.calculateCanvasArea) !== 'undefined') wh = E2.app.calculateCanvasArea() } this.aspect = wh.width / wh.height this.camera.left = -this.aspect this.camera.right = this.aspect this.camera.top = 1 this.camera.bottom = -1 } WorldEditorOrthographicCamera.prototype.update = function() { var distance = this.camera.position.length() var zoom = 1 / distance if (this.camera.zoom !== zoom) { this.camera.zoom = zoom this.camera.updateProjectionMatrix() } }
var fs = require('fs'); var gulp = require('gulp'); var Server = require('karma').Server; var concat = require('gulp-concat'); var jshint = require('gulp-jshint'); var header = require('gulp-header'); var footer = require('gulp-footer'); var rename = require('gulp-rename'); var es = require('event-stream'); var del = require('del'); var uglify = require('gulp-uglify'); var plumber = require('gulp-plumber');//To prevent pipe breaking caused by errors at 'watch' var git = require('gulp-git'); var bump = require('gulp-bump'); var runSequence = require('run-sequence'); var versionAfterBump; gulp.task('default', ['build', 'test']); gulp.task('build', ['scripts']); gulp.task('test', ['build', 'karma']); gulp.task('watch', ['build', 'karma-watch'], function() { gulp.watch(['src/**/*.{js,html}'], ['build']); }); gulp.task('clean', function(cb) { del(['dist'], cb); }); gulp.task('scripts', ['clean'], function() { var buildLib = function() { return gulp.src(['src/*.js']) .pipe(plumber({ errorHandler: handleError })) .pipe(header('(function () { \n\'use strict\';\n')) .pipe(footer('\n}());')) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }; var config = { pkg: JSON.parse(fs.readFileSync('./package.json')), banner: '/*!\n' + ' * <%= pkg.name %>\n' + ' * <%= pkg.homepage %>\n' + ' * Version: <%= pkg.version %> - <%= timestamp %>\n' + ' * License: <%= pkg.license %>\n' + ' */\n\n\n' }; return es.merge(buildLib()) .pipe(plumber({ errorHandler: handleError })) .pipe(concat('event.js')) .pipe(header(config.banner, { timestamp: (new Date()).toISOString(), pkg: config.pkg })) .pipe(gulp.dest('dist')) .pipe(uglify({preserveComments: 'some'})) .pipe(rename({extname: '.min.js'})) .pipe(gulp.dest('dist')); }); gulp.task('karma', ['build'], function() { var server = new Server({configFile: __dirname + '/karma.conf.js', singleRun: true}); server.start(); }); gulp.task('karma-watch', ['build'], function() { var server = new Server({configFile: __dirname + '/karma.conf.js', singleRun: false}); server.start(); }); var handleError = function(err) { console.log(err.toString()); this.emit('end'); }; gulp.task('release:bump', function() { var type = process.argv[3] ? process.argv[3].substr(2) : 'patch'; return gulp.src(['./package.json']) .pipe(bump({type: type})) .pipe(gulp.dest('./')) .on('end', function() { versionAfterBump = require('./package.json').version; }); }); gulp.task('release:rebuild', function(cb) { runSequence('release:bump', 'build', cb); // bump will here be executed before build }); gulp.task('release:commit', ['release:rebuild'], function() { return gulp.src(['./package.json', 'dist/**/*']) .pipe(git.add()) .pipe(git.commit(versionAfterBump)); }); gulp.task('release:tag', ['release:commit'], function() { git.tag(versionAfterBump, versionAfterBump); }); gulp.task('release', ['release:tag']);
var moment = require("../../moment"); /************************************************** Serbian-latin (sr) *************************************************/ exports["locale:sr"] = { setUp : function (cb) { moment.locale('sr'); moment.createFromInputFallback = function () { throw new Error("input not handled by moment"); }; cb(); }, tearDown : function (cb) { moment.locale('en'); cb(); }, "parse" : function (test) { var tests = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split("_"), i; function equalTest(input, mmm, i) { test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } test.done(); }, "format" : function (test) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'nedelja, 14. februar 2010, 3:25:50 pm'], ['ddd, hA', 'ned., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedelja ned. ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['L', '14. 02. 2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 15:25'], ['LLLL', 'nedelja, 14. februar 2010 15:25'], ['l', '14. 2. 2010'], ['ll', '14. feb. 2010'], ['lll', '14. feb. 2010 15:25'], ['llll', 'ned., 14. feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } test.done(); }, "format ordinal" : function (test) { test.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); test.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); test.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); test.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); test.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); test.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); test.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); test.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); test.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); test.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); test.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); test.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); test.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); test.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); test.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); test.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); test.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); test.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); test.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); test.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); test.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); test.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); test.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); test.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); test.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); test.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); test.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); test.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); test.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); test.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); test.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); test.done(); }, "format month" : function (test) { var expected = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split("_"), i; for (i = 0; i < expected.length; i++) { test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } test.done(); }, "format week" : function (test) { var expected = 'nedelja ned. ne_ponedeljak pon. po_utorak uto. ut_sreda sre. sr_četvrtak čet. če_petak pet. pe_subota sub. su'.split("_"), i; for (i = 0; i < expected.length; i++) { test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } test.done(); }, "from" : function (test) { var start = moment([2007, 1, 28]); test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "nekoliko sekundi", "44 seconds = a few seconds"); test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "jedan minut", "45 seconds = a minute"); test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), "jedan minut", "89 seconds = a minute"); test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), "2 minute", "90 seconds = 2 minutes"); test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), "44 minuta", "44 minutes = 44 minutes"); test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), "jedan sat", "45 minutes = an hour"); test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), "jedan sat", "89 minutes = an hour"); test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), "2 sata", "90 minutes = 2 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), "5 sati", "5 hours = 5 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), "21 sati", "21 hours = 21 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), "dan", "22 hours = a day"); test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), "dan", "35 hours = a day"); test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), "2 dana", "36 hours = 2 days"); test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), "dan", "1 day = a day"); test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), "5 dana", "5 days = 5 days"); test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "25 dana", "25 days = 25 days"); test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "mesec", "26 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "mesec", "30 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), "mesec", "43 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "2 meseca", "46 days = 2 months"); test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "2 meseca", "75 days = 2 months"); test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "3 meseca", "76 days = 3 months"); test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "mesec", "1 month = a month"); test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "5 meseci", "5 months = 5 months"); test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "godinu", "345 days = a year"); test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "2 godine", "548 days = 2 years"); test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "godinu", "1 year = a year"); test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5 godina", "5 years = 5 years"); test.done(); }, "suffix" : function (test) { test.equal(moment(30000).from(0), "za nekoliko sekundi", "prefix"); test.equal(moment(0).from(30000), "pre nekoliko sekundi", "prefix"); test.done(); }, "now from now" : function (test) { test.equal(moment().fromNow(), "pre nekoliko sekundi", "now from now should display as in the past"); test.done(); }, "fromNow" : function (test) { test.equal(moment().add({s: 30}).fromNow(), "za nekoliko sekundi", "in a few seconds"); test.equal(moment().add({d: 5}).fromNow(), "za 5 dana", "in 5 days"); test.done(); }, "calendar day" : function (test) { var a = moment().hours(2).minutes(0).seconds(0); test.equal(moment(a).calendar(), "danas u 2:00", "today at the same time"); test.equal(moment(a).add({m: 25}).calendar(), "danas u 2:25", "Now plus 25 min"); test.equal(moment(a).add({h: 1}).calendar(), "danas u 3:00", "Now plus 1 hour"); test.equal(moment(a).add({d: 1}).calendar(), "sutra u 2:00", "tomorrow at the same time"); test.equal(moment(a).subtract({h: 1}).calendar(), "danas u 1:00", "Now minus 1 hour"); test.equal(moment(a).subtract({d: 1}).calendar(), "juče u 2:00", "yesterday at the same time"); test.done(); }, "calendar next week" : function (test) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: return '[u] [nedelju] [u] LT'; case 3: return '[u] [sredu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } } for (i = 2; i < 7; i++) { m = moment().add({d: i}); test.equal(m.calendar(), m.format(makeFormat(m)), "Today + " + i + " days current time"); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format(makeFormat(m)), "Today + " + i + " days beginning of day"); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format(makeFormat(m)), "Today + " + i + " days end of day"); } test.done(); }, "calendar last week" : function (test) { var i, m; function makeFormat(d) { var lastWeekDay = [ '[prošle] [nedelje] [u] LT', '[prošlog] [ponedeljka] [u] LT', '[prošlog] [utorka] [u] LT', '[prošle] [srede] [u] LT', '[prošlog] [četvrtka] [u] LT', '[prošlog] [petka] [u] LT', '[prošle] [subote] [u] LT' ]; return lastWeekDay[d.day()]; } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); test.equal(m.calendar(), m.format(makeFormat(m)), "Today - " + i + " days current time"); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format(makeFormat(m)), "Today - " + i + " days beginning of day"); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format(makeFormat(m)), "Today - " + i + " days end of day"); } test.done(); }, "calendar all else" : function (test) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago"); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week"); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago"); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks"); test.done(); }, // Monday is the first day of the week. // The week that contains Jan 1st is the first week of the year. "weeks year starting sunday" : function (test) { test.equal(moment([2011, 11, 26]).week(), 1, "Dec 26 2011 should be week 1"); test.equal(moment([2012, 0, 1]).week(), 1, "Jan 1 2012 should be week 1"); test.equal(moment([2012, 0, 2]).week(), 2, "Jan 2 2012 should be week 2"); test.equal(moment([2012, 0, 8]).week(), 2, "Jan 8 2012 should be week 2"); test.equal(moment([2012, 0, 9]).week(), 3, "Jan 9 2012 should be week 3"); test.done(); }, "weeks year starting monday" : function (test) { test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 should be week 1"); test.equal(moment([2007, 0, 7]).week(), 1, "Jan 7 2007 should be week 1"); test.equal(moment([2007, 0, 8]).week(), 2, "Jan 8 2007 should be week 2"); test.equal(moment([2007, 0, 14]).week(), 2, "Jan 14 2007 should be week 2"); test.equal(moment([2007, 0, 15]).week(), 3, "Jan 15 2007 should be week 3"); test.done(); }, "weeks year starting tuesday" : function (test) { test.equal(moment([2007, 11, 31]).week(), 1, "Dec 31 2007 should be week 1"); test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 should be week 1"); test.equal(moment([2008, 0, 6]).week(), 1, "Jan 6 2008 should be week 1"); test.equal(moment([2008, 0, 7]).week(), 2, "Jan 7 2008 should be week 2"); test.equal(moment([2008, 0, 13]).week(), 2, "Jan 13 2008 should be week 2"); test.equal(moment([2008, 0, 14]).week(), 3, "Jan 14 2008 should be week 3"); test.done(); }, "weeks year starting wednesday" : function (test) { test.equal(moment([2002, 11, 30]).week(), 1, "Dec 30 2002 should be week 1"); test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 should be week 1"); test.equal(moment([2003, 0, 5]).week(), 1, "Jan 5 2003 should be week 1"); test.equal(moment([2003, 0, 6]).week(), 2, "Jan 6 2003 should be week 2"); test.equal(moment([2003, 0, 12]).week(), 2, "Jan 12 2003 should be week 2"); test.equal(moment([2003, 0, 13]).week(), 3, "Jan 13 2003 should be week 3"); test.done(); }, "weeks year starting thursday" : function (test) { test.equal(moment([2008, 11, 29]).week(), 1, "Dec 29 2008 should be week 1"); test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 should be week 1"); test.equal(moment([2009, 0, 4]).week(), 1, "Jan 4 2009 should be week 1"); test.equal(moment([2009, 0, 5]).week(), 2, "Jan 5 2009 should be week 2"); test.equal(moment([2009, 0, 11]).week(), 2, "Jan 11 2009 should be week 2"); test.equal(moment([2009, 0, 12]).week(), 3, "Jan 12 2009 should be week 3"); test.done(); }, "weeks year starting friday" : function (test) { test.equal(moment([2009, 11, 28]).week(), 1, "Dec 28 2009 should be week 1"); test.equal(moment([2010, 0, 1]).week(), 1, "Jan 1 2010 should be week 1"); test.equal(moment([2010, 0, 3]).week(), 1, "Jan 3 2010 should be week 1"); test.equal(moment([2010, 0, 4]).week(), 2, "Jan 4 2010 should be week 2"); test.equal(moment([2010, 0, 10]).week(), 2, "Jan 10 2010 should be week 2"); test.equal(moment([2010, 0, 11]).week(), 3, "Jan 11 2010 should be week 3"); test.done(); }, "weeks year starting saturday" : function (test) { test.equal(moment([2010, 11, 27]).week(), 1, "Dec 27 2010 should be week 1"); test.equal(moment([2011, 0, 1]).week(), 1, "Jan 1 2011 should be week 1"); test.equal(moment([2011, 0, 2]).week(), 1, "Jan 2 2011 should be week 1"); test.equal(moment([2011, 0, 3]).week(), 2, "Jan 3 2011 should be week 2"); test.equal(moment([2011, 0, 9]).week(), 2, "Jan 9 2011 should be week 2"); test.equal(moment([2011, 0, 10]).week(), 3, "Jan 10 2011 should be week 3"); test.done(); }, "weeks year starting sunday formatted" : function (test) { test.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', "Dec 26 2011 should be week 1"); test.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', "Jan 1 2012 should be week 1"); test.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', "Jan 2 2012 should be week 2"); test.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', "Jan 8 2012 should be week 2"); test.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', "Jan 9 2012 should be week 3"); test.done(); } };
/* * URI가 주어진 포맷에 맞는지 확인하는 URI_MATCHER 클래스 * * 포맷에 파라미터 구간을 지정할 수 있어 URI로부터 파라미터 값을 가져올 수 있습니다. */ global.URI_MATCHER = CLASS({ init : (inner, self, format) => { //REQUIRED: format let Check = CLASS({ init : (inner, self, uri) => { //REQUIRED: uri let uriParts = uri.split('/'); let isMatched; let uriParams = {}; let find = (format) => { let formatParts = format.split('/'); return EACH(uriParts, (uriPart, i) => { let formatPart = formatParts[i]; if (formatPart === '**') { isMatched = true; return false; } if (formatPart === undefined) { return false; } // find params. if (uriPart !== '' && formatPart.charAt(0) === '{' && formatPart.charAt(formatPart.length - 1) === '}') { uriParams[formatPart.substring(1, formatPart.length - 1)] = uriPart; } else if (formatPart !== '*' && formatPart !== uriPart) { return false; } if (i === uriParts.length - 1 && i < formatParts.length - 1 && formatParts[formatParts.length - 1] !== '') { return false; } }) === true || isMatched === true; }; if (CHECK_IS_ARRAY(format) === true) { isMatched = EACH(format, (format) => { return find(format) !== true; }) !== true; } else { isMatched = find(format); } let checkIsMatched = self.checkIsMatched = () => { return isMatched; }; let getURIParams = self.getURIParams = () => { return uriParams; }; } }); let check = self.check = (uri) => { return Check(uri); }; } });
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
var mongodb = require('./mongodb'); var Schema = mongodb.mongoose.Schema; var contentSchema = new Schema({ city: String, //发帖所在的城市 title: String, //帖子标题 uptime: String, //发帖时间 text: String, //帖子正文 url: String, //帖子地址 keys: Array, //关键词数组 price: Array, //价格关键词数组 room_num: Array, //房间数量数组(一居) room_size: Array, //房间大小(主卧,整租,次卧) rent_way: Array, //租赁方式(求租,合租) date: String //发帖日期(比如2014-09-08) }); module.exports = mongodb.mongoose.model("content", contentSchema);
/*! * Ext JS Library 3.1.1 * Copyright(c) 2006-2010 Ext JS, LLC * licensing@extjs.com * http://www.extjs.com/license */ /** * @class Ext.grid.PropertyRecord * A specific {@link Ext.data.Record} type that represents a name/value pair and is made to work with the * {@link Ext.grid.PropertyGrid}. Typically, PropertyRecords do not need to be created directly as they can be * created implicitly by simply using the appropriate data configs either via the {@link Ext.grid.PropertyGrid#source} * config property or by calling {@link Ext.grid.PropertyGrid#setSource}. However, if the need arises, these records * can also be created explicitly as shwon below. Example usage: * <pre><code> var rec = new Ext.grid.PropertyRecord({ name: 'Birthday', value: new Date(Date.parse('05/26/1972')) }); // Add record to an already populated grid grid.store.addSorted(rec); </code></pre> * @constructor * @param {Object} config A data object in the format: {name: [name], value: [value]}. The specified value's type * will be read automatically by the grid to determine the type of editor to use when displaying it. */ Ext.grid.PropertyRecord = Ext.data.Record.create([ {name:'name',type:'string'}, 'value' ]); /** * @class Ext.grid.PropertyStore * @extends Ext.util.Observable * A custom wrapper for the {@link Ext.grid.PropertyGrid}'s {@link Ext.data.Store}. This class handles the mapping * between the custom data source objects supported by the grid and the {@link Ext.grid.PropertyRecord} format * required for compatibility with the underlying store. Generally this class should not need to be used directly -- * the grid's data should be accessed from the underlying store via the {@link #store} property. * @constructor * @param {Ext.grid.Grid} grid The grid this store will be bound to * @param {Object} source The source data config object */ Ext.grid.PropertyStore = Ext.extend(Ext.util.Observable, { constructor : function(grid, source){ this.grid = grid; this.store = new Ext.data.Store({ recordType : Ext.grid.PropertyRecord }); this.store.on('update', this.onUpdate, this); if(source){ this.setSource(source); } Ext.grid.PropertyStore.superclass.constructor.call(this); }, // protected - should only be called by the grid. Use grid.setSource instead. setSource : function(o){ this.source = o; this.store.removeAll(); var data = []; for(var k in o){ if(this.isEditableValue(o[k])){ data.push(new Ext.grid.PropertyRecord({name: k, value: o[k]}, k)); } } this.store.loadRecords({records: data}, {}, true); }, // private onUpdate : function(ds, record, type){ if(type == Ext.data.Record.EDIT){ var v = record.data.value; var oldValue = record.modified.value; if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){ this.source[record.id] = v; record.commit(); this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue); }else{ record.reject(); } } }, // private getProperty : function(row){ return this.store.getAt(row); }, // private isEditableValue: function(val){ return Ext.isPrimitive(val) || Ext.isDate(val); }, // private setValue : function(prop, value, create){ var r = this.getRec(prop); if(r){ r.set('value', value); this.source[prop] = value; }else if(create){ // only create if specified. this.source[prop] = value; r = new Ext.grid.PropertyRecord({name: prop, value: value}, prop); this.store.add(r); } }, // private remove : function(prop){ var r = this.getRec(prop); if(r){ this.store.remove(r); delete this.source[prop]; } }, // private getRec : function(prop){ return this.store.getById(prop); }, // protected - should only be called by the grid. Use grid.getSource instead. getSource : function(){ return this.source; } }); /** * @class Ext.grid.PropertyColumnModel * @extends Ext.grid.ColumnModel * A custom column model for the {@link Ext.grid.PropertyGrid}. Generally it should not need to be used directly. * @constructor * @param {Ext.grid.Grid} grid The grid this store will be bound to * @param {Object} source The source data config object */ Ext.grid.PropertyColumnModel = Ext.extend(Ext.grid.ColumnModel, { // private - strings used for locale support nameText : 'Name', valueText : 'Value', dateFormat : 'm/j/Y', trueText: 'true', falseText: 'false', constructor : function(grid, store){ var g = Ext.grid, f = Ext.form; this.grid = grid; g.PropertyColumnModel.superclass.constructor.call(this, [ {header: this.nameText, width:50, sortable: true, dataIndex:'name', id: 'name', menuDisabled:true}, {header: this.valueText, width:50, resizable:false, dataIndex: 'value', id: 'value', menuDisabled:true} ]); this.store = store; var bfield = new f.Field({ autoCreate: {tag: 'select', children: [ {tag: 'option', value: 'true', html: this.trueText}, {tag: 'option', value: 'false', html: this.falseText} ]}, getValue : function(){ return this.el.dom.value == 'true'; } }); this.editors = { 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})), 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})), 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})), 'boolean' : new g.GridEditor(bfield, { autoSize: 'both' }) }; this.renderCellDelegate = this.renderCell.createDelegate(this); this.renderPropDelegate = this.renderProp.createDelegate(this); }, // private renderDate : function(dateVal){ return dateVal.dateFormat(this.dateFormat); }, // private renderBool : function(bVal){ return this[bVal ? 'trueText' : 'falseText']; }, // private isCellEditable : function(colIndex, rowIndex){ return colIndex == 1; }, // private getRenderer : function(col){ return col == 1 ? this.renderCellDelegate : this.renderPropDelegate; }, // private renderProp : function(v){ return this.getPropertyName(v); }, // private renderCell : function(val, meta, rec){ var renderer = this.grid.customRenderers[rec.get('name')]; if(renderer){ return renderer.apply(this, arguments); } var rv = val; if(Ext.isDate(val)){ rv = this.renderDate(val); }else if(typeof val == 'boolean'){ rv = this.renderBool(val); } return Ext.util.Format.htmlEncode(rv); }, // private getPropertyName : function(name){ var pn = this.grid.propertyNames; return pn && pn[name] ? pn[name] : name; }, // private getCellEditor : function(colIndex, rowIndex){ var p = this.store.getProperty(rowIndex), n = p.data.name, val = p.data.value; if(this.grid.customEditors[n]){ return this.grid.customEditors[n]; } if(Ext.isDate(val)){ return this.editors.date; }else if(typeof val == 'number'){ return this.editors.number; }else if(typeof val == 'boolean'){ return this.editors['boolean']; }else{ return this.editors.string; } }, // inherit docs destroy : function(){ Ext.grid.PropertyColumnModel.superclass.destroy.call(this); for(var ed in this.editors){ Ext.destroy(this.editors[ed]); } } }); /** * @class Ext.grid.PropertyGrid * @extends Ext.grid.EditorGridPanel * A specialized grid implementation intended to mimic the traditional property grid as typically seen in * development IDEs. Each row in the grid represents a property of some object, and the data is stored * as a set of name/value pairs in {@link Ext.grid.PropertyRecord}s. Example usage: * <pre><code> var grid = new Ext.grid.PropertyGrid({ title: 'Properties Grid', autoHeight: true, width: 300, renderTo: 'grid-ct', source: { "(name)": "My Object", "Created": new Date(Date.parse('10/15/2006')), "Available": false, "Version": .01, "Description": "A test object" } }); </code></pre> * @constructor * @param {Object} config The grid config object */ Ext.grid.PropertyGrid = Ext.extend(Ext.grid.EditorGridPanel, { /** * @cfg {Object} propertyNames An object containing property name/display name pairs. * If specified, the display name will be shown in the name column instead of the property name. */ /** * @cfg {Object} source A data object to use as the data source of the grid (see {@link #setSource} for details). */ /** * @cfg {Object} customEditors An object containing name/value pairs of custom editor type definitions that allow * the grid to support additional types of editable fields. By default, the grid supports strongly-typed editing * of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and * associated with a custom input control by specifying a custom editor. The name of the editor * type should correspond with the name of the property that will use the editor. Example usage: * <pre><code> var grid = new Ext.grid.PropertyGrid({ ... customEditors: { 'Start Time': new Ext.grid.GridEditor(new Ext.form.TimeField({selectOnFocus:true})) }, source: { 'Start Time': '10:00 AM' } }); </code></pre> */ /** * @cfg {Object} source A data object to use as the data source of the grid (see {@link #setSource} for details). */ /** * @cfg {Object} customRenderers An object containing name/value pairs of custom renderer type definitions that allow * the grid to support custom rendering of fields. By default, the grid supports strongly-typed rendering * of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and * associated with the type of the value. The name of the renderer type should correspond with the name of the property * that it will render. Example usage: * <pre><code> var grid = new Ext.grid.PropertyGrid({ ... customRenderers: { Available: function(v){ if(v){ return '<span style="color: green;">Yes</span>'; }else{ return '<span style="color: red;">No</span>'; } } }, source: { Available: true } }); </code></pre> */ // private config overrides enableColumnMove:false, stripeRows:false, trackMouseOver: false, clicksToEdit:1, enableHdMenu : false, viewConfig : { forceFit:true }, // private initComponent : function(){ this.customRenderers = this.customRenderers || {}; this.customEditors = this.customEditors || {}; this.lastEditRow = null; var store = new Ext.grid.PropertyStore(this); this.propStore = store; var cm = new Ext.grid.PropertyColumnModel(this, store); store.store.sort('name', 'ASC'); this.addEvents( /** * @event beforepropertychange * Fires before a property value changes. Handlers can return false to cancel the property change * (this will internally call {@link Ext.data.Record#reject} on the property's record). * @param {Object} source The source data object for the grid (corresponds to the same object passed in * as the {@link #source} config property). * @param {String} recordId The record's id in the data store * @param {Mixed} value The current edited property value * @param {Mixed} oldValue The original property value prior to editing */ 'beforepropertychange', /** * @event propertychange * Fires after a property value has changed. * @param {Object} source The source data object for the grid (corresponds to the same object passed in * as the {@link #source} config property). * @param {String} recordId The record's id in the data store * @param {Mixed} value The current edited property value * @param {Mixed} oldValue The original property value prior to editing */ 'propertychange' ); this.cm = cm; this.ds = store.store; Ext.grid.PropertyGrid.superclass.initComponent.call(this); this.mon(this.selModel, 'beforecellselect', function(sm, rowIndex, colIndex){ if(colIndex === 0){ this.startEditing.defer(200, this, [rowIndex, 1]); return false; } }, this); }, // private onRender : function(){ Ext.grid.PropertyGrid.superclass.onRender.apply(this, arguments); this.getGridEl().addClass('x-props-grid'); }, // private afterRender: function(){ Ext.grid.PropertyGrid.superclass.afterRender.apply(this, arguments); if(this.source){ this.setSource(this.source); } }, /** * Sets the source data object containing the property data. The data object can contain one or more name/value * pairs representing all of the properties of an object to display in the grid, and this data will automatically * be loaded into the grid's {@link #store}. The values should be supplied in the proper data type if needed, * otherwise string type will be assumed. If the grid already contains data, this method will replace any * existing data. See also the {@link #source} config value. Example usage: * <pre><code> grid.setSource({ "(name)": "My Object", "Created": new Date(Date.parse('10/15/2006')), // date type "Available": false, // boolean type "Version": .01, // decimal type "Description": "A test object" }); </code></pre> * @param {Object} source The data object */ setSource : function(source){ this.propStore.setSource(source); }, /** * Gets the source data object containing the property data. See {@link #setSource} for details regarding the * format of the data object. * @return {Object} The data object */ getSource : function(){ return this.propStore.getSource(); }, /** * Sets the value of a property. * @param {String} prop The name of the property to set * @param {Mixed} value The value to test * @param {Boolean} create (Optional) True to create the property if it doesn't already exist. Defaults to <tt>false</tt>. */ setProperty : function(prop, value, create){ this.propStore.setValue(prop, value, create); }, /** * Removes a property from the grid. * @param {String} prop The name of the property to remove */ removeProperty : function(prop){ this.propStore.remove(prop); } /** * @cfg store * @hide */ /** * @cfg colModel * @hide */ /** * @cfg cm * @hide */ /** * @cfg columns * @hide */ }); Ext.reg("propertygrid", Ext.grid.PropertyGrid);
/** * Copyright 2012-2017, Plotly, Inc. * 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. */ 'use strict'; var d3 = require('d3'); var Color = require('../color'); module.exports = function style(traces) { traces.each(function(d) { var trace = d[0].trace, yObj = trace.error_y || {}, xObj = trace.error_x || {}; var s = d3.select(this); s.selectAll('path.yerror') .style('stroke-width', yObj.thickness + 'px') .call(Color.stroke, yObj.color); if(xObj.copy_ystyle) xObj = yObj; s.selectAll('path.xerror') .style('stroke-width', xObj.thickness + 'px') .call(Color.stroke, xObj.color); }); };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _default = { "syntax-async-generators": require("@babel/plugin-syntax-async-generators"), "syntax-dynamic-import": require("@babel/plugin-syntax-dynamic-import"), "syntax-json-strings": require("@babel/plugin-syntax-json-strings"), "syntax-object-rest-spread": require("@babel/plugin-syntax-object-rest-spread"), "syntax-optional-catch-binding": require("@babel/plugin-syntax-optional-catch-binding"), "transform-async-to-generator": require("@babel/plugin-transform-async-to-generator"), "proposal-async-generator-functions": require("@babel/plugin-proposal-async-generator-functions"), "proposal-dynamic-import": require("@babel/plugin-proposal-dynamic-import"), "proposal-json-strings": require("@babel/plugin-proposal-json-strings"), "transform-arrow-functions": require("@babel/plugin-transform-arrow-functions"), "transform-block-scoped-functions": require("@babel/plugin-transform-block-scoped-functions"), "transform-block-scoping": require("@babel/plugin-transform-block-scoping"), "transform-classes": require("@babel/plugin-transform-classes"), "transform-computed-properties": require("@babel/plugin-transform-computed-properties"), "transform-destructuring": require("@babel/plugin-transform-destructuring"), "transform-dotall-regex": require("@babel/plugin-transform-dotall-regex"), "transform-duplicate-keys": require("@babel/plugin-transform-duplicate-keys"), "transform-for-of": require("@babel/plugin-transform-for-of"), "transform-function-name": require("@babel/plugin-transform-function-name"), "transform-literals": require("@babel/plugin-transform-literals"), "transform-member-expression-literals": require("@babel/plugin-transform-member-expression-literals"), "transform-modules-amd": require("@babel/plugin-transform-modules-amd"), "transform-modules-commonjs": require("@babel/plugin-transform-modules-commonjs"), "transform-modules-systemjs": require("@babel/plugin-transform-modules-systemjs"), "transform-modules-umd": require("@babel/plugin-transform-modules-umd"), "transform-named-capturing-groups-regex": require("@babel/plugin-transform-named-capturing-groups-regex"), "transform-object-super": require("@babel/plugin-transform-object-super"), "transform-parameters": require("@babel/plugin-transform-parameters"), "transform-property-literals": require("@babel/plugin-transform-property-literals"), "transform-reserved-words": require("@babel/plugin-transform-reserved-words"), "transform-shorthand-properties": require("@babel/plugin-transform-shorthand-properties"), "transform-spread": require("@babel/plugin-transform-spread"), "transform-sticky-regex": require("@babel/plugin-transform-sticky-regex"), "transform-template-literals": require("@babel/plugin-transform-template-literals"), "transform-typeof-symbol": require("@babel/plugin-transform-typeof-symbol"), "transform-unicode-regex": require("@babel/plugin-transform-unicode-regex"), "transform-exponentiation-operator": require("@babel/plugin-transform-exponentiation-operator"), "transform-new-target": require("@babel/plugin-transform-new-target"), "proposal-object-rest-spread": require("@babel/plugin-proposal-object-rest-spread"), "proposal-optional-catch-binding": require("@babel/plugin-proposal-optional-catch-binding"), "transform-regenerator": require("@babel/plugin-transform-regenerator"), "proposal-unicode-property-regex": require("@babel/plugin-proposal-unicode-property-regex") }; exports.default = _default;
/** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ */ THREE.WebGLRenderer = function ( parameters ) { console.log( 'THREE.WebGLRenderer', THREE.REVISION ); parameters = parameters || {}; var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ), _precision = parameters.precision !== undefined ? parameters.precision : 'highp', _alpha = parameters.alpha !== undefined ? parameters.alpha : true, _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, _antialias = parameters.antialias !== undefined ? parameters.antialias : false, _stencil = parameters.stencil !== undefined ? parameters.stencil : true, _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ), _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0, _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4; // public properties this.domElement = _canvas; this.context = null; // clearing this.autoClear = true; this.autoClearColor = true; this.autoClearDepth = true; this.autoClearStencil = true; // scene graph this.sortObjects = true; this.autoUpdateObjects = true; this.autoUpdateScene = true; // physically based shading this.gammaInput = false; this.gammaOutput = false; this.physicallyBasedShading = false; // shadow map this.shadowMapEnabled = false; this.shadowMapAutoUpdate = true; this.shadowMapSoft = true; this.shadowMapCullFrontFaces = true; this.shadowMapDebug = false; this.shadowMapCascade = false; // morphs this.maxMorphTargets = 8; this.maxMorphNormals = 4; // flags this.autoScaleCubemaps = true; // custom render plugins this.renderPluginsPre = []; this.renderPluginsPost = []; // info this.info = { memory: { programs: 0, geometries: 0, textures: 0 }, render: { calls: 0, vertices: 0, faces: 0, points: 0 } }; // internal properties var _this = this, _gl, _programs = [], // internal state cache _currentProgram = null, _currentFramebuffer = null, _currentMaterialId = -1, _currentGeometryGroupHash = null, _currentCamera = null, _geometryGroupCounter = 0, // GL state cache _oldDoubleSided = -1, _oldFlipSided = -1, _oldBlending = -1, _oldBlendEquation = -1, _oldBlendSrc = -1, _oldBlendDst = -1, _oldDepthTest = -1, _oldDepthWrite = -1, _oldPolygonOffset = null, _oldPolygonOffsetFactor = null, _oldPolygonOffsetUnits = null, _oldLineWidth = null, _viewportX = 0, _viewportY = 0, _viewportWidth = 0, _viewportHeight = 0, _currentWidth = 0, _currentHeight = 0, // frustum _frustum = new THREE.Frustum(), // camera matrices cache _projScreenMatrix = new THREE.Matrix4(), _projScreenMatrixPS = new THREE.Matrix4(), _vector3 = new THREE.Vector4(), // light arrays cache _direction = new THREE.Vector3(), _lightsNeedUpdate = true, _lights = { ambient: [ 0, 0, 0 ], directional: { length: 0, colors: new Array(), positions: new Array() }, point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }, spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() } }; // initialize _gl = initGL(); setDefaultGLState(); this.context = _gl; // GPU capabilities var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ), _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ), _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); // API this.getContext = function () { return _gl; }; this.supportsVertexTextures = function () { return _maxVertexTextures > 0; }; this.setSize = function ( width, height ) { _canvas.width = width; _canvas.height = height; this.setViewport( 0, 0, _canvas.width, _canvas.height ); }; this.setViewport = function ( x, y, width, height ) { _viewportX = x; _viewportY = y; _viewportWidth = width; _viewportHeight = height; _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); }; this.setScissor = function ( x, y, width, height ) { _gl.scissor( x, y, width, height ); }; this.enableScissorTest = function ( enable ) { enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST ); }; // Clearing this.setClearColorHex = function ( hex, alpha ) { _clearColor.setHex( hex ); _clearAlpha = alpha; _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); }; this.setClearColor = function ( color, alpha ) { _clearColor.copy( color ); _clearAlpha = alpha; _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); }; this.getClearColor = function () { return _clearColor; }; this.getClearAlpha = function () { return _clearAlpha; }; this.clear = function ( color, depth, stencil ) { var bits = 0; if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; _gl.clear( bits ); }; this.clearTarget = function ( renderTarget, color, depth, stencil ) { this.setRenderTarget( renderTarget ); this.clear( color, depth, stencil ); }; // Plugins this.addPostPlugin = function ( plugin ) { plugin.init( this ); this.renderPluginsPost.push( plugin ); }; this.addPrePlugin = function ( plugin ) { plugin.init( this ); this.renderPluginsPre.push( plugin ); }; // Deallocation this.deallocateObject = function ( object ) { if ( ! object.__webglInit ) return; object.__webglInit = false; delete object._modelViewMatrix; delete object._normalMatrix; delete object._normalMatrixArray; delete object._modelViewMatrixArray; delete object._objectMatrixArray; if ( object instanceof THREE.Mesh ) { for ( var g in object.geometry.geometryGroups ) { deleteMeshBuffers( object.geometry.geometryGroups[ g ] ); } } else if ( object instanceof THREE.Ribbon ) { deleteRibbonBuffers( object.geometry ); } else if ( object instanceof THREE.Line ) { deleteLineBuffers( object.geometry ); } else if ( object instanceof THREE.ParticleSystem ) { deleteParticleBuffers( object.geometry ); } }; this.deallocateTexture = function ( texture ) { if ( ! texture.__webglInit ) return; texture.__webglInit = false; _gl.deleteTexture( texture.__webglTexture ); _this.info.memory.textures --; }; this.deallocateRenderTarget = function ( renderTarget ) { if ( !renderTarget || ! renderTarget.__webglTexture ) return; _gl.deleteTexture( renderTarget.__webglTexture ); if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { for ( var i = 0; i < 6; i ++ ) { _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] ); _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] ); } } else { _gl.deleteFramebuffer( renderTarget.__webglFramebuffer ); _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer ); } }; // Rendering this.updateShadowMap = function ( scene, camera ) { _currentProgram = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; _oldDoubleSided = -1; _oldFlipSided = -1; this.shadowMapPlugin.update( scene, camera ); }; // Internal functions // Buffer allocation function createParticleBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); _this.info.geometries ++; }; function createLineBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); _this.info.memory.geometries ++; }; function createRibbonBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); _this.info.memory.geometries ++; }; function createMeshBuffers ( geometryGroup ) { geometryGroup.__webglVertexBuffer = _gl.createBuffer(); geometryGroup.__webglNormalBuffer = _gl.createBuffer(); geometryGroup.__webglTangentBuffer = _gl.createBuffer(); geometryGroup.__webglColorBuffer = _gl.createBuffer(); geometryGroup.__webglUVBuffer = _gl.createBuffer(); geometryGroup.__webglUV2Buffer = _gl.createBuffer(); geometryGroup.__webglSkinVertexABuffer = _gl.createBuffer(); geometryGroup.__webglSkinVertexBBuffer = _gl.createBuffer(); geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); geometryGroup.__webglFaceBuffer = _gl.createBuffer(); geometryGroup.__webglLineBuffer = _gl.createBuffer(); var m, ml; if ( geometryGroup.numMorphTargets ) { geometryGroup.__webglMorphTargetsBuffers = []; for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() ); } } if ( geometryGroup.numMorphNormals ) { geometryGroup.__webglMorphNormalsBuffers = []; for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() ); } } _this.info.memory.geometries ++; }; // Buffer deallocation function deleteParticleBuffers ( geometry ) { _gl.deleteBuffer( geometry.__webglVertexBuffer ); _gl.deleteBuffer( geometry.__webglColorBuffer ); _this.info.memory.geometries --; }; function deleteLineBuffers ( geometry ) { _gl.deleteBuffer( geometry.__webglVertexBuffer ); _gl.deleteBuffer( geometry.__webglColorBuffer ); _this.info.memory.geometries --; }; function deleteRibbonBuffers ( geometry ) { _gl.deleteBuffer( geometry.__webglVertexBuffer ); _gl.deleteBuffer( geometry.__webglColorBuffer ); _this.info.memory.geometries --; }; function deleteMeshBuffers ( geometryGroup ) { _gl.deleteBuffer( geometryGroup.__webglVertexBuffer ); _gl.deleteBuffer( geometryGroup.__webglNormalBuffer ); _gl.deleteBuffer( geometryGroup.__webglTangentBuffer ); _gl.deleteBuffer( geometryGroup.__webglColorBuffer ); _gl.deleteBuffer( geometryGroup.__webglUVBuffer ); _gl.deleteBuffer( geometryGroup.__webglUV2Buffer ); _gl.deleteBuffer( geometryGroup.__webglSkinVertexABuffer ); _gl.deleteBuffer( geometryGroup.__webglSkinVertexBBuffer ); _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer ); _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer ); _gl.deleteBuffer( geometryGroup.__webglFaceBuffer ); _gl.deleteBuffer( geometryGroup.__webglLineBuffer ); var m, ml; if ( geometryGroup.numMorphTargets ) { for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] ); } } if ( geometryGroup.numMorphNormals ) { for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] ); } } if ( geometryGroup.__webglCustomAttributesList ) { for ( var id in geometryGroup.__webglCustomAttributesList ) { _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer ); } } _this.info.memory.geometries --; }; // Buffer initialization function initCustomAttributes ( geometry, object ) { var nvertices = geometry.vertices.length; var material = object.material; if ( material.attributes ) { if ( geometry.__webglCustomAttributesList === undefined ) { geometry.__webglCustomAttributesList = []; } for ( var a in material.attributes ) { var attribute = material.attributes[ a ]; if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { attribute.__webglInitialized = true; var size = 1; // "f" and "i" if ( attribute.type === "v2" ) size = 2; else if ( attribute.type === "v3" ) size = 3; else if ( attribute.type === "v4" ) size = 4; else if ( attribute.type === "c" ) size = 3; attribute.size = size; attribute.array = new Float32Array( nvertices * size ); attribute.buffer = _gl.createBuffer(); attribute.buffer.belongsToAttribute = a; attribute.needsUpdate = true; } geometry.__webglCustomAttributesList.push( attribute ); } } }; function initParticleBuffers ( geometry, object ) { var nvertices = geometry.vertices.length; geometry.__vertexArray = new Float32Array( nvertices * 3 ); geometry.__colorArray = new Float32Array( nvertices * 3 ); geometry.__sortArray = []; geometry.__webglParticleCount = nvertices; initCustomAttributes ( geometry, object ); }; function initLineBuffers ( geometry, object ) { var nvertices = geometry.vertices.length; geometry.__vertexArray = new Float32Array( nvertices * 3 ); geometry.__colorArray = new Float32Array( nvertices * 3 ); geometry.__webglLineCount = nvertices; initCustomAttributes ( geometry, object ); }; function initRibbonBuffers ( geometry ) { var nvertices = geometry.vertices.length; geometry.__vertexArray = new Float32Array( nvertices * 3 ); geometry.__colorArray = new Float32Array( nvertices * 3 ); geometry.__webglVertexCount = nvertices; }; function initMeshBuffers ( geometryGroup, object ) { var geometry = object.geometry, faces3 = geometryGroup.faces3, faces4 = geometryGroup.faces4, nvertices = faces3.length * 3 + faces4.length * 4, ntris = faces3.length * 1 + faces4.length * 2, nlines = faces3.length * 3 + faces4.length * 4, material = getBufferMaterial( object, geometryGroup ), uvType = bufferGuessUVType( material ), normalType = bufferGuessNormalType( material ), vertexColorType = bufferGuessVertexColorType( material ); //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material ); geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); if ( normalType ) { geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); } if ( geometry.hasTangents ) { geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); } if ( vertexColorType ) { geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); } if ( uvType ) { if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) { geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); } if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) { geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); } } if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { geometryGroup.__skinVertexAArray = new Float32Array( nvertices * 4 ); geometryGroup.__skinVertexBArray = new Float32Array( nvertices * 4 ); geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); } geometryGroup.__faceArray = new Uint16Array( ntris * 3 ); geometryGroup.__lineArray = new Uint16Array( nlines * 2 ); var m, ml; if ( geometryGroup.numMorphTargets ) { geometryGroup.__morphTargetsArrays = []; for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) ); } } if ( geometryGroup.numMorphNormals ) { geometryGroup.__morphNormalsArrays = []; for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) ); } } geometryGroup.__webglFaceCount = ntris * 3; geometryGroup.__webglLineCount = nlines * 2; // custom attributes if ( material.attributes ) { if ( geometryGroup.__webglCustomAttributesList === undefined ) { geometryGroup.__webglCustomAttributesList = []; } for ( var a in material.attributes ) { // Do a shallow copy of the attribute object so different geometryGroup chunks use different // attribute buffers which are correctly indexed in the setMeshBuffers function var originalAttribute = material.attributes[ a ]; var attribute = {}; for ( var property in originalAttribute ) { attribute[ property ] = originalAttribute[ property ]; } if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { attribute.__webglInitialized = true; var size = 1; // "f" and "i" if( attribute.type === "v2" ) size = 2; else if( attribute.type === "v3" ) size = 3; else if( attribute.type === "v4" ) size = 4; else if( attribute.type === "c" ) size = 3; attribute.size = size; attribute.array = new Float32Array( nvertices * size ); attribute.buffer = _gl.createBuffer(); attribute.buffer.belongsToAttribute = a; originalAttribute.needsUpdate = true; attribute.__original = originalAttribute; } geometryGroup.__webglCustomAttributesList.push( attribute ); } } geometryGroup.__inittedArrays = true; }; function getBufferMaterial( object, geometryGroup ) { if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) { return object.material; } else if ( geometryGroup.materialIndex >= 0 ) { return object.geometry.materials[ geometryGroup.materialIndex ]; } }; function materialNeedsSmoothNormals ( material ) { return material && material.shading !== undefined && material.shading === THREE.SmoothShading; }; function bufferGuessNormalType ( material ) { // only MeshBasicMaterial and MeshDepthMaterial don't need normals if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) { return false; } if ( materialNeedsSmoothNormals( material ) ) { return THREE.SmoothShading; } else { return THREE.FlatShading; } }; function bufferGuessVertexColorType ( material ) { if ( material.vertexColors ) { return material.vertexColors; } return false; }; function bufferGuessUVType ( material ) { // material must use some texture to require uvs if ( material.map || material.lightMap || material instanceof THREE.ShaderMaterial ) { return true; } return false; }; // Buffer setting function setParticleBuffers ( geometry, hint, object ) { var v, c, vertex, offset, index, color, vertices = geometry.vertices, vl = vertices.length, colors = geometry.colors, cl = colors.length, vertexArray = geometry.__vertexArray, colorArray = geometry.__colorArray, sortArray = geometry.__sortArray, dirtyVertices = geometry.verticesNeedUpdate, dirtyElements = geometry.elementsNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, customAttributes = geometry.__webglCustomAttributesList, i, il, a, ca, cal, value, customAttribute; if ( object.sortParticles ) { _projScreenMatrixPS.copy( _projScreenMatrix ); _projScreenMatrixPS.multiplySelf( object.matrixWorld ); for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; _vector3.copy( vertex ); _projScreenMatrixPS.multiplyVector3( _vector3 ); sortArray[ v ] = [ _vector3.z, v ]; } sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } ); for ( v = 0; v < vl; v ++ ) { vertex = vertices[ sortArray[v][1] ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } for ( c = 0; c < cl; c ++ ) { offset = c * 3; color = colors[ sortArray[c][1] ]; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue; offset = 0; cal = customAttribute.value.length; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; customAttribute.array[ ca ] = customAttribute.value[ index ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } } } } else { if ( dirtyVertices ) { for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } } if ( dirtyColors ) { for ( c = 0; c < cl; c ++ ) { color = colors[ c ]; offset = c * 3; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices") ) { cal = customAttribute.value.length; offset = 0; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { customAttribute.array[ ca ] = customAttribute.value[ ca ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } } } } } if ( dirtyVertices || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyColors || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } } }; function setLineBuffers ( geometry, hint ) { var v, c, vertex, offset, color, vertices = geometry.vertices, colors = geometry.colors, vl = vertices.length, cl = colors.length, vertexArray = geometry.__vertexArray, colorArray = geometry.__colorArray, dirtyVertices = geometry.verticesNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, customAttributes = geometry.__webglCustomAttributesList, i, il, a, ca, cal, value, customAttribute; if ( dirtyVertices ) { for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyColors ) { for ( c = 0; c < cl; c ++ ) { color = colors[ c ]; offset = c * 3; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) { offset = 0; cal = customAttribute.value.length; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { customAttribute.array[ ca ] = customAttribute.value[ ca ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } } }; function setRibbonBuffers ( geometry, hint ) { var v, c, vertex, offset, color, vertices = geometry.vertices, colors = geometry.colors, vl = vertices.length, cl = colors.length, vertexArray = geometry.__vertexArray, colorArray = geometry.__colorArray, dirtyVertices = geometry.verticesNeedUpdate, dirtyColors = geometry.colorsNeedUpdate; if ( dirtyVertices ) { for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyColors ) { for ( c = 0; c < cl; c ++ ) { color = colors[ c ]; offset = c * 3; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } }; function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { if ( ! geometryGroup.__inittedArrays ) { // console.log( object ); return; } var normalType = bufferGuessNormalType( material ), vertexColorType = bufferGuessVertexColorType( material ), uvType = bufferGuessUVType( material ), needsSmoothNormals = ( normalType === THREE.SmoothShading ); var f, fl, fi, face, vertexNormals, faceNormal, normal, vertexColors, faceColor, vertexTangents, uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4, c1, c2, c3, c4, sw1, sw2, sw3, sw4, si1, si2, si3, si4, sa1, sa2, sa3, sa4, sb1, sb2, sb3, sb4, m, ml, i, il, vn, uvi, uv2i, vk, vkl, vka, nka, chf, faceVertexNormals, a, vertexIndex = 0, offset = 0, offset_uv = 0, offset_uv2 = 0, offset_face = 0, offset_normal = 0, offset_tangent = 0, offset_line = 0, offset_color = 0, offset_skin = 0, offset_morphTarget = 0, offset_custom = 0, offset_customSrc = 0, value, vertexArray = geometryGroup.__vertexArray, uvArray = geometryGroup.__uvArray, uv2Array = geometryGroup.__uv2Array, normalArray = geometryGroup.__normalArray, tangentArray = geometryGroup.__tangentArray, colorArray = geometryGroup.__colorArray, skinVertexAArray = geometryGroup.__skinVertexAArray, skinVertexBArray = geometryGroup.__skinVertexBArray, skinIndexArray = geometryGroup.__skinIndexArray, skinWeightArray = geometryGroup.__skinWeightArray, morphTargetsArrays = geometryGroup.__morphTargetsArrays, morphNormalsArrays = geometryGroup.__morphNormalsArrays, customAttributes = geometryGroup.__webglCustomAttributesList, customAttribute, faceArray = geometryGroup.__faceArray, lineArray = geometryGroup.__lineArray, geometry = object.geometry, // this is shared for all chunks dirtyVertices = geometry.verticesNeedUpdate, dirtyElements = geometry.elementsNeedUpdate, dirtyUvs = geometry.uvsNeedUpdate, dirtyNormals = geometry.normalsNeedUpdate, dirtyTangents = geometry.tangetsNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, dirtyMorphTargets = geometry.morphTargetsNeedUpdate, vertices = geometry.vertices, chunk_faces3 = geometryGroup.faces3, chunk_faces4 = geometryGroup.faces4, obj_faces = geometry.faces, obj_uvs = geometry.faceVertexUvs[ 0 ], obj_uvs2 = geometry.faceVertexUvs[ 1 ], obj_colors = geometry.colors, obj_skinVerticesA = geometry.skinVerticesA, obj_skinVerticesB = geometry.skinVerticesB, obj_skinIndices = geometry.skinIndices, obj_skinWeights = geometry.skinWeights, morphTargets = geometry.morphTargets, morphNormals = geometry.morphNormals; if ( dirtyVertices ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = vertices[ face.a ]; v2 = vertices[ face.b ]; v3 = vertices[ face.c ]; vertexArray[ offset ] = v1.x; vertexArray[ offset + 1 ] = v1.y; vertexArray[ offset + 2 ] = v1.z; vertexArray[ offset + 3 ] = v2.x; vertexArray[ offset + 4 ] = v2.y; vertexArray[ offset + 5 ] = v2.z; vertexArray[ offset + 6 ] = v3.x; vertexArray[ offset + 7 ] = v3.y; vertexArray[ offset + 8 ] = v3.z; offset += 9; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; v1 = vertices[ face.a ]; v2 = vertices[ face.b ]; v3 = vertices[ face.c ]; v4 = vertices[ face.d ]; vertexArray[ offset ] = v1.x; vertexArray[ offset + 1 ] = v1.y; vertexArray[ offset + 2 ] = v1.z; vertexArray[ offset + 3 ] = v2.x; vertexArray[ offset + 4 ] = v2.y; vertexArray[ offset + 5 ] = v2.z; vertexArray[ offset + 6 ] = v3.x; vertexArray[ offset + 7 ] = v3.y; vertexArray[ offset + 8 ] = v3.z; vertexArray[ offset + 9 ] = v4.x; vertexArray[ offset + 10 ] = v4.y; vertexArray[ offset + 11 ] = v4.z; offset += 12; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyMorphTargets ) { for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { offset_morphTarget = 0; for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { chf = chunk_faces3[ f ]; face = obj_faces[ chf ]; // morph positions v1 = morphTargets[ vk ].vertices[ face.a ]; v2 = morphTargets[ vk ].vertices[ face.b ]; v3 = morphTargets[ vk ].vertices[ face.c ]; vka = morphTargetsArrays[ vk ]; vka[ offset_morphTarget ] = v1.x; vka[ offset_morphTarget + 1 ] = v1.y; vka[ offset_morphTarget + 2 ] = v1.z; vka[ offset_morphTarget + 3 ] = v2.x; vka[ offset_morphTarget + 4 ] = v2.y; vka[ offset_morphTarget + 5 ] = v2.z; vka[ offset_morphTarget + 6 ] = v3.x; vka[ offset_morphTarget + 7 ] = v3.y; vka[ offset_morphTarget + 8 ] = v3.z; // morph normals if ( material.morphNormals ) { if ( needsSmoothNormals ) { faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; n1 = faceVertexNormals.a; n2 = faceVertexNormals.b; n3 = faceVertexNormals.c; } else { n1 = morphNormals[ vk ].faceNormals[ chf ]; n2 = n1; n3 = n1; } nka = morphNormalsArrays[ vk ]; nka[ offset_morphTarget ] = n1.x; nka[ offset_morphTarget + 1 ] = n1.y; nka[ offset_morphTarget + 2 ] = n1.z; nka[ offset_morphTarget + 3 ] = n2.x; nka[ offset_morphTarget + 4 ] = n2.y; nka[ offset_morphTarget + 5 ] = n2.z; nka[ offset_morphTarget + 6 ] = n3.x; nka[ offset_morphTarget + 7 ] = n3.y; nka[ offset_morphTarget + 8 ] = n3.z; } // offset_morphTarget += 9; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { chf = chunk_faces4[ f ]; face = obj_faces[ chf ]; // morph positions v1 = morphTargets[ vk ].vertices[ face.a ]; v2 = morphTargets[ vk ].vertices[ face.b ]; v3 = morphTargets[ vk ].vertices[ face.c ]; v4 = morphTargets[ vk ].vertices[ face.d ]; vka = morphTargetsArrays[ vk ]; vka[ offset_morphTarget ] = v1.x; vka[ offset_morphTarget + 1 ] = v1.y; vka[ offset_morphTarget + 2 ] = v1.z; vka[ offset_morphTarget + 3 ] = v2.x; vka[ offset_morphTarget + 4 ] = v2.y; vka[ offset_morphTarget + 5 ] = v2.z; vka[ offset_morphTarget + 6 ] = v3.x; vka[ offset_morphTarget + 7 ] = v3.y; vka[ offset_morphTarget + 8 ] = v3.z; vka[ offset_morphTarget + 9 ] = v4.x; vka[ offset_morphTarget + 10 ] = v4.y; vka[ offset_morphTarget + 11 ] = v4.z; // morph normals if ( material.morphNormals ) { if ( needsSmoothNormals ) { faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; n1 = faceVertexNormals.a; n2 = faceVertexNormals.b; n3 = faceVertexNormals.c; n4 = faceVertexNormals.d; } else { n1 = morphNormals[ vk ].faceNormals[ chf ]; n2 = n1; n3 = n1; n4 = n1; } nka = morphNormalsArrays[ vk ]; nka[ offset_morphTarget ] = n1.x; nka[ offset_morphTarget + 1 ] = n1.y; nka[ offset_morphTarget + 2 ] = n1.z; nka[ offset_morphTarget + 3 ] = n2.x; nka[ offset_morphTarget + 4 ] = n2.y; nka[ offset_morphTarget + 5 ] = n2.z; nka[ offset_morphTarget + 6 ] = n3.x; nka[ offset_morphTarget + 7 ] = n3.y; nka[ offset_morphTarget + 8 ] = n3.z; nka[ offset_morphTarget + 9 ] = n4.x; nka[ offset_morphTarget + 10 ] = n4.y; nka[ offset_morphTarget + 11 ] = n4.z; } // offset_morphTarget += 12; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); if ( material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); } } } if ( obj_skinWeights.length ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; // weights sw1 = obj_skinWeights[ face.a ]; sw2 = obj_skinWeights[ face.b ]; sw3 = obj_skinWeights[ face.c ]; skinWeightArray[ offset_skin ] = sw1.x; skinWeightArray[ offset_skin + 1 ] = sw1.y; skinWeightArray[ offset_skin + 2 ] = sw1.z; skinWeightArray[ offset_skin + 3 ] = sw1.w; skinWeightArray[ offset_skin + 4 ] = sw2.x; skinWeightArray[ offset_skin + 5 ] = sw2.y; skinWeightArray[ offset_skin + 6 ] = sw2.z; skinWeightArray[ offset_skin + 7 ] = sw2.w; skinWeightArray[ offset_skin + 8 ] = sw3.x; skinWeightArray[ offset_skin + 9 ] = sw3.y; skinWeightArray[ offset_skin + 10 ] = sw3.z; skinWeightArray[ offset_skin + 11 ] = sw3.w; // indices si1 = obj_skinIndices[ face.a ]; si2 = obj_skinIndices[ face.b ]; si3 = obj_skinIndices[ face.c ]; skinIndexArray[ offset_skin ] = si1.x; skinIndexArray[ offset_skin + 1 ] = si1.y; skinIndexArray[ offset_skin + 2 ] = si1.z; skinIndexArray[ offset_skin + 3 ] = si1.w; skinIndexArray[ offset_skin + 4 ] = si2.x; skinIndexArray[ offset_skin + 5 ] = si2.y; skinIndexArray[ offset_skin + 6 ] = si2.z; skinIndexArray[ offset_skin + 7 ] = si2.w; skinIndexArray[ offset_skin + 8 ] = si3.x; skinIndexArray[ offset_skin + 9 ] = si3.y; skinIndexArray[ offset_skin + 10 ] = si3.z; skinIndexArray[ offset_skin + 11 ] = si3.w; // vertices A sa1 = obj_skinVerticesA[ face.a ]; sa2 = obj_skinVerticesA[ face.b ]; sa3 = obj_skinVerticesA[ face.c ]; skinVertexAArray[ offset_skin ] = sa1.x; skinVertexAArray[ offset_skin + 1 ] = sa1.y; skinVertexAArray[ offset_skin + 2 ] = sa1.z; skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader skinVertexAArray[ offset_skin + 4 ] = sa2.x; skinVertexAArray[ offset_skin + 5 ] = sa2.y; skinVertexAArray[ offset_skin + 6 ] = sa2.z; skinVertexAArray[ offset_skin + 7 ] = 1; skinVertexAArray[ offset_skin + 8 ] = sa3.x; skinVertexAArray[ offset_skin + 9 ] = sa3.y; skinVertexAArray[ offset_skin + 10 ] = sa3.z; skinVertexAArray[ offset_skin + 11 ] = 1; // vertices B sb1 = obj_skinVerticesB[ face.a ]; sb2 = obj_skinVerticesB[ face.b ]; sb3 = obj_skinVerticesB[ face.c ]; skinVertexBArray[ offset_skin ] = sb1.x; skinVertexBArray[ offset_skin + 1 ] = sb1.y; skinVertexBArray[ offset_skin + 2 ] = sb1.z; skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader skinVertexBArray[ offset_skin + 4 ] = sb2.x; skinVertexBArray[ offset_skin + 5 ] = sb2.y; skinVertexBArray[ offset_skin + 6 ] = sb2.z; skinVertexBArray[ offset_skin + 7 ] = 1; skinVertexBArray[ offset_skin + 8 ] = sb3.x; skinVertexBArray[ offset_skin + 9 ] = sb3.y; skinVertexBArray[ offset_skin + 10 ] = sb3.z; skinVertexBArray[ offset_skin + 11 ] = 1; offset_skin += 12; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; // weights sw1 = obj_skinWeights[ face.a ]; sw2 = obj_skinWeights[ face.b ]; sw3 = obj_skinWeights[ face.c ]; sw4 = obj_skinWeights[ face.d ]; skinWeightArray[ offset_skin ] = sw1.x; skinWeightArray[ offset_skin + 1 ] = sw1.y; skinWeightArray[ offset_skin + 2 ] = sw1.z; skinWeightArray[ offset_skin + 3 ] = sw1.w; skinWeightArray[ offset_skin + 4 ] = sw2.x; skinWeightArray[ offset_skin + 5 ] = sw2.y; skinWeightArray[ offset_skin + 6 ] = sw2.z; skinWeightArray[ offset_skin + 7 ] = sw2.w; skinWeightArray[ offset_skin + 8 ] = sw3.x; skinWeightArray[ offset_skin + 9 ] = sw3.y; skinWeightArray[ offset_skin + 10 ] = sw3.z; skinWeightArray[ offset_skin + 11 ] = sw3.w; skinWeightArray[ offset_skin + 12 ] = sw4.x; skinWeightArray[ offset_skin + 13 ] = sw4.y; skinWeightArray[ offset_skin + 14 ] = sw4.z; skinWeightArray[ offset_skin + 15 ] = sw4.w; // indices si1 = obj_skinIndices[ face.a ]; si2 = obj_skinIndices[ face.b ]; si3 = obj_skinIndices[ face.c ]; si4 = obj_skinIndices[ face.d ]; skinIndexArray[ offset_skin ] = si1.x; skinIndexArray[ offset_skin + 1 ] = si1.y; skinIndexArray[ offset_skin + 2 ] = si1.z; skinIndexArray[ offset_skin + 3 ] = si1.w; skinIndexArray[ offset_skin + 4 ] = si2.x; skinIndexArray[ offset_skin + 5 ] = si2.y; skinIndexArray[ offset_skin + 6 ] = si2.z; skinIndexArray[ offset_skin + 7 ] = si2.w; skinIndexArray[ offset_skin + 8 ] = si3.x; skinIndexArray[ offset_skin + 9 ] = si3.y; skinIndexArray[ offset_skin + 10 ] = si3.z; skinIndexArray[ offset_skin + 11 ] = si3.w; skinIndexArray[ offset_skin + 12 ] = si4.x; skinIndexArray[ offset_skin + 13 ] = si4.y; skinIndexArray[ offset_skin + 14 ] = si4.z; skinIndexArray[ offset_skin + 15 ] = si4.w; // vertices A sa1 = obj_skinVerticesA[ face.a ]; sa2 = obj_skinVerticesA[ face.b ]; sa3 = obj_skinVerticesA[ face.c ]; sa4 = obj_skinVerticesA[ face.d ]; skinVertexAArray[ offset_skin ] = sa1.x; skinVertexAArray[ offset_skin + 1 ] = sa1.y; skinVertexAArray[ offset_skin + 2 ] = sa1.z; skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader skinVertexAArray[ offset_skin + 4 ] = sa2.x; skinVertexAArray[ offset_skin + 5 ] = sa2.y; skinVertexAArray[ offset_skin + 6 ] = sa2.z; skinVertexAArray[ offset_skin + 7 ] = 1; skinVertexAArray[ offset_skin + 8 ] = sa3.x; skinVertexAArray[ offset_skin + 9 ] = sa3.y; skinVertexAArray[ offset_skin + 10 ] = sa3.z; skinVertexAArray[ offset_skin + 11 ] = 1; skinVertexAArray[ offset_skin + 12 ] = sa4.x; skinVertexAArray[ offset_skin + 13 ] = sa4.y; skinVertexAArray[ offset_skin + 14 ] = sa4.z; skinVertexAArray[ offset_skin + 15 ] = 1; // vertices B sb1 = obj_skinVerticesB[ face.a ]; sb2 = obj_skinVerticesB[ face.b ]; sb3 = obj_skinVerticesB[ face.c ]; sb4 = obj_skinVerticesB[ face.d ]; skinVertexBArray[ offset_skin ] = sb1.x; skinVertexBArray[ offset_skin + 1 ] = sb1.y; skinVertexBArray[ offset_skin + 2 ] = sb1.z; skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader skinVertexBArray[ offset_skin + 4 ] = sb2.x; skinVertexBArray[ offset_skin + 5 ] = sb2.y; skinVertexBArray[ offset_skin + 6 ] = sb2.z; skinVertexBArray[ offset_skin + 7 ] = 1; skinVertexBArray[ offset_skin + 8 ] = sb3.x; skinVertexBArray[ offset_skin + 9 ] = sb3.y; skinVertexBArray[ offset_skin + 10 ] = sb3.z; skinVertexBArray[ offset_skin + 11 ] = 1; skinVertexBArray[ offset_skin + 12 ] = sb4.x; skinVertexBArray[ offset_skin + 13 ] = sb4.y; skinVertexBArray[ offset_skin + 14 ] = sb4.z; skinVertexBArray[ offset_skin + 15 ] = 1; offset_skin += 16; } if ( offset_skin > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexAArray, hint ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexBArray, hint ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); } } if ( dirtyColors && vertexColorType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexColors = face.vertexColors; faceColor = face.color; if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) { c1 = vertexColors[ 0 ]; c2 = vertexColors[ 1 ]; c3 = vertexColors[ 2 ]; } else { c1 = faceColor; c2 = faceColor; c3 = faceColor; } colorArray[ offset_color ] = c1.r; colorArray[ offset_color + 1 ] = c1.g; colorArray[ offset_color + 2 ] = c1.b; colorArray[ offset_color + 3 ] = c2.r; colorArray[ offset_color + 4 ] = c2.g; colorArray[ offset_color + 5 ] = c2.b; colorArray[ offset_color + 6 ] = c3.r; colorArray[ offset_color + 7 ] = c3.g; colorArray[ offset_color + 8 ] = c3.b; offset_color += 9; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; vertexColors = face.vertexColors; faceColor = face.color; if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) { c1 = vertexColors[ 0 ]; c2 = vertexColors[ 1 ]; c3 = vertexColors[ 2 ]; c4 = vertexColors[ 3 ]; } else { c1 = faceColor; c2 = faceColor; c3 = faceColor; c4 = faceColor; } colorArray[ offset_color ] = c1.r; colorArray[ offset_color + 1 ] = c1.g; colorArray[ offset_color + 2 ] = c1.b; colorArray[ offset_color + 3 ] = c2.r; colorArray[ offset_color + 4 ] = c2.g; colorArray[ offset_color + 5 ] = c2.b; colorArray[ offset_color + 6 ] = c3.r; colorArray[ offset_color + 7 ] = c3.g; colorArray[ offset_color + 8 ] = c3.b; colorArray[ offset_color + 9 ] = c4.r; colorArray[ offset_color + 10 ] = c4.g; colorArray[ offset_color + 11 ] = c4.b; offset_color += 12; } if ( offset_color > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } } if ( dirtyTangents && geometry.hasTangents ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexTangents = face.vertexTangents; t1 = vertexTangents[ 0 ]; t2 = vertexTangents[ 1 ]; t3 = vertexTangents[ 2 ]; tangentArray[ offset_tangent ] = t1.x; tangentArray[ offset_tangent + 1 ] = t1.y; tangentArray[ offset_tangent + 2 ] = t1.z; tangentArray[ offset_tangent + 3 ] = t1.w; tangentArray[ offset_tangent + 4 ] = t2.x; tangentArray[ offset_tangent + 5 ] = t2.y; tangentArray[ offset_tangent + 6 ] = t2.z; tangentArray[ offset_tangent + 7 ] = t2.w; tangentArray[ offset_tangent + 8 ] = t3.x; tangentArray[ offset_tangent + 9 ] = t3.y; tangentArray[ offset_tangent + 10 ] = t3.z; tangentArray[ offset_tangent + 11 ] = t3.w; offset_tangent += 12; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; vertexTangents = face.vertexTangents; t1 = vertexTangents[ 0 ]; t2 = vertexTangents[ 1 ]; t3 = vertexTangents[ 2 ]; t4 = vertexTangents[ 3 ]; tangentArray[ offset_tangent ] = t1.x; tangentArray[ offset_tangent + 1 ] = t1.y; tangentArray[ offset_tangent + 2 ] = t1.z; tangentArray[ offset_tangent + 3 ] = t1.w; tangentArray[ offset_tangent + 4 ] = t2.x; tangentArray[ offset_tangent + 5 ] = t2.y; tangentArray[ offset_tangent + 6 ] = t2.z; tangentArray[ offset_tangent + 7 ] = t2.w; tangentArray[ offset_tangent + 8 ] = t3.x; tangentArray[ offset_tangent + 9 ] = t3.y; tangentArray[ offset_tangent + 10 ] = t3.z; tangentArray[ offset_tangent + 11 ] = t3.w; tangentArray[ offset_tangent + 12 ] = t4.x; tangentArray[ offset_tangent + 13 ] = t4.y; tangentArray[ offset_tangent + 14 ] = t4.z; tangentArray[ offset_tangent + 15 ] = t4.w; offset_tangent += 16; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); } if ( dirtyNormals && normalType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexNormals = face.vertexNormals; faceNormal = face.normal; if ( vertexNormals.length === 3 && needsSmoothNormals ) { for ( i = 0; i < 3; i ++ ) { vn = vertexNormals[ i ]; normalArray[ offset_normal ] = vn.x; normalArray[ offset_normal + 1 ] = vn.y; normalArray[ offset_normal + 2 ] = vn.z; offset_normal += 3; } } else { for ( i = 0; i < 3; i ++ ) { normalArray[ offset_normal ] = faceNormal.x; normalArray[ offset_normal + 1 ] = faceNormal.y; normalArray[ offset_normal + 2 ] = faceNormal.z; offset_normal += 3; } } } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; vertexNormals = face.vertexNormals; faceNormal = face.normal; if ( vertexNormals.length === 4 && needsSmoothNormals ) { for ( i = 0; i < 4; i ++ ) { vn = vertexNormals[ i ]; normalArray[ offset_normal ] = vn.x; normalArray[ offset_normal + 1 ] = vn.y; normalArray[ offset_normal + 2 ] = vn.z; offset_normal += 3; } } else { for ( i = 0; i < 4; i ++ ) { normalArray[ offset_normal ] = faceNormal.x; normalArray[ offset_normal + 1 ] = faceNormal.y; normalArray[ offset_normal + 2 ] = faceNormal.z; offset_normal += 3; } } } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); } if ( dirtyUvs && obj_uvs && uvType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { fi = chunk_faces3[ f ]; face = obj_faces[ fi ]; uv = obj_uvs[ fi ]; if ( uv === undefined ) continue; for ( i = 0; i < 3; i ++ ) { uvi = uv[ i ]; uvArray[ offset_uv ] = uvi.u; uvArray[ offset_uv + 1 ] = uvi.v; offset_uv += 2; } } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { fi = chunk_faces4[ f ]; face = obj_faces[ fi ]; uv = obj_uvs[ fi ]; if ( uv === undefined ) continue; for ( i = 0; i < 4; i ++ ) { uvi = uv[ i ]; uvArray[ offset_uv ] = uvi.u; uvArray[ offset_uv + 1 ] = uvi.v; offset_uv += 2; } } if ( offset_uv > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); } } if ( dirtyUvs && obj_uvs2 && uvType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { fi = chunk_faces3[ f ]; face = obj_faces[ fi ]; uv2 = obj_uvs2[ fi ]; if ( uv2 === undefined ) continue; for ( i = 0; i < 3; i ++ ) { uv2i = uv2[ i ]; uv2Array[ offset_uv2 ] = uv2i.u; uv2Array[ offset_uv2 + 1 ] = uv2i.v; offset_uv2 += 2; } } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { fi = chunk_faces4[ f ]; face = obj_faces[ fi ]; uv2 = obj_uvs2[ fi ]; if ( uv2 === undefined ) continue; for ( i = 0; i < 4; i ++ ) { uv2i = uv2[ i ]; uv2Array[ offset_uv2 ] = uv2i.u; uv2Array[ offset_uv2 + 1 ] = uv2i.v; offset_uv2 += 2; } } if ( offset_uv2 > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); } } if ( dirtyElements ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; faceArray[ offset_face ] = vertexIndex; faceArray[ offset_face + 1 ] = vertexIndex + 1; faceArray[ offset_face + 2 ] = vertexIndex + 2; offset_face += 3; lineArray[ offset_line ] = vertexIndex; lineArray[ offset_line + 1 ] = vertexIndex + 1; lineArray[ offset_line + 2 ] = vertexIndex; lineArray[ offset_line + 3 ] = vertexIndex + 2; lineArray[ offset_line + 4 ] = vertexIndex + 1; lineArray[ offset_line + 5 ] = vertexIndex + 2; offset_line += 6; vertexIndex += 3; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; faceArray[ offset_face ] = vertexIndex; faceArray[ offset_face + 1 ] = vertexIndex + 1; faceArray[ offset_face + 2 ] = vertexIndex + 3; faceArray[ offset_face + 3 ] = vertexIndex + 1; faceArray[ offset_face + 4 ] = vertexIndex + 2; faceArray[ offset_face + 5 ] = vertexIndex + 3; offset_face += 6; lineArray[ offset_line ] = vertexIndex; lineArray[ offset_line + 1 ] = vertexIndex + 1; lineArray[ offset_line + 2 ] = vertexIndex; lineArray[ offset_line + 3 ] = vertexIndex + 3; lineArray[ offset_line + 4 ] = vertexIndex + 1; lineArray[ offset_line + 5 ] = vertexIndex + 2; lineArray[ offset_line + 6 ] = vertexIndex + 2; lineArray[ offset_line + 7 ] = vertexIndex + 3; offset_line += 8; vertexIndex += 4; } _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( ! customAttribute.__original.needsUpdate ) continue; offset_custom = 0; offset_customSrc = 0; if ( customAttribute.size === 1 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; offset_custom += 3; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ]; offset_custom += 4; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; customAttribute.array[ offset_custom ] = value; customAttribute.array[ offset_custom + 1 ] = value; customAttribute.array[ offset_custom + 2 ] = value; offset_custom += 3; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces4[ f ] ]; customAttribute.array[ offset_custom ] = value; customAttribute.array[ offset_custom + 1 ] = value; customAttribute.array[ offset_custom + 2 ] = value; customAttribute.array[ offset_custom + 3 ] = value; offset_custom += 4; } } } else if ( customAttribute.size === 2 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; offset_custom += 6; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; v4 = customAttribute.value[ face.d ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; customAttribute.array[ offset_custom + 6 ] = v4.x; customAttribute.array[ offset_custom + 7 ] = v4.y; offset_custom += 8; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; offset_custom += 6; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces4[ f ] ]; v1 = value; v2 = value; v3 = value; v4 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; customAttribute.array[ offset_custom + 6 ] = v4.x; customAttribute.array[ offset_custom + 7 ] = v4.y; offset_custom += 8; } } } else if ( customAttribute.size === 3 ) { var pp; if ( customAttribute.type === "c" ) { pp = [ "r", "g", "b" ]; } else { pp = [ "x", "y", "z" ]; } if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; v4 = customAttribute.value[ face.d ]; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ]; offset_custom += 12; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces4[ f ] ]; v1 = value; v2 = value; v3 = value; v4 = value; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ]; offset_custom += 12; } } } else if ( customAttribute.size === 4 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces4[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; v4 = customAttribute.value[ face.d ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; customAttribute.array[ offset_custom + 12 ] = v4.x; customAttribute.array[ offset_custom + 13 ] = v4.y; customAttribute.array[ offset_custom + 14 ] = v4.z; customAttribute.array[ offset_custom + 15 ] = v4.w; offset_custom += 16; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces4[ f ] ]; v1 = value; v2 = value; v3 = value; v4 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; customAttribute.array[ offset_custom + 12 ] = v4.x; customAttribute.array[ offset_custom + 13 ] = v4.y; customAttribute.array[ offset_custom + 14 ] = v4.z; customAttribute.array[ offset_custom + 15 ] = v4.w; offset_custom += 16; } } } _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } if ( dispose ) { delete geometryGroup.__inittedArrays; delete geometryGroup.__colorArray; delete geometryGroup.__normalArray; delete geometryGroup.__tangentArray; delete geometryGroup.__uvArray; delete geometryGroup.__uv2Array; delete geometryGroup.__faceArray; delete geometryGroup.__vertexArray; delete geometryGroup.__lineArray; delete geometryGroup.__skinVertexAArray; delete geometryGroup.__skinVertexBArray; delete geometryGroup.__skinIndexArray; delete geometryGroup.__skinWeightArray; } }; // Buffer rendering this.renderBufferImmediate = function ( object, program, shading ) { if ( ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer(); if ( ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer(); if ( object.hasPos ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.position ); _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.hasNormal ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer ); if ( shading === THREE.FlatShading ) { var nx, ny, nz, nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz, normalArray, i, il = object.count * 3; for( i = 0; i < il; i += 9 ) { normalArray = object.normalArray; nax = normalArray[ i ]; nay = normalArray[ i + 1 ]; naz = normalArray[ i + 2 ]; nbx = normalArray[ i + 3 ]; nby = normalArray[ i + 4 ]; nbz = normalArray[ i + 5 ]; ncx = normalArray[ i + 6 ]; ncy = normalArray[ i + 7 ]; ncz = normalArray[ i + 8 ]; nx = ( nax + nbx + ncx ) / 3; ny = ( nay + nby + ncy ) / 3; nz = ( naz + nbz + ncz ) / 3; normalArray[ i ] = nx; normalArray[ i + 1 ] = ny; normalArray[ i + 2 ] = nz; normalArray[ i + 3 ] = nx; normalArray[ i + 4 ] = ny; normalArray[ i + 5 ] = nz; normalArray[ i + 6 ] = nx; normalArray[ i + 7 ] = ny; normalArray[ i + 8 ] = nz; } } _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.normal ); _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); object.count = 0; }; this.renderBufferDirect = function ( camera, lights, fog, material, geometryGroup, object ) { if ( material.visible === false ) return; var program, attributes, linewidth, primitives, a, attribute; program = setProgram( camera, lights, fog, material, object ); attributes = program.attributes; var updateBuffers = false, wireframeBit = material.wireframe ? 1 : 0, geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; if ( geometryGroupHash !== _currentGeometryGroupHash ) { _currentGeometryGroupHash = geometryGroupHash; updateBuffers = true; } // render mesh if ( object instanceof THREE.Mesh ) { var offsets = geometryGroup.offsets; for ( var i = 0, il = offsets.length; i < il; ++ i ) { if ( updateBuffers ) { // vertices _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexPositionBuffer ); _gl.vertexAttribPointer( attributes.position, geometryGroup.vertexPositionBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 ); // normals if ( attributes.normal >= 0 && geometryGroup.vertexNormalBuffer ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexNormalBuffer ); _gl.vertexAttribPointer( attributes.normal, geometryGroup.vertexNormalBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 ); } // uvs if ( attributes.uv >= 0 && geometryGroup.vertexUvBuffer ) { if ( geometryGroup.vertexUvBuffer ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexUvBuffer ); _gl.vertexAttribPointer( attributes.uv, geometryGroup.vertexUvBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 2 ); _gl.enableVertexAttribArray( attributes.uv ); } else { _gl.disableVertexAttribArray( attributes.uv ); } } // colors if ( attributes.color >= 0 && geometryGroup.vertexColorBuffer ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexColorBuffer ); _gl.vertexAttribPointer( attributes.color, geometryGroup.vertexColorBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 4 ); } _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.vertexIndexBuffer ); } // render indexed triangles _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 = Uint16 _this.info.render.calls ++; _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared _this.info.render.faces += offsets[ i ].count / 3; } } }; this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { if ( material.visible === false ) return; var program, attributes, linewidth, primitives, a, attribute, i, il; program = setProgram( camera, lights, fog, material, object ); attributes = program.attributes; var updateBuffers = false, wireframeBit = material.wireframe ? 1 : 0, geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; if ( geometryGroupHash !== _currentGeometryGroupHash ) { _currentGeometryGroupHash = geometryGroupHash; updateBuffers = true; } // vertices if ( !material.morphTargets && attributes.position >= 0 ) { if ( updateBuffers ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } } else { if ( object.morphTargetBase ) { setupMorphTargets( material, geometryGroup, object ); } } if ( updateBuffers ) { // custom attributes // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers if ( geometryGroup.__webglCustomAttributesList ) { for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { attribute = geometryGroup.__webglCustomAttributesList[ i ]; if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); } } } // colors if ( attributes.color >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); } // normals if ( attributes.normal >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } // tangents if ( attributes.tangent >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); } // uvs if ( attributes.uv >= 0 ) { if ( geometryGroup.__webglUVBuffer ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); _gl.enableVertexAttribArray( attributes.uv ); } else { _gl.disableVertexAttribArray( attributes.uv ); } } if ( attributes.uv2 >= 0 ) { if ( geometryGroup.__webglUV2Buffer ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); _gl.enableVertexAttribArray( attributes.uv2 ); } else { _gl.disableVertexAttribArray( attributes.uv2 ); } } if ( material.skinning && attributes.skinVertexA >= 0 && attributes.skinVertexB >= 0 && attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer ); _gl.vertexAttribPointer( attributes.skinVertexA, 4, _gl.FLOAT, false, 0, 0 ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer ); _gl.vertexAttribPointer( attributes.skinVertexB, 4, _gl.FLOAT, false, 0, 0 ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); } } // render mesh if ( object instanceof THREE.Mesh ) { // wireframe if ( material.wireframe ) { setLineWidth( material.wireframeLinewidth ); if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 ); // triangles } else { if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 ); } _this.info.render.calls ++; _this.info.render.vertices += geometryGroup.__webglFaceCount; _this.info.render.faces += geometryGroup.__webglFaceCount / 3; // render lines } else if ( object instanceof THREE.Line ) { primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; setLineWidth( material.linewidth ); _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount ); _this.info.render.calls ++; // render particles } else if ( object instanceof THREE.ParticleSystem ) { _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); _this.info.render.calls ++; _this.info.render.points += geometryGroup.__webglParticleCount; // render ribbon } else if ( object instanceof THREE.Ribbon ) { _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount ); _this.info.render.calls ++; } }; function setupMorphTargets ( material, geometryGroup, object ) { // set base var attributes = material.program.attributes; if ( object.morphTargetBase !== - 1 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } else if ( attributes.position >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.morphTargetForcedOrder.length ) { // set forced order var m = 0; var order = object.morphTargetForcedOrder; var influences = object.morphTargetInfluences; while ( m < material.numSupportedMorphTargets && m < order.length ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); if ( material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; m ++; } } else { // find most influencing var used = []; var candidateInfluence = - 1; var candidate = 0; var influences = object.morphTargetInfluences; var i, il = influences.length; var m = 0; if ( object.morphTargetBase !== - 1 ) { used[ object.morphTargetBase ] = true; } while ( m < material.numSupportedMorphTargets ) { for ( i = 0; i < il; i ++ ) { if ( !used[ i ] && influences[ i ] > candidateInfluence ) { candidate = i; candidateInfluence = influences[ candidate ]; } } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ candidate ] ); _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); if ( material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ candidate ] ); _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } object.__webglMorphTargetInfluences[ m ] = candidateInfluence; used[ candidate ] = 1; candidateInfluence = -1; m ++; } } // load updated influences uniform if( material.program.uniforms.morphTargetInfluences !== null ) { _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); } }; function painterSort ( a, b ) { return b.z - a.z; }; // Rendering this.render = function ( scene, camera, renderTarget, forceClear ) { var i, il, webglObject, object, renderList, lights = scene.__lights, fog = scene.fog; // reset caching for this frame _currentMaterialId = -1; _lightsNeedUpdate = true; // update scene graph if ( camera.parent === undefined ) { console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' ); scene.add( camera ); } if ( this.autoUpdateScene ) scene.updateMatrixWorld(); // update camera matrices and frustum if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 ); if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 ); camera.matrixWorldInverse.getInverse( camera.matrixWorld ); camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray ); camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray ); _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse ); _frustum.setFromMatrix( _projScreenMatrix ); // update WebGL objects if ( this.autoUpdateObjects ) this.initWebGLObjects( scene ); // custom render plugins (pre pass) renderPlugins( this.renderPluginsPre, scene, camera ); // _this.info.render.calls = 0; _this.info.render.vertices = 0; _this.info.render.faces = 0; _this.info.render.points = 0; this.setRenderTarget( renderTarget ); if ( this.autoClear || forceClear ) { this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); } // set matrices for regular objects (frustum culled) renderList = scene.__webglObjects; for ( i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; webglObject.render = false; if ( object.visible ) { if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) { //object.matrixWorld.flattenToArray( object._objectMatrixArray ); setupMatrices( object, camera ); unrollBufferMaterial( webglObject ); webglObject.render = true; if ( this.sortObjects ) { if ( object.renderDepth ) { webglObject.z = object.renderDepth; } else { _vector3.copy( object.matrixWorld.getPosition() ); _projScreenMatrix.multiplyVector3( _vector3 ); webglObject.z = _vector3.z; } } } } } if ( this.sortObjects ) { renderList.sort( painterSort ); } // set matrices for immediate objects renderList = scene.__webglObjectsImmediate; for ( i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; if ( object.visible ) { /* if ( object.matrixAutoUpdate ) { object.matrixWorld.flattenToArray( object._objectMatrixArray ); } */ setupMatrices( object, camera ); unrollImmediateBufferMaterial( webglObject ); } } if ( scene.overrideMaterial ) { var material = scene.overrideMaterial; this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); this.setDepthTest( material.depthTest ); this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material ); renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material ); } else { // opaque pass (front-to-back order) this.setBlending( THREE.NormalBlending ); renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false ); renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false ); // transparent pass (back-to-front order) renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true ); renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true ); } // custom render plugins (post pass) renderPlugins( this.renderPluginsPost, scene, camera ); // Generate mipmap if we're using any kind of mipmap filtering if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { updateRenderTargetMipmap( renderTarget ); } // Ensure depth buffer writing is enabled so it can be cleared on next render this.setDepthTest( true ); this.setDepthWrite( true ); // _gl.finish(); }; function renderPlugins( plugins, scene, camera ) { if ( ! plugins.length ) return; for ( var i = 0, il = plugins.length; i < il; i ++ ) { // reset state for plugin (to start from clean slate) _currentProgram = null; _currentCamera = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _oldDoubleSided = -1; _oldFlipSided = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; plugins[ i ].render( scene, camera, _currentWidth, _currentHeight ); // reset state after plugin (anything could have changed) _currentProgram = null; _currentCamera = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _oldDoubleSided = -1; _oldFlipSided = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; } }; function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) { var webglObject, object, buffer, material, start, end, delta; if ( reverse ) { start = renderList.length - 1; end = -1; delta = -1; } else { start = 0; end = renderList.length; delta = 1; } for ( var i = start; i !== end; i += delta ) { webglObject = renderList[ i ]; if ( webglObject.render ) { object = webglObject.object; buffer = webglObject.buffer; if ( overrideMaterial ) { material = overrideMaterial; } else { material = webglObject[ materialType ]; if ( ! material ) continue; if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); _this.setDepthTest( material.depthTest ); _this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } _this.setObjectFaces( object ); if ( buffer instanceof THREE.BufferGeometry ) { _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); } else { _this.renderBuffer( camera, lights, fog, material, buffer, object ); } } } }; function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) { var webglObject, object, material, program; for ( var i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; if ( object.visible ) { if ( overrideMaterial ) { material = overrideMaterial; } else { material = webglObject[ materialType ]; if ( ! material ) continue; if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); _this.setDepthTest( material.depthTest ); _this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } _this.renderImmediateObject( camera, lights, fog, material, object ); } } }; this.renderImmediateObject = function ( camera, lights, fog, material, object ) { var program = setProgram( camera, lights, fog, material, object ); _currentGeometryGroupHash = -1; _this.setObjectFaces( object ); if ( object.immediateRenderCallback ) { object.immediateRenderCallback( program, _gl, _frustum ); } else { object.render( function( object ) { _this.renderBufferImmediate( object, program, material.shading ); } ); } }; function unrollImmediateBufferMaterial ( globject ) { var object = globject.object, material = object.material; if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } }; function unrollBufferMaterial ( globject ) { var object = globject.object, buffer = globject.buffer, material, materialIndex, meshMaterial; meshMaterial = object.material; if ( meshMaterial instanceof THREE.MeshFaceMaterial ) { materialIndex = buffer.materialIndex; if ( materialIndex >= 0 ) { material = object.geometry.materials[ materialIndex ]; if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } } } else { material = meshMaterial; if ( material ) { if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } } } }; // Geometry splitting function sortFacesByMaterial ( geometry ) { var f, fl, face, materialIndex, vertices, materialHash, groupHash, hash_map = {}; var numMorphTargets = geometry.morphTargets.length; var numMorphNormals = geometry.morphNormals.length; geometry.geometryGroups = {}; for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) { face = geometry.faces[ f ]; materialIndex = face.materialIndex; materialHash = ( materialIndex !== undefined ) ? materialIndex : -1; if ( hash_map[ materialHash ] === undefined ) { hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 }; } groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter; if ( geometry.geometryGroups[ groupHash ] === undefined ) { geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; } vertices = face instanceof THREE.Face3 ? 3 : 4; if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) { hash_map[ materialHash ].counter += 1; groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter; if ( geometry.geometryGroups[ groupHash ] === undefined ) { geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; } } if ( face instanceof THREE.Face3 ) { geometry.geometryGroups[ groupHash ].faces3.push( f ); } else { geometry.geometryGroups[ groupHash ].faces4.push( f ); } geometry.geometryGroups[ groupHash ].vertices += vertices; } geometry.geometryGroupsList = []; for ( var g in geometry.geometryGroups ) { geometry.geometryGroups[ g ].id = _geometryGroupCounter ++; geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] ); } }; // Objects refresh this.initWebGLObjects = function ( scene ) { if ( !scene.__webglObjects ) { scene.__webglObjects = []; scene.__webglObjectsImmediate = []; scene.__webglSprites = []; scene.__webglFlares = []; } while ( scene.__objectsAdded.length ) { addObject( scene.__objectsAdded[ 0 ], scene ); scene.__objectsAdded.splice( 0, 1 ); } while ( scene.__objectsRemoved.length ) { removeObject( scene.__objectsRemoved[ 0 ], scene ); scene.__objectsRemoved.splice( 0, 1 ); } // update must be called after objects adding / removal for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) { updateObject( scene.__webglObjects[ o ].object ); } }; // Objects adding function addObject ( object, scene ) { var g, geometry, geometryGroup; if ( ! object.__webglInit ) { object.__webglInit = true; object._modelViewMatrix = new THREE.Matrix4(); object._normalMatrix = new THREE.Matrix3(); //object._normalMatrixArray = new Float32Array( 9 ); //object._modelViewMatrixArray = new Float32Array( 16 ); //object._objectMatrixArray = new Float32Array( 16 ); //object.matrixWorld.flattenToArray( object._objectMatrixArray ); if ( object instanceof THREE.Mesh ) { geometry = object.geometry; if ( geometry instanceof THREE.Geometry ) { if ( geometry.geometryGroups === undefined ) { sortFacesByMaterial( geometry ); } // create separate VBOs per geometry chunk for ( g in geometry.geometryGroups ) { geometryGroup = geometry.geometryGroups[ g ]; // initialise VBO on the first access if ( ! geometryGroup.__webglVertexBuffer ) { createMeshBuffers( geometryGroup ); initMeshBuffers( geometryGroup, object ); geometry.verticesNeedUpdate = true; geometry.morphTargetsNeedUpdate = true; geometry.elementsNeedUpdate = true; geometry.uvsNeedUpdate = true; geometry.normalsNeedUpdate = true; geometry.tangetsNeedUpdate = true; geometry.colorsNeedUpdate = true; } } } } else if ( object instanceof THREE.Ribbon ) { geometry = object.geometry; if( ! geometry.__webglVertexBuffer ) { createRibbonBuffers( geometry ); initRibbonBuffers( geometry ); geometry.verticesNeedUpdate = true; geometry.colorsNeedUpdate = true; } } else if ( object instanceof THREE.Line ) { geometry = object.geometry; if( ! geometry.__webglVertexBuffer ) { createLineBuffers( geometry ); initLineBuffers( geometry, object ); geometry.verticesNeedUpdate = true; geometry.colorsNeedUpdate = true; } } else if ( object instanceof THREE.ParticleSystem ) { geometry = object.geometry; if ( ! geometry.__webglVertexBuffer ) { createParticleBuffers( geometry ); initParticleBuffers( geometry, object ); geometry.verticesNeedUpdate = true; geometry.colorsNeedUpdate = true; } } } if ( ! object.__webglActive ) { if ( object instanceof THREE.Mesh ) { geometry = object.geometry; if ( geometry instanceof THREE.BufferGeometry ) { addBuffer( scene.__webglObjects, geometry, object ); } else { for ( g in geometry.geometryGroups ) { geometryGroup = geometry.geometryGroups[ g ]; addBuffer( scene.__webglObjects, geometryGroup, object ); } } } else if ( object instanceof THREE.Ribbon || object instanceof THREE.Line || object instanceof THREE.ParticleSystem ) { geometry = object.geometry; addBuffer( scene.__webglObjects, geometry, object ); } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { addBufferImmediate( scene.__webglObjectsImmediate, object ); } else if ( object instanceof THREE.Sprite ) { scene.__webglSprites.push( object ); } else if ( object instanceof THREE.LensFlare ) { scene.__webglFlares.push( object ); } object.__webglActive = true; } }; function addBuffer ( objlist, buffer, object ) { objlist.push( { buffer: buffer, object: object, opaque: null, transparent: null } ); }; function addBufferImmediate ( objlist, object ) { objlist.push( { object: object, opaque: null, transparent: null } ); }; // Objects updates function updateObject ( object ) { var geometry = object.geometry, geometryGroup, customAttributesDirty, material; if ( object instanceof THREE.Mesh ) { if ( geometry instanceof THREE.BufferGeometry ) { /* if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate || geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || geometry.colorsNeedUpdate ) { // TODO // set buffers from typed arrays } */ geometry.verticesNeedUpdate = false; geometry.elementsNeedUpdate = false; geometry.uvsNeedUpdate = false; geometry.normalsNeedUpdate = false; geometry.colorsNeedUpdate = false; } else { // check all geometry groups for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) { geometryGroup = geometry.geometryGroupsList[ i ]; material = getBufferMaterial( object, geometryGroup ); customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate || geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || geometry.colorsNeedUpdate || geometry.tangetsNeedUpdate || customAttributesDirty ) { setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material ); } } geometry.verticesNeedUpdate = false; geometry.morphTargetsNeedUpdate = false; geometry.elementsNeedUpdate = false; geometry.uvsNeedUpdate = false; geometry.normalsNeedUpdate = false; geometry.colorsNeedUpdate = false; geometry.tangetsNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } } else if ( object instanceof THREE.Ribbon ) { if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) { setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW ); } geometry.verticesNeedUpdate = false; geometry.colorsNeedUpdate = false; } else if ( object instanceof THREE.Line ) { material = getBufferMaterial( object, geometryGroup ); customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) { setLineBuffers( geometry, _gl.DYNAMIC_DRAW ); } geometry.verticesNeedUpdate = false; geometry.colorsNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } else if ( object instanceof THREE.ParticleSystem ) { material = getBufferMaterial( object, geometryGroup ); customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) { setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object ); } geometry.verticesNeedUpdate = false; geometry.colorsNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } }; // Objects updates - custom attributes check function areCustomAttributesDirty ( material ) { for ( var a in material.attributes ) { if ( material.attributes[ a ].needsUpdate ) return true; } return false; }; function clearCustomAttributes ( material ) { for ( var a in material.attributes ) { material.attributes[ a ].needsUpdate = false; } }; // Objects removal function removeObject ( object, scene ) { if ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem || object instanceof THREE.Ribbon || object instanceof THREE.Line ) { removeInstances( scene.__webglObjects, object ); } else if ( object instanceof THREE.Sprite ) { removeInstancesDirect( scene.__webglSprites, object ); } else if ( object instanceof THREE.LensFlare ) { removeInstancesDirect( scene.__webglFlares, object ); } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { removeInstances( scene.__webglObjectsImmediate, object ); } object.__webglActive = false; }; function removeInstances ( objlist, object ) { for ( var o = objlist.length - 1; o >= 0; o -- ) { if ( objlist[ o ].object === object ) { objlist.splice( o, 1 ); } } }; function removeInstancesDirect ( objlist, object ) { for ( var o = objlist.length - 1; o >= 0; o -- ) { if ( objlist[ o ] === object ) { objlist.splice( o, 1 ); } } }; // Materials this.initMaterial = function ( material, lights, fog, object ) { var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID; if ( material instanceof THREE.MeshDepthMaterial ) { shaderID = 'depth'; } else if ( material instanceof THREE.MeshNormalMaterial ) { shaderID = 'normal'; } else if ( material instanceof THREE.MeshBasicMaterial ) { shaderID = 'basic'; } else if ( material instanceof THREE.MeshLambertMaterial ) { shaderID = 'lambert'; } else if ( material instanceof THREE.MeshPhongMaterial ) { shaderID = 'phong'; } else if ( material instanceof THREE.LineBasicMaterial ) { shaderID = 'basic'; } else if ( material instanceof THREE.ParticleBasicMaterial ) { shaderID = 'particle_basic'; } if ( shaderID ) { setMaterialShaders( material, THREE.ShaderLib[ shaderID ] ); } // heuristics to create shader parameters according to lights in the scene // (not to blow over maxLights budget) maxLightCount = allocateLights( lights ); maxShadows = allocateShadows( lights ); maxBones = allocateBones( object ); parameters = { map: !!material.map, envMap: !!material.envMap, lightMap: !!material.lightMap, vertexColors: material.vertexColors, fog: fog, useFog: material.fog, sizeAttenuation: material.sizeAttenuation, skinning: material.skinning, maxBones: maxBones, morphTargets: material.morphTargets, morphNormals: material.morphNormals, maxMorphTargets: this.maxMorphTargets, maxMorphNormals: this.maxMorphNormals, maxDirLights: maxLightCount.directional, maxPointLights: maxLightCount.point, maxSpotLights: maxLightCount.spot, maxShadows: maxShadows, shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow, shadowMapSoft: this.shadowMapSoft, shadowMapDebug: this.shadowMapDebug, shadowMapCascade: this.shadowMapCascade, alphaTest: material.alphaTest, metal: material.metal, perPixel: material.perPixel, wrapAround: material.wrapAround, doubleSided: object && object.doubleSided }; material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters ); var attributes = material.program.attributes; if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position ); if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color ); if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal ); if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent ); if ( material.skinning && attributes.skinVertexA >=0 && attributes.skinVertexB >= 0 && attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { _gl.enableVertexAttribArray( attributes.skinVertexA ); _gl.enableVertexAttribArray( attributes.skinVertexB ); _gl.enableVertexAttribArray( attributes.skinIndex ); _gl.enableVertexAttribArray( attributes.skinWeight ); } if ( material.attributes ) { for ( a in material.attributes ) { if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] ); } } if ( material.morphTargets ) { material.numSupportedMorphTargets = 0; var id, base = "morphTarget"; for ( i = 0; i < this.maxMorphTargets; i ++ ) { id = base + i; if ( attributes[ id ] >= 0 ) { _gl.enableVertexAttribArray( attributes[ id ] ); material.numSupportedMorphTargets ++; } } } if ( material.morphNormals ) { material.numSupportedMorphNormals = 0; var id, base = "morphNormal"; for ( i = 0; i < this.maxMorphNormals; i ++ ) { id = base + i; if ( attributes[ id ] >= 0 ) { _gl.enableVertexAttribArray( attributes[ id ] ); material.numSupportedMorphNormals ++; } } } material.uniformsList = []; for ( u in material.uniforms ) { material.uniformsList.push( [ material.uniforms[ u ], u ] ); } }; function setMaterialShaders( material, shaders ) { material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms ); material.vertexShader = shaders.vertexShader; material.fragmentShader = shaders.fragmentShader; }; function setProgram( camera, lights, fog, material, object ) { if ( ! material.program || material.needsUpdate ) { _this.initMaterial( material, lights, fog, object ); material.needsUpdate = false; } if ( material.morphTargets ) { if ( ! object.__webglMorphTargetInfluences ) { object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); for ( var i = 0, il = _this.maxMorphTargets; i < il; i ++ ) { object.__webglMorphTargetInfluences[ i ] = 0; } } } var refreshMaterial = false; var program = material.program, p_uniforms = program.uniforms, m_uniforms = material.uniforms; if ( program !== _currentProgram ) { _gl.useProgram( program ); _currentProgram = program; refreshMaterial = true; } if ( material.id !== _currentMaterialId ) { _currentMaterialId = material.id; refreshMaterial = true; } if ( refreshMaterial || camera !== _currentCamera ) { _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray ); if ( camera !== _currentCamera ) _currentCamera = camera; } if ( refreshMaterial ) { // refresh uniforms common to several materials if ( fog && material.fog ) { refreshUniformsFog( m_uniforms, fog ); } if ( material instanceof THREE.MeshPhongMaterial || material instanceof THREE.MeshLambertMaterial || material.lights ) { if ( _lightsNeedUpdate ) { setupLights( program, lights ); _lightsNeedUpdate = false; } refreshUniformsLights( m_uniforms, _lights ); } if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) { refreshUniformsCommon( m_uniforms, material ); } // refresh single material specific uniforms if ( material instanceof THREE.LineBasicMaterial ) { refreshUniformsLine( m_uniforms, material ); } else if ( material instanceof THREE.ParticleBasicMaterial ) { refreshUniformsParticle( m_uniforms, material ); } else if ( material instanceof THREE.MeshPhongMaterial ) { refreshUniformsPhong( m_uniforms, material ); } else if ( material instanceof THREE.MeshLambertMaterial ) { refreshUniformsLambert( m_uniforms, material ); } else if ( material instanceof THREE.MeshDepthMaterial ) { m_uniforms.mNear.value = camera.near; m_uniforms.mFar.value = camera.far; m_uniforms.opacity.value = material.opacity; } else if ( material instanceof THREE.MeshNormalMaterial ) { m_uniforms.opacity.value = material.opacity; } if ( object.receiveShadow && ! material._shadowPass ) { refreshUniformsShadow( m_uniforms, lights ); } // load common uniforms loadUniformsGeneric( program, material.uniformsList ); // load material specific uniforms // (shader material also gets them for the sake of genericity) if ( material instanceof THREE.ShaderMaterial || material instanceof THREE.MeshPhongMaterial || material.envMap ) { if ( p_uniforms.cameraPosition !== null ) { var position = camera.matrixWorld.getPosition(); _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z ); } } if ( material instanceof THREE.MeshPhongMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.ShaderMaterial || material.skinning ) { if ( p_uniforms.viewMatrix !== null ) { _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray ); } } if ( material.skinning ) { _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices ); } } loadUniformsMatrices( p_uniforms, object ); if ( p_uniforms.objectMatrix !== null ) { _gl.uniformMatrix4fv( p_uniforms.objectMatrix, false, object.matrixWorld.elements ); } return program; }; // Uniforms (refresh uniforms objects) function refreshUniformsCommon ( uniforms, material ) { uniforms.opacity.value = material.opacity; if ( _this.gammaInput ) { uniforms.diffuse.value.copyGammaToLinear( material.color ); } else { uniforms.diffuse.value = material.color; } uniforms.map.texture = material.map; if ( material.map ) { uniforms.offsetRepeat.value.set( material.map.offset.x, material.map.offset.y, material.map.repeat.x, material.map.repeat.y ); } uniforms.lightMap.texture = material.lightMap; uniforms.envMap.texture = material.envMap; uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1; if ( _this.gammaInput ) { //uniforms.reflectivity.value = material.reflectivity * material.reflectivity; uniforms.reflectivity.value = material.reflectivity; } else { uniforms.reflectivity.value = material.reflectivity; } uniforms.refractionRatio.value = material.refractionRatio; uniforms.combine.value = material.combine; uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping; }; function refreshUniformsLine ( uniforms, material ) { uniforms.diffuse.value = material.color; uniforms.opacity.value = material.opacity; }; function refreshUniformsParticle ( uniforms, material ) { uniforms.psColor.value = material.color; uniforms.opacity.value = material.opacity; uniforms.size.value = material.size; uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. uniforms.map.texture = material.map; }; function refreshUniformsFog ( uniforms, fog ) { uniforms.fogColor.value = fog.color; if ( fog instanceof THREE.Fog ) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; } else if ( fog instanceof THREE.FogExp2 ) { uniforms.fogDensity.value = fog.density; } }; function refreshUniformsPhong ( uniforms, material ) { uniforms.shininess.value = material.shininess; if ( _this.gammaInput ) { uniforms.ambient.value.copyGammaToLinear( material.ambient ); uniforms.emissive.value.copyGammaToLinear( material.emissive ); uniforms.specular.value.copyGammaToLinear( material.specular ); } else { uniforms.ambient.value = material.ambient; uniforms.emissive.value = material.emissive; uniforms.specular.value = material.specular; } if ( material.wrapAround ) { uniforms.wrapRGB.value.copy( material.wrapRGB ); } }; function refreshUniformsLambert ( uniforms, material ) { if ( _this.gammaInput ) { uniforms.ambient.value.copyGammaToLinear( material.ambient ); uniforms.emissive.value.copyGammaToLinear( material.emissive ); } else { uniforms.ambient.value = material.ambient; uniforms.emissive.value = material.emissive; } if ( material.wrapAround ) { uniforms.wrapRGB.value.copy( material.wrapRGB ); } }; function refreshUniformsLights ( uniforms, lights ) { uniforms.ambientLightColor.value = lights.ambient; uniforms.directionalLightColor.value = lights.directional.colors; uniforms.directionalLightDirection.value = lights.directional.positions; uniforms.pointLightColor.value = lights.point.colors; uniforms.pointLightPosition.value = lights.point.positions; uniforms.pointLightDistance.value = lights.point.distances; uniforms.spotLightColor.value = lights.spot.colors; uniforms.spotLightPosition.value = lights.spot.positions; uniforms.spotLightDistance.value = lights.spot.distances; uniforms.spotLightDirection.value = lights.spot.directions; uniforms.spotLightAngle.value = lights.spot.angles; uniforms.spotLightExponent.value = lights.spot.exponents; }; function refreshUniformsShadow ( uniforms, lights ) { if ( uniforms.shadowMatrix ) { var j = 0; for ( var i = 0, il = lights.length; i < il; i ++ ) { var light = lights[ i ]; if ( ! light.castShadow ) continue; if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { uniforms.shadowMap.texture[ j ] = light.shadowMap; uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; uniforms.shadowBias.value[ j ] = light.shadowBias; j ++; } } } }; // Uniforms (load to GPU) function loadUniformsMatrices ( uniforms, object ) { _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); if ( uniforms.normalMatrix ) { _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); } }; function loadUniformsGeneric ( program, uniforms ) { var uniform, value, type, location, texture, i, il, j, jl, offset; for ( j = 0, jl = uniforms.length; j < jl; j ++ ) { location = program.uniforms[ uniforms[ j ][ 1 ] ]; if ( !location ) continue; uniform = uniforms[ j ][ 0 ]; type = uniform.type; value = uniform.value; switch ( type ) { case "i": // single integer _gl.uniform1i( location, value ); break; case "f": // single float _gl.uniform1f( location, value ); break; case "v2": // single THREE.Vector2 _gl.uniform2f( location, value.x, value.y ); break; case "v3": // single THREE.Vector3 _gl.uniform3f( location, value.x, value.y, value.z ); break; case "v4": // single THREE.Vector4 _gl.uniform4f( location, value.x, value.y, value.z, value.w ); break; case "c": // single THREE.Color _gl.uniform3f( location, value.r, value.g, value.b ); break; case "fv1": // flat array of floats (JS or typed array) _gl.uniform1fv( location, value ); break; case "fv": // flat array of floats with 3 x N size (JS or typed array) _gl.uniform3fv( location, value ); break; case "v2v": // array of THREE.Vector2 if ( ! uniform._array ) { uniform._array = new Float32Array( 2 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 2; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; } _gl.uniform2fv( location, uniform._array ); break; case "v3v": // array of THREE.Vector3 if ( ! uniform._array ) { uniform._array = new Float32Array( 3 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 3; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; uniform._array[ offset + 2 ] = value[ i ].z; } _gl.uniform3fv( location, uniform._array ); break; case "v4v": // array of THREE.Vector4 if ( ! uniform._array ) { uniform._array = new Float32Array( 4 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 4; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; uniform._array[ offset + 2 ] = value[ i ].z; uniform._array[ offset + 3 ] = value[ i ].w; } _gl.uniform4fv( location, uniform._array ); break; case "m4": // single THREE.Matrix4 if ( ! uniform._array ) { uniform._array = new Float32Array( 16 ); } value.flattenToArray( uniform._array ); _gl.uniformMatrix4fv( location, false, uniform._array ); break; case "m4v": // array of THREE.Matrix4 if ( ! uniform._array ) { uniform._array = new Float32Array( 16 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); } _gl.uniformMatrix4fv( location, false, uniform._array ); break; case "t": // single THREE.Texture (2d or cube) _gl.uniform1i( location, value ); texture = uniform.texture; if ( !texture ) continue; if ( texture.image instanceof Array && texture.image.length === 6 ) { setCubeTexture( texture, value ); } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { setCubeTextureDynamic( texture, value ); } else { _this.setTexture( texture, value ); } break; case "tv": // array of THREE.Texture (2d) if ( ! uniform._array ) { uniform._array = []; for( i = 0, il = uniform.texture.length; i < il; i ++ ) { uniform._array[ i ] = value + i; } } _gl.uniform1iv( location, uniform._array ); for( i = 0, il = uniform.texture.length; i < il; i ++ ) { texture = uniform.texture[ i ]; if ( !texture ) continue; _this.setTexture( texture, uniform._array[ i ] ); } break; } } }; function setupMatrices ( object, camera ) { object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld); object._normalMatrix.getInverse( object._modelViewMatrix ); object._normalMatrix.transpose(); }; function setupLights ( program, lights ) { var l, ll, light, n, r = 0, g = 0, b = 0, color, position, intensity, distance, zlights = _lights, dcolors = zlights.directional.colors, dpositions = zlights.directional.positions, pcolors = zlights.point.colors, ppositions = zlights.point.positions, pdistances = zlights.point.distances, scolors = zlights.spot.colors, spositions = zlights.spot.positions, sdistances = zlights.spot.distances, sdirections = zlights.spot.directions, sangles = zlights.spot.angles, sexponents = zlights.spot.exponents, dlength = 0, plength = 0, slength = 0, doffset = 0, poffset = 0, soffset = 0; for ( l = 0, ll = lights.length; l < ll; l ++ ) { light = lights[ l ]; if ( light.onlyShadow ) continue; color = light.color; intensity = light.intensity; distance = light.distance; if ( light instanceof THREE.AmbientLight ) { if ( _this.gammaInput ) { r += color.r * color.r; g += color.g * color.g; b += color.b * color.b; } else { r += color.r; g += color.g; b += color.b; } } else if ( light instanceof THREE.DirectionalLight ) { doffset = dlength * 3; if ( _this.gammaInput ) { dcolors[ doffset ] = color.r * color.r * intensity * intensity; dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity; dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity; } else { dcolors[ doffset ] = color.r * intensity; dcolors[ doffset + 1 ] = color.g * intensity; dcolors[ doffset + 2 ] = color.b * intensity; } _direction.copy( light.matrixWorld.getPosition() ); _direction.subSelf( light.target.matrixWorld.getPosition() ); _direction.normalize(); dpositions[ doffset ] = _direction.x; dpositions[ doffset + 1 ] = _direction.y; dpositions[ doffset + 2 ] = _direction.z; dlength += 1; } else if( light instanceof THREE.PointLight ) { poffset = plength * 3; if ( _this.gammaInput ) { pcolors[ poffset ] = color.r * color.r * intensity * intensity; pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity; pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity; } else { pcolors[ poffset ] = color.r * intensity; pcolors[ poffset + 1 ] = color.g * intensity; pcolors[ poffset + 2 ] = color.b * intensity; } position = light.matrixWorld.getPosition(); ppositions[ poffset ] = position.x; ppositions[ poffset + 1 ] = position.y; ppositions[ poffset + 2 ] = position.z; pdistances[ plength ] = distance; plength += 1; } else if( light instanceof THREE.SpotLight ) { soffset = slength * 3; if ( _this.gammaInput ) { scolors[ soffset ] = color.r * color.r * intensity * intensity; scolors[ soffset + 1 ] = color.g * color.g * intensity * intensity; scolors[ soffset + 2 ] = color.b * color.b * intensity * intensity; } else { scolors[ soffset ] = color.r * intensity; scolors[ soffset + 1 ] = color.g * intensity; scolors[ soffset + 2 ] = color.b * intensity; } position = light.matrixWorld.getPosition(); spositions[ soffset ] = position.x; spositions[ soffset + 1 ] = position.y; spositions[ soffset + 2 ] = position.z; sdistances[ slength ] = distance; _direction.copy( position ); _direction.subSelf( light.target.matrixWorld.getPosition() ); _direction.normalize(); sdirections[ soffset ] = _direction.x; sdirections[ soffset + 1 ] = _direction.y; sdirections[ soffset + 2 ] = _direction.z; sangles[ slength ] = Math.cos( light.angle ); sexponents[ slength ] = light.exponent; slength += 1; } } // null eventual remains from removed lights // (this is to avoid if in shader) for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0; for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0; for ( l = slength * 3, ll = scolors.length; l < ll; l ++ ) scolors[ l ] = 0.0; zlights.directional.length = dlength; zlights.point.length = plength; zlights.spot.length = slength; zlights.ambient[ 0 ] = r; zlights.ambient[ 1 ] = g; zlights.ambient[ 2 ] = b; }; // GL state setting this.setFaceCulling = function ( cullFace, frontFace ) { if ( cullFace ) { if ( !frontFace || frontFace === "ccw" ) { _gl.frontFace( _gl.CCW ); } else { _gl.frontFace( _gl.CW ); } if( cullFace === "back" ) { _gl.cullFace( _gl.BACK ); } else if( cullFace === "front" ) { _gl.cullFace( _gl.FRONT ); } else { _gl.cullFace( _gl.FRONT_AND_BACK ); } _gl.enable( _gl.CULL_FACE ); } else { _gl.disable( _gl.CULL_FACE ); } }; this.setObjectFaces = function ( object ) { if ( _oldDoubleSided !== object.doubleSided ) { if ( object.doubleSided ) { _gl.disable( _gl.CULL_FACE ); } else { _gl.enable( _gl.CULL_FACE ); } _oldDoubleSided = object.doubleSided; } if ( _oldFlipSided !== object.flipSided ) { if ( object.flipSided ) { _gl.frontFace( _gl.CW ); } else { _gl.frontFace( _gl.CCW ); } _oldFlipSided = object.flipSided; } }; this.setDepthTest = function ( depthTest ) { if ( _oldDepthTest !== depthTest ) { if ( depthTest ) { _gl.enable( _gl.DEPTH_TEST ); } else { _gl.disable( _gl.DEPTH_TEST ); } _oldDepthTest = depthTest; } }; this.setDepthWrite = function ( depthWrite ) { if ( _oldDepthWrite !== depthWrite ) { _gl.depthMask( depthWrite ); _oldDepthWrite = depthWrite; } }; function setLineWidth ( width ) { if ( width !== _oldLineWidth ) { _gl.lineWidth( width ); _oldLineWidth = width; } }; function setPolygonOffset ( polygonoffset, factor, units ) { if ( _oldPolygonOffset !== polygonoffset ) { if ( polygonoffset ) { _gl.enable( _gl.POLYGON_OFFSET_FILL ); } else { _gl.disable( _gl.POLYGON_OFFSET_FILL ); } _oldPolygonOffset = polygonoffset; } if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) { _gl.polygonOffset( factor, units ); _oldPolygonOffsetFactor = factor; _oldPolygonOffsetUnits = units; } }; this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) { if ( blending !== _oldBlending ) { switch ( blending ) { case THREE.NoBlending: _gl.disable( _gl.BLEND ); break; case THREE.AdditiveBlending: _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); break; case THREE.SubtractiveBlending: // TODO: Find blendFuncSeparate() combination _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR ); break; case THREE.MultiplyBlending: // TODO: Find blendFuncSeparate() combination _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR ); break; case THREE.CustomBlending: _gl.enable( _gl.BLEND ); break; default: _gl.enable( _gl.BLEND ); _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD ); _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA ); break; } _oldBlending = blending; } if ( blending === THREE.CustomBlending ) { if ( blendEquation !== _oldBlendEquation ) { _gl.blendEquation( paramThreeToGL( blendEquation ) ); _oldBlendEquation = blendEquation; } if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) { _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) ); _oldBlendSrc = blendSrc; _oldBlendDst = blendDst; } } else { _oldBlendEquation = null; _oldBlendSrc = null; _oldBlendDst = null; } }; // Shaders function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) { var p, pl, program, code; var chunks = []; // Generate code if ( shaderID ) { chunks.push( shaderID ); } else { chunks.push( fragmentShader ); chunks.push( vertexShader ); } for ( p in parameters ) { chunks.push( p ); chunks.push( parameters[ p ] ); } code = chunks.join(); // Check if code has been already compiled for ( p = 0, pl = _programs.length; p < pl; p ++ ) { if ( _programs[ p ].code === code ) { // console.log( "Code already compiled." /*: \n\n" + code*/ ); return _programs[ p ].program; } } //console.log( "building new program " ); // program = _gl.createProgram(); var prefix_vertex = [ "precision " + _precision + " float;", ( _maxVertexTextures > 0 ) ? "#define VERTEX_TEXTURES" : "", _this.gammaInput ? "#define GAMMA_INPUT" : "", _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "", "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, "#define MAX_SHADOWS " + parameters.maxShadows, "#define MAX_BONES " + parameters.maxBones, parameters.map ? "#define USE_MAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.vertexColors ? "#define USE_COLOR" : "", parameters.skinning ? "#define USE_SKINNING" : "", parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", parameters.morphNormals ? "#define USE_MORPHNORMALS" : "", parameters.perPixel ? "#define PHONG_PER_PIXEL" : "", parameters.wrapAround ? "#define WRAP_AROUND" : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "", parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", "uniform mat4 objectMatrix;", "uniform mat4 modelViewMatrix;", "uniform mat4 projectionMatrix;", "uniform mat4 viewMatrix;", "uniform mat3 normalMatrix;", "uniform vec3 cameraPosition;", "attribute vec3 position;", "attribute vec3 normal;", "attribute vec2 uv;", "attribute vec2 uv2;", "#ifdef USE_COLOR", "attribute vec3 color;", "#endif", "#ifdef USE_MORPHTARGETS", "attribute vec3 morphTarget0;", "attribute vec3 morphTarget1;", "attribute vec3 morphTarget2;", "attribute vec3 morphTarget3;", "#ifdef USE_MORPHNORMALS", "attribute vec3 morphNormal0;", "attribute vec3 morphNormal1;", "attribute vec3 morphNormal2;", "attribute vec3 morphNormal3;", "#else", "attribute vec3 morphTarget4;", "attribute vec3 morphTarget5;", "attribute vec3 morphTarget6;", "attribute vec3 morphTarget7;", "#endif", "#endif", "#ifdef USE_SKINNING", "attribute vec4 skinVertexA;", "attribute vec4 skinVertexB;", "attribute vec4 skinIndex;", "attribute vec4 skinWeight;", "#endif", "" ].join("\n"); var prefix_fragment = [ "precision " + _precision + " float;", "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, "#define MAX_SHADOWS " + parameters.maxShadows, parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "", _this.gammaInput ? "#define GAMMA_INPUT" : "", _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "", ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "", ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "", parameters.map ? "#define USE_MAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.vertexColors ? "#define USE_COLOR" : "", parameters.metal ? "#define METAL" : "", parameters.perPixel ? "#define PHONG_PER_PIXEL" : "", parameters.wrapAround ? "#define WRAP_AROUND" : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "", parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", "uniform mat4 viewMatrix;", "uniform vec3 cameraPosition;", "" ].join("\n"); _gl.attachShader( program, getShader( "fragment", prefix_fragment + fragmentShader ) ); _gl.attachShader( program, getShader( "vertex", prefix_vertex + vertexShader ) ); _gl.linkProgram( program ); if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) { console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" ); } //console.log( prefix_fragment + fragmentShader ); //console.log( prefix_vertex + vertexShader ); program.uniforms = {}; program.attributes = {}; var identifiers, u, a, i; // cache uniform locations identifiers = [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition', 'boneGlobalMatrices', 'morphTargetInfluences' ]; for ( u in uniforms ) { identifiers.push( u ); } cacheUniformLocations( program, identifiers ); // cache attributes locations identifiers = [ "position", "normal", "uv", "uv2", "tangent", "color", "skinVertexA", "skinVertexB", "skinIndex", "skinWeight" ]; for ( i = 0; i < parameters.maxMorphTargets; i ++ ) { identifiers.push( "morphTarget" + i ); } for ( i = 0; i < parameters.maxMorphNormals; i ++ ) { identifiers.push( "morphNormal" + i ); } for ( a in attributes ) { identifiers.push( a ); } cacheAttributeLocations( program, identifiers ); program.id = _programs.length; _programs.push( { program: program, code: code } ); _this.info.memory.programs = _programs.length; return program; }; // Shader parameters cache function cacheUniformLocations ( program, identifiers ) { var i, l, id; for( i = 0, l = identifiers.length; i < l; i ++ ) { id = identifiers[ i ]; program.uniforms[ id ] = _gl.getUniformLocation( program, id ); } }; function cacheAttributeLocations ( program, identifiers ) { var i, l, id; for( i = 0, l = identifiers.length; i < l; i ++ ) { id = identifiers[ i ]; program.attributes[ id ] = _gl.getAttribLocation( program, id ); } }; function getShader ( type, string ) { var shader; if ( type === "fragment" ) { shader = _gl.createShader( _gl.FRAGMENT_SHADER ); } else if ( type === "vertex" ) { shader = _gl.createShader( _gl.VERTEX_SHADER ); } _gl.shaderSource( shader, string ); _gl.compileShader( shader ); if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) { console.error( _gl.getShaderInfoLog( shader ) ); console.error( string ); return null; } return shader; }; // Textures function isPowerOfTwo ( value ) { return ( value & ( value - 1 ) ) === 0; }; function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { if ( isImagePowerOfTwo ) { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); } else { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); } }; this.setTexture = function ( texture, slot ) { if ( texture.needsUpdate ) { if ( ! texture.__webglInit ) { texture.__webglInit = true; texture.__webglTexture = _gl.createTexture(); _this.info.memory.textures ++; } _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); var image = texture.image, isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ), glFormat = paramThreeToGL( texture.format ), glType = paramThreeToGL( texture.type ); setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); if ( texture instanceof THREE.DataTexture ) { _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); } else { _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); } if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); texture.needsUpdate = false; if ( texture.onUpdate ) texture.onUpdate(); } else { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); } }; function clampToMaxSize ( image, maxSize ) { if ( image.width <= maxSize && image.height <= maxSize ) { return image; } // Warning: Scaling through the canvas will only work with images that use // premultiplied alpha. var maxDimension = Math.max( image.width, image.height ); var newWidth = Math.floor( image.width * maxSize / maxDimension ); var newHeight = Math.floor( image.height * maxSize / maxDimension ); var canvas = document.createElement( 'canvas' ); canvas.width = newWidth; canvas.height = newHeight; var ctx = canvas.getContext( "2d" ); ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight ); return canvas; } function setCubeTexture ( texture, slot ) { if ( texture.image.length === 6 ) { if ( texture.needsUpdate ) { if ( ! texture.image.__webglTextureCube ) { texture.image.__webglTextureCube = _gl.createTexture(); } _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); var cubeImage = []; for ( var i = 0; i < 6; i ++ ) { if ( _this.autoScaleCubemaps ) { cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); } else { cubeImage[ i ] = texture.image[ i ]; } } var image = cubeImage[ 0 ], isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ), glFormat = paramThreeToGL( texture.format ), glType = paramThreeToGL( texture.type ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); for ( var i = 0; i < 6; i ++ ) { _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); } if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); texture.needsUpdate = false; if ( texture.onUpdate ) texture.onUpdate(); } else { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); } } }; function setCubeTextureDynamic ( texture, slot ) { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); }; // Render targets function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); }; function setupRenderBuffer ( renderbuffer, renderTarget ) { _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); /* For some reason this is not working. Defaulting to RGBA4. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); */ } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); } else { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); } }; this.setRenderTarget = function ( renderTarget ) { var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); if ( renderTarget && ! renderTarget.__webglFramebuffer ) { if( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; if( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; renderTarget.__webglTexture = _gl.createTexture(); // Setup texture, create render and frame buffers var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ), glFormat = paramThreeToGL( renderTarget.format ), glType = paramThreeToGL( renderTarget.type ); if ( isCube ) { renderTarget.__webglFramebuffer = []; renderTarget.__webglRenderbuffer = []; _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); for ( var i = 0; i < 6; i ++ ) { renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); } if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); } else { renderTarget.__webglFramebuffer = _gl.createFramebuffer(); renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); } // Release everything if ( isCube ) { _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); } else { _gl.bindTexture( _gl.TEXTURE_2D, null ); } _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, null); } var framebuffer, width, height, vx, vy; if ( renderTarget ) { if ( isCube ) { framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; } else { framebuffer = renderTarget.__webglFramebuffer; } width = renderTarget.width; height = renderTarget.height; vx = 0; vy = 0; } else { framebuffer = null; width = _viewportWidth; height = _viewportHeight; vx = _viewportX; vy = _viewportY; } if ( framebuffer !== _currentFramebuffer ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _gl.viewport( vx, vy, width, height ); _currentFramebuffer = framebuffer; } _currentWidth = width; _currentHeight = height; }; function updateRenderTargetMipmap ( renderTarget ) { if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); } else { _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); _gl.generateMipmap( _gl.TEXTURE_2D ); _gl.bindTexture( _gl.TEXTURE_2D, null ); } }; // Fallback filters for non-power-of-2 textures function filterFallback ( f ) { switch ( f ) { case THREE.NearestFilter: case THREE.NearestMipMapNearestFilter: case THREE.NearestMipMapLinearFilter: return _gl.NEAREST; break; case THREE.LinearFilter: case THREE.LinearMipMapNearestFilter: case THREE.LinearMipMapLinearFilter: default: return _gl.LINEAR; break; } }; // Map three.js constants to WebGL constants function paramThreeToGL ( p ) { switch ( p ) { case THREE.RepeatWrapping: return _gl.REPEAT; break; case THREE.ClampToEdgeWrapping: return _gl.CLAMP_TO_EDGE; break; case THREE.MirroredRepeatWrapping: return _gl.MIRRORED_REPEAT; break; case THREE.NearestFilter: return _gl.NEAREST; break; case THREE.NearestMipMapNearestFilter: return _gl.NEAREST_MIPMAP_NEAREST; break; case THREE.NearestMipMapLinearFilter: return _gl.NEAREST_MIPMAP_LINEAR; break; case THREE.LinearFilter: return _gl.LINEAR; break; case THREE.LinearMipMapNearestFilter: return _gl.LINEAR_MIPMAP_NEAREST; break; case THREE.LinearMipMapLinearFilter: return _gl.LINEAR_MIPMAP_LINEAR; break; case THREE.ByteType: return _gl.BYTE; break; case THREE.UnsignedByteType: return _gl.UNSIGNED_BYTE; break; case THREE.ShortType: return _gl.SHORT; break; case THREE.UnsignedShortType: return _gl.UNSIGNED_SHORT; break; case THREE.IntType: return _gl.INT; break; case THREE.UnsignedIntType: return _gl.UNSIGNED_INT; break; case THREE.FloatType: return _gl.FLOAT; break; case THREE.AlphaFormat: return _gl.ALPHA; break; case THREE.RGBFormat: return _gl.RGB; break; case THREE.RGBAFormat: return _gl.RGBA; break; case THREE.LuminanceFormat: return _gl.LUMINANCE; break; case THREE.LuminanceAlphaFormat: return _gl.LUMINANCE_ALPHA; break; case THREE.AddEquation: return _gl.FUNC_ADD; break; case THREE.SubtractEquation: return _gl.FUNC_SUBTRACT; break; case THREE.ReverseSubtractEquation: return _gl.FUNC_REVERSE_SUBTRACT; break; case THREE.ZeroFactor: return _gl.ZERO; break; case THREE.OneFactor: return _gl.ONE; break; case THREE.SrcColorFactor: return _gl.SRC_COLOR; break; case THREE.OneMinusSrcColorFactor: return _gl.ONE_MINUS_SRC_COLOR; break; case THREE.SrcAlphaFactor: return _gl.SRC_ALPHA; break; case THREE.OneMinusSrcAlphaFactor: return _gl.ONE_MINUS_SRC_ALPHA; break; case THREE.DstAlphaFactor: return _gl.DST_ALPHA; break; case THREE.OneMinusDstAlphaFactor: return _gl.ONE_MINUS_DST_ALPHA; break; case THREE.DstColorFactor: return _gl.DST_COLOR; break; case THREE.OneMinusDstColorFactor: return _gl.ONE_MINUS_DST_COLOR; break; case THREE.SrcAlphaSaturateFactor: return _gl.SRC_ALPHA_SATURATE; break; } return 0; }; // Allocations function allocateBones ( object ) { // default for when object is not specified // ( for example when prebuilding shader // to be used with multiple objects ) // // - leave some extra space for other uniforms // - limit here is ANGLE's 254 max uniform vectors // (up to 54 should be safe) var maxBones = 50; if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { maxBones = object.bones.length; } return maxBones; }; function allocateLights ( lights ) { var l, ll, light, dirLights, pointLights, spotLights, maxDirLights, maxPointLights, maxSpotLights; dirLights = pointLights = spotLights = maxDirLights = maxPointLights = maxSpotLights = 0; for ( l = 0, ll = lights.length; l < ll; l ++ ) { light = lights[ l ]; if ( light.onlyShadow ) continue; if ( light instanceof THREE.DirectionalLight ) dirLights ++; if ( light instanceof THREE.PointLight ) pointLights ++; if ( light instanceof THREE.SpotLight ) spotLights ++; } if ( ( pointLights + spotLights + dirLights ) <= _maxLights ) { maxDirLights = dirLights; maxPointLights = pointLights; maxSpotLights = spotLights; } else { maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) ); maxPointLights = _maxLights - maxDirLights; maxSpotLights = maxPointLights; // this is not really correct } return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights }; }; function allocateShadows ( lights ) { var l, ll, light, maxShadows = 0; for ( l = 0, ll = lights.length; l < ll; l++ ) { light = lights[ l ]; if ( ! light.castShadow ) continue; if ( light instanceof THREE.SpotLight ) maxShadows ++; if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; } return maxShadows; }; // Initialization function initGL () { var gl; try { if ( ! ( gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) { throw 'Error creating WebGL context.'; } } catch ( error ) { console.error( error ); } if ( ! gl.getExtension( 'OES_texture_float' ) ) { console.log( 'THREE.WebGLRenderer: Float textures not supported.' ); } return gl; }; function setDefaultGLState () { _gl.clearColor( 0, 0, 0, 1 ); _gl.clearDepth( 1 ); _gl.clearStencil( 0 ); _gl.enable( _gl.DEPTH_TEST ); _gl.depthFunc( _gl.LEQUAL ); _gl.frontFace( _gl.CCW ); _gl.cullFace( _gl.BACK ); _gl.enable( _gl.CULL_FACE ); _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); }; // default plugins (order is important) this.shadowMapPlugin = new THREE.ShadowMapPlugin(); this.addPrePlugin( this.shadowMapPlugin ); this.addPostPlugin( new THREE.SpritePlugin() ); this.addPostPlugin( new THREE.LensFlarePlugin() ); };
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var Canvas_1 = require("./Canvas"); var EventListeners_1 = require("./Utils/EventListeners"); var Particles_1 = require("./Particles"); var Retina_1 = require("./Retina"); var ShapeType_1 = require("../Enums/ShapeType"); var PolygonMask_1 = require("./PolygonMask"); var FrameManager_1 = require("./FrameManager"); var Options_1 = require("./Options/Options"); var Utils_1 = require("./Utils/Utils"); var Presets_1 = require("./Utils/Presets"); var Emitter_1 = require("./Emitter"); var Absorber_1 = require("./Absorber"); var Container = (function () { function Container(id, params) { var presets = []; for (var _i = 2; _i < arguments.length; _i++) { presets[_i - 2] = arguments[_i]; } this.started = false; this.destroyed = false; this.id = id; this.paused = true; this.sourceOptions = params; this.lastFrameTime = 0; this.pageHidden = false; this.retina = new Retina_1.Retina(this); this.canvas = new Canvas_1.Canvas(this); this.particles = new Particles_1.Particles(this); this.polygon = new PolygonMask_1.PolygonMask(this); this.drawer = new FrameManager_1.FrameManager(this); this.interactivity = { mouse: {}, }; this.images = []; this.bubble = {}; this.repulse = { particles: [] }; this.emitters = []; this.absorbers = []; this.options = new Options_1.Options(); for (var _a = 0, presets_1 = presets; _a < presets_1.length; _a++) { var preset = presets_1[_a]; this.options.load(Presets_1.Presets.getPreset(preset)); } if (this.sourceOptions) { this.options.load(this.sourceOptions); } this.eventListeners = new EventListeners_1.EventListeners(this); } Container.requestFrame = function (callback) { return window.customRequestAnimationFrame(callback); }; Container.cancelAnimation = function (handle) { window.cancelAnimationFrame(handle); }; Container.prototype.play = function () { var _this = this; if (this.paused) { this.lastFrameTime = performance.now(); this.paused = false; for (var _i = 0, _a = this.emitters; _i < _a.length; _i++) { var emitter = _a[_i]; emitter.start(); } } this.drawAnimationFrame = Container.requestFrame(function (t) { return _this.drawer.nextFrame(t); }); }; Container.prototype.pause = function () { if (this.drawAnimationFrame !== undefined) { for (var _i = 0, _a = this.emitters; _i < _a.length; _i++) { var emitter = _a[_i]; emitter.stop(); } Container.cancelAnimation(this.drawAnimationFrame); delete this.drawAnimationFrame; this.paused = true; } }; Container.prototype.densityAutoParticles = function () { if (!(this.canvas.element && this.options.particles.number.density.enable)) { return; } var area = this.canvas.element.width * this.canvas.element.height / 1000; if (this.retina.isRetina) { area /= this.retina.pixelRatio * 2; } var optParticlesNumber = this.options.particles.number.value; var density = this.options.particles.number.density.area; var particlesNumber = area * optParticlesNumber / density; var particlesCount = this.particles.count; if (particlesCount < particlesNumber) { this.particles.push(Math.abs(particlesNumber - particlesCount)); } else if (particlesCount > particlesNumber) { this.particles.removeQuantity(particlesCount - particlesNumber); } }; Container.prototype.destroy = function () { this.stop(); this.retina.reset(); this.canvas.destroy(); delete this.interactivity; delete this.options; delete this.retina; delete this.canvas; delete this.particles; delete this.polygon; delete this.bubble; delete this.repulse; delete this.images; delete this.drawer; delete this.eventListeners; this.destroyed = true; }; Container.prototype.exportImg = function (callback) { this.exportImage(callback); }; Container.prototype.exportImage = function (callback, type, quality) { var _a; return (_a = this.canvas.element) === null || _a === void 0 ? void 0 : _a.toBlob(callback, type !== null && type !== void 0 ? type : "image/png", quality); }; Container.prototype.exportConfiguration = function () { return JSON.stringify(this.options, undefined, 2); }; Container.prototype.refresh = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: this.stop(); return [4, this.start()]; case 1: _a.sent(); return [2]; } }); }); }; Container.prototype.stop = function () { if (!this.started) { return; } this.started = false; this.eventListeners.removeListeners(); this.pause(); this.images = []; this.particles.clear(); this.retina.reset(); this.canvas.clear(); this.polygon.reset(); this.emitters = []; this.absorbers = []; delete this.particles.lineLinkedColor; }; Container.prototype.start = function () { return __awaiter(this, void 0, void 0, function () { var _i, _a, character, character, _b, _c, optionsImage; return __generator(this, function (_d) { switch (_d.label) { case 0: if (this.started) { return [2]; } this.started = true; this.eventListeners.addListeners(); return [4, this.polygon.init()]; case 1: _d.sent(); if (!(Utils_1.Utils.isInArray(ShapeType_1.ShapeType.char, this.options.particles.shape.type) || Utils_1.Utils.isInArray(ShapeType_1.ShapeType.character, this.options.particles.shape.type))) return [3, 8]; if (!(this.options.particles.shape.character instanceof Array)) return [3, 6]; _i = 0, _a = this.options.particles.shape.character; _d.label = 2; case 2: if (!(_i < _a.length)) return [3, 5]; character = _a[_i]; return [4, Utils_1.Utils.loadFont(character)]; case 3: _d.sent(); _d.label = 4; case 4: _i++; return [3, 2]; case 5: return [3, 8]; case 6: character = this.options.particles.shape.character; if (!(character !== undefined)) return [3, 8]; return [4, Utils_1.Utils.loadFont(character)]; case 7: _d.sent(); _d.label = 8; case 8: if (!Utils_1.Utils.isInArray(ShapeType_1.ShapeType.image, this.options.particles.shape.type)) return [3, 15]; if (!(this.options.particles.shape.image instanceof Array)) return [3, 13]; _b = 0, _c = this.options.particles.shape.image; _d.label = 9; case 9: if (!(_b < _c.length)) return [3, 12]; optionsImage = _c[_b]; return [4, this.loadImageShape(optionsImage)]; case 10: _d.sent(); _d.label = 11; case 11: _b++; return [3, 9]; case 12: return [3, 15]; case 13: return [4, this.loadImageShape(this.options.particles.shape.image)]; case 14: _d.sent(); _d.label = 15; case 15: this.init(); this.play(); return [2]; } }); }); }; Container.prototype.loadImageShape = function (imageShape) { return __awaiter(this, void 0, void 0, function () { var _a, _b, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: _d.trys.push([0, 2, , 3]); _b = (_a = this.images).push; return [4, Utils_1.Utils.loadImage(imageShape)]; case 1: _b.apply(_a, [_d.sent()]); return [3, 3]; case 2: _c = _d.sent(); return [3, 3]; case 3: return [2]; } }); }); }; Container.prototype.init = function () { this.retina.init(); this.canvas.init(); this.particles.init(); if (this.options.emitters instanceof Array) { for (var _i = 0, _a = this.options.emitters; _i < _a.length; _i++) { var emitterOptions = _a[_i]; var emitter = new Emitter_1.Emitter(this, emitterOptions); this.emitters.push(emitter); } } else { var emitterOptions = this.options.emitters; var emitter = new Emitter_1.Emitter(this, emitterOptions); this.emitters.push(emitter); } if (this.options.absorbers instanceof Array) { for (var _b = 0, _c = this.options.absorbers; _b < _c.length; _b++) { var absorberOptions = _c[_b]; var absorber = new Absorber_1.Absorber(this, absorberOptions); this.absorbers.push(absorber); } } else { var absorberOptions = this.options.absorbers; var absorber = new Absorber_1.Absorber(this, absorberOptions); this.absorbers.push(absorber); } this.densityAutoParticles(); }; return Container; }()); exports.Container = Container;
require('./shim'); require('./src/core.dict'); require('./src/core.$for'); require('./src/core.delay'); require('./src/core.binding'); require('./src/core.object'); require('./src/core.array'); require('./src/core.number'); require('./src/core.string'); require('./src/core.date'); require('./src/core.global'); require('./src/core.log'); module.exports = global.core;
// Native Javascript for Bootstrap 3 | Bulk require // by dnp_theme // Require/npm/Bower by Ingwie Phoenix /** @file This file bulk-requires all the native components and gives it back as the exports. Due to the NodeJS-y environment, each entry is a factory function. Once called, it expects a global `window` and `document` object to be present. I.e.: ```javascript global.window = require("web-like-environment"); global.document = window.document; // Now, window and document are available. var modal = require("bootstrap.native").modal(); ``` */ module.exports = { affix: require("./lib/affix-native"), alert: require("./lib/alert-native"), button: require("./lib/button-native"), carousel: require("./lib/carousel-native"), collapse: require("./lib/collapse-native"), dropdown: require("./lib/dropdown-native"), modal: require("./lib/modal-native"), popover: require("./lib/popover-native"), scrollspy: require("./lib/scrollspy-native"), tab: require("./lib/tab-native"), tooltip: require("./lib/tooltip-native") };
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import { isFragment } from 'react-is'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Typography from '../Typography'; import BreadcrumbCollapsed from './BreadcrumbCollapsed'; export const styles = { /* Styles applied to the root element. */ root: {}, /* Styles applied to the ol element. */ ol: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', padding: 0, margin: 0, listStyle: 'none' }, /* Styles applied to the li element. */ li: {}, /* Styles applied to the separator element. */ separator: { display: 'flex', userSelect: 'none', marginLeft: 8, marginRight: 8 } }; function insertSeparators(items, className, separator) { return items.reduce((acc, current, index) => { if (index < items.length - 1) { acc = acc.concat(current, React.createElement("li", { "aria-hidden": true, key: `separator-${index}`, className: className }, separator)); } else { acc.push(current); } return acc; }, []); } const Breadcrumbs = React.forwardRef(function Breadcrumbs(props, ref) { const { children, classes, className, component: Component = 'nav', expandText = 'Show path', itemsAfterCollapse = 1, itemsBeforeCollapse = 1, maxItems = 8, separator = '/' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "component", "expandText", "itemsAfterCollapse", "itemsBeforeCollapse", "maxItems", "separator"]); const [expanded, setExpanded] = React.useState(false); const renderItemsBeforeAndAfter = allItems => { const handleClickExpand = () => { setExpanded(true); }; // This defends against someone passing weird input, to ensure that if all // items would be shown anyway, we just show all items without the EllipsisItem if (itemsBeforeCollapse + itemsAfterCollapse >= allItems.length) { if (process.env.NODE_ENV !== 'production') { console.error(['Material-UI: you have provided an invalid combination of props to the Breadcrumbs.', `itemsAfterCollapse={${itemsAfterCollapse}} + itemsBeforeCollapse={${itemsBeforeCollapse}} >= maxItems={${maxItems}}`].join('\n')); } return allItems; } return [...allItems.slice(0, itemsBeforeCollapse), React.createElement(BreadcrumbCollapsed, { "aria-label": expandText, key: "ellipsis", onClick: handleClickExpand }), ...allItems.slice(allItems.length - itemsAfterCollapse, allItems.length)]; }; const allItems = React.Children.toArray(children).filter(child => { if (process.env.NODE_ENV !== 'production') { if (isFragment(child)) { console.error(["Material-UI: the Breadcrumbs component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } return React.isValidElement(child); }).map((child, index) => React.createElement("li", { className: classes.li, key: `child-${index}` }, child)); return React.createElement(Typography, _extends({ ref: ref, component: Component, color: "textSecondary", className: clsx(classes.root, className) }, other), React.createElement("ol", { className: classes.ol }, insertSeparators(expanded || maxItems && allItems.length <= maxItems ? allItems : renderItemsBeforeAndAfter(allItems), classes.separator, separator))); }); process.env.NODE_ENV !== "production" ? Breadcrumbs.propTypes = { /** * The breadcrumb children. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. * By default, it maps the variant to a good default headline component. */ component: PropTypes.elementType, /** * Override the default label for the expand button. * * For localization purposes, you can use the provided [translations](/guides/localization/). */ expandText: PropTypes.string, /** * If max items is exceeded, the number of items to show after the ellipsis. */ itemsAfterCollapse: PropTypes.number, /** * If max items is exceeded, the number of items to show before the ellipsis. */ itemsBeforeCollapse: PropTypes.number, /** * Specifies the maximum number of breadcrumbs to display. When there are more * than the maximum number, only the first `itemsBeforeCollapse` and last `itemsAfterCollapse` * will be shown, with an ellipsis in between. */ maxItems: PropTypes.number, /** * Custom separator node. */ separator: PropTypes.node } : void 0; export default withStyles(styles, { name: 'MuiBreadcrumbs' })(Breadcrumbs);
var _ = require('lodash'); var colors = require('cli-color-keywords')(); var diff = require('diff'); var toInt = require('to-int'); exports.getDiff = function(before, after) { var cmp = diff.diffWords(before.trim(), after.trim()); return cmp.map( function(item, index, collection) { var val = item.value; var color = ''; if (item.added) { color = 'green'; } else if (item.removed) { color = 'error'; } if (color) { val = colors[color](val); } return val; } ).join(''); }; exports.prefix = function(str, prefix) { str = String(str); if (str.indexOf(prefix) !== 0) { str = prefix + str; } return str; }; exports._ = _; exports.STR_SUB_HAS_CHANGED = '"{0}" has changed to "{1}"'; exports.iterateLines = function(contents, iterator) { var lines = contents.split('\n'); return lines.map(iterator).join('\n'); }; exports.getLineOffset = function(num) { return _.isNumber(num) ? num : toInt; };
( function () { 'use strict'; var OSG = window.OSG; var osgViewer = OSG.osgViewer; var osg = OSG.osg; var osgDB = OSG.osgDB; function colorFloatTo255( color ) { return [ color[ 0 ] * 255.0, color[ 1 ] * 255.0, color[ 2 ] * 255.0 ]; } function color255ToFloat( color ) { return [ color[ 0 ] / 255.0, color[ 1 ] / 255.0, color[ 2 ] / 255.0 ]; } var Example = function () {}; Example.prototype = { // the root node scene: undefined, model: undefined, ground: new window.Ground(), scale: 1.0, debugDiv: document.getElementById( 'debug' ), gui: undefined, params: undefined, viewer: undefined, run: function () { this.cacheURLs = {}; var canvas = document.getElementById( 'View' ); this.viewer = new osgViewer.Viewer( canvas ); this.viewer.init(); this.viewer.getCamera().setClearColor( [ 0.005, 0.005, 0.005, 1.0 ] ); this.scene = new osg.Node(); this.scene.addChild( this.ground ); this.viewer.setSceneData( this.scene ); this.viewer.setupManipulator(); this.viewer.run(); this.initGui(); this.changeModel( 'file.osgjs' ); }, initGui: function () { this.gui = new window.dat.GUI(); var self = this; // config to let dat.gui change the scale this.params = { model: 'file.osgjs', adjustY: 0.001, groundColor: colorFloatTo255( self.ground.getColor() ), backgroundColor: colorFloatTo255( self.viewer.getCamera().getClearColor() ), reset: function () { self.resetHeightAndGui(); }, }; var modelController = this.gui.add( this.params, 'model', [ 'file.osgjs', 'sphere' ] ); modelController.onFinishChange( function ( value ) { self.changeModel( value ); } ); var adjustYController = this.gui.add( this.params, 'adjustY', -1.0, 1.0 ); adjustYController.onChange( function ( value ) { self.ground.setNormalizedHeight( value ); } ); this.gui.add( this.params, 'reset' ).name( 'Reset ground height' ); var colorController = this.gui.addColor( this.params, 'groundColor' ); colorController.onChange( function ( color ) { self.ground.setColor( color255ToFloat( color ) ); } ); var backgroundColorController = this.gui.addColor( this.params, 'backgroundColor' ); backgroundColorController.onChange( function ( color ) { var temp = [ 0.0, 0.0, 0.0 ]; temp[ 0 ] = Math.pow( color[ 0 ] / 255.0, 2.2 ); temp[ 1 ] = Math.pow( color[ 1 ] / 255.0, 2.2 ); temp[ 2 ] = Math.pow( color[ 2 ] / 255.0, 2.2 ); self.viewer.getCamera().setClearColor( temp ); } ); }, resetHeightAndGui: function () { this.ground.setGroundFromModel( this.model ); this.params.adjustY = this.ground.getNormalizedHeight(); // Update gui for ( var i in this.gui.__controllers ) this.gui.__controllers[ i ].updateDisplay(); }, setModel: function ( model ) { this.scene.removeChild( this.model ); this.model = model; this.resetHeightAndGui(); this.scene.addChild( this.model ); this.viewer.getManipulator().computeHomePosition(); }, changeModel: function ( key ) { if ( this.cacheURLs[ key ] ) return this.setModel( this.cacheURLs[ key ] ); if ( key === 'sphere' ) { var sphere = this.cacheURLs[ key ] = osg.createTexturedSphere( 1.0, 20, 20 ); return this.setModel( sphere ); } osgDB.readNodeURL( '../media/models/material-test/' + key ).then( function ( model ) { this.cacheURLs[ key ] = model; this.setModel( model ); }.bind( this ) ); } }; window.addEventListener( 'load', function () { var example = new Example(); example.run(); }, true ); } )();
"use strict"; var bodec = require('bodec'); var treeMap = require('../lib/object-codec').treeMap; module.exports = function (repo) { var loadAs = repo.loadAs; repo.loadAs = newLoadAs; var saveAs = repo.saveAs; repo.saveAs = newSaveAs; function newLoadAs(type, hash, callback) { if (!callback) return newLoadAs.bind(repo, type, hash); var realType = type === "text" ? "blob": type === "array" ? "tree" : type; return loadAs.call(repo, realType, hash, onLoad); function onLoad(err, body, hash) { if (body === undefined) return callback(err); if (type === "text") body = bodec.toUnicode(body); if (type === "array") body = toArray(body); return callback(err, body, hash); } } function newSaveAs(type, body, callback) { if (!callback) return newSaveAs.bind(repo, type, body); type = type === "text" ? "blob": type === "array" ? "tree" : type; if (type === "blob") { if (typeof body === "string") { body = bodec.fromUnicode(body); } } else if (type === "tree") { body = normalizeTree(body); } else if (type === "commit") { body = normalizeCommit(body); } else if (type === "tag") { body = normalizeTag(body); } return saveAs.call(repo, type, body, callback); } }; function toArray(tree) { return Object.keys(tree).map(treeMap, tree); } function normalizeTree(body) { var type = body && typeof body; if (type !== "object") { throw new TypeError("Tree body must be array or object"); } var tree = {}, i, l, entry; // If array form is passed in, convert to object form. if (Array.isArray(body)) { for (i = 0, l = body.length; i < l; i++) { entry = body[i]; tree[entry.name] = { mode: entry.mode, hash: entry.hash }; } } else { var names = Object.keys(body); for (i = 0, l = names.length; i < l; i++) { var name = names[i]; entry = body[name]; tree[name] = { mode: entry.mode, hash: entry.hash }; } } return tree; } function normalizeCommit(body) { if (!body || typeof body !== "object") { throw new TypeError("Commit body must be an object"); } if (!(body.tree && body.author && body.message)) { throw new TypeError("Tree, author, and message are required for commits"); } var parents = body.parents || (body.parent ? [ body.parent ] : []); if (!Array.isArray(parents)) { throw new TypeError("Parents must be an array"); } var author = normalizePerson(body.author); var committer = body.committer ? normalizePerson(body.committer) : author; return { tree: body.tree, parents: parents, author: author, committer: committer, message: body.message }; } function normalizeTag(body) { if (!body || typeof body !== "object") { throw new TypeError("Tag body must be an object"); } if (!(body.object && body.type && body.tag && body.tagger && body.message)) { throw new TypeError("Object, type, tag, tagger, and message required"); } return { object: body.object, type: body.type, tag: body.tag, tagger: normalizePerson(body.tagger), message: body.message }; } function normalizePerson(person) { if (!person || typeof person !== "object") { throw new TypeError("Person must be an object"); } if (!person.name || !person.email) { throw new TypeError("Name and email are required for person fields"); } return { name: person.name, email: person.email, date: person.date || new Date() }; }
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.themes} object, which is used to * manage themes registration and loading. */ /** * Manages themes registration and loading. * @namespace * @augments CKEDITOR.resourceManager * @example */ CKEDITOR.themes = new CKEDITOR.resourceManager( '_source/' + // @Packager.RemoveLine 'themes/', 'theme');
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.styles = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _Collapse = _interopRequireDefault(require("../Collapse")); var _withStyles = _interopRequireDefault(require("../styles/withStyles")); var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { marginTop: 8, marginLeft: 12, // half icon paddingLeft: 8 + 12, // margin + half icon paddingRight: 8, borderLeft: "1px solid ".concat(theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]) }, /* Styles applied to the root element if `last={true}` (controlled by `Step`). */ last: { borderLeft: 'none' }, /* Styles applied to the Transition component. */ transition: {} }; }; exports.styles = styles; var StepContent = React.forwardRef(function StepContent(props, ref) { var active = props.active, alternativeLabel = props.alternativeLabel, children = props.children, classes = props.classes, className = props.className, completed = props.completed, expanded = props.expanded, last = props.last, optional = props.optional, orientation = props.orientation, _props$TransitionComp = props.TransitionComponent, TransitionComponent = _props$TransitionComp === void 0 ? _Collapse.default : _props$TransitionComp, _props$transitionDura = props.transitionDuration, transitionDurationProp = _props$transitionDura === void 0 ? 'auto' : _props$transitionDura, TransitionProps = props.TransitionProps, other = (0, _objectWithoutProperties2.default)(props, ["active", "alternativeLabel", "children", "classes", "className", "completed", "expanded", "last", "optional", "orientation", "TransitionComponent", "transitionDuration", "TransitionProps"]); if (process.env.NODE_ENV !== 'production') { if (orientation !== 'vertical') { console.error('Material-UI: <StepContent /> is only designed for use with the vertical stepper.'); } } var transitionDuration = transitionDurationProp; if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) { transitionDuration = undefined; } return React.createElement("div", (0, _extends2.default)({ className: (0, _clsx.default)(classes.root, className, last && classes.last), ref: ref }, other), React.createElement(TransitionComponent, (0, _extends2.default)({ in: active || expanded, className: classes.transition, timeout: transitionDuration, unmountOnExit: true }, TransitionProps), children)); }); process.env.NODE_ENV !== "production" ? StepContent.propTypes = { /** * @ignore * Expands the content. */ active: _propTypes.default.bool, /** * @ignore * Set internally by Step when it's supplied with the alternativeLabel prop. */ alternativeLabel: _propTypes.default.bool, /** * Step content. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object.isRequired, /** * @ignore */ className: _propTypes.default.string, /** * @ignore */ completed: _propTypes.default.bool, /** * @ignore */ expanded: _propTypes.default.bool, /** * @ignore */ last: _propTypes.default.bool, /** * @ignore * Set internally by Step when it's supplied with the optional prop. */ optional: _propTypes.default.bool, /** * @ignore */ orientation: _propTypes.default.oneOf(['horizontal', 'vertical']), /** * The component used for the transition. * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component. */ TransitionComponent: _propTypes.default.elementType, /** * Adjust the duration of the content expand transition. * Passed as a prop to the transition component. * * Set to 'auto' to automatically calculate transition time based on height. */ transitionDuration: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.shape({ enter: _propTypes.default.number, exit: _propTypes.default.number }), _propTypes.default.oneOf(['auto'])]), /** * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element. */ TransitionProps: _propTypes.default.object } : void 0; var _default = (0, _withStyles.default)(styles, { name: 'MuiStepContent' })(StepContent); exports.default = _default;
// # disallowAttributeConcatenation: `true` // // Pug must not contain any attribute concatenation. // // ```pug // //- Invalid // a(href='text ' + title) Link // //- Invalid under `'aggressive'` // a(href=text + title) Link // a(href=num1 + num2) Link // ``` var assert = require('assert'); module.exports = function () {}; module.exports.prototype = { name: 'disallowAttributeConcatenation', schema: { enum: [null, true] }, configure: function (options) { assert(options === true || options === 'aggressive', this.name + ' option requires either a true value or "aggressive". Otherwise it should be removed'); this._aggressive = options === 'aggressive'; }, lint: function (file, errors) { var _this = this; file.iterateTokensByType('attribute', function (token) { file.addErrorForConcatenation(token, errors, 'Attribute concatenation must not be used', _this._aggressive); }); } };
import { InternalHelperReference } from '../utils/references'; import { dasherize } from 'ember-runtime/system/string'; function normalizeClass({ positional, named }) { let value = positional.at(1).value(); let activeClass = named.at('activeClass').value(); let inactiveClass = named.at('inactiveClass').value(); // When using the colon syntax, evaluate the truthiness or falsiness // of the value to determine which className to return. if (activeClass || inactiveClass) { if (!!value) { return activeClass; } else { return inactiveClass; } // If value is a Boolean and true, return the dasherized property // name. } else if (value === true) { let propName = positional.at(0); // Only apply to last segment in the path. if (propName) { let segments = propName.split('.'); propName = segments[segments.length - 1]; } return dasherize(propName); // If the value is not false, undefined, or null, return the current // value of the property. } else if (value !== false && value != null) { return value; // Nothing to display. Return null so that the old class is removed // but no new class is added. } else { return null; } } export default { isInternalHelper: true, toReference(args) { return new InternalHelperReference(normalizeClass, args); } };
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var crypto = require('crypto'); var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var http = require('http'); var https = require('https'); var os = require('os'); var querystring = require('querystring'); var url = require('url'); var util = require('util'); var zlib = require('zlib'); var assert = require('assert-plus'); var backoff = require('backoff'); var KeepAliveAgent = require('keep-alive-agent'); var mime = require('mime'); var once = require('once'); var uuid = require('node-uuid'); var dtrace = require('../dtrace'); var errors = require('../errors'); ///--- Globals /* JSSTYLED */ var VERSION = JSON.parse(fs.readFileSync(require('path').normalize(__dirname + '/../../package.json'), 'utf8')).version; ///--- Helpers function cloneRetryOptions(options, defaults) { if (options === false) { return ({ minTimeout: 1, maxTimeout: 2, retries: 1 }); } assert.optionalObject(options, 'options.retry'); var r = options || {}; assert.optionalNumber(r.minTimeout, 'options.retry.minTimeout'); assert.optionalNumber(r.maxTimeout, 'options.retry.maxTimeout'); assert.optionalNumber(r.retries, 'options.retry.retries'); assert.optionalObject(defaults, 'defaults'); defaults = defaults || {}; return ({ minTimeout: r.minTimeout || defaults.minTimeout || 1000, maxTimeout: r.maxTimeout || defaults.maxTimeout || Infinity, retries: r.retries || defaults.retries || 4 }); } function defaultUserAgent() { var UA = 'restify/' + VERSION + ' (' + os.arch() + '-' + os.platform() + '; ' + 'v8/' + process.versions.v8 + '; ' + 'OpenSSL/' + process.versions.openssl + ') ' + 'node/' + process.versions.node; return (UA); } function ConnectTimeoutError(ms) { if (Error.captureStackTrace) Error.captureStackTrace(this, ConnectTimeoutError); this.message = 'connect timeout after ' + ms + 'ms'; this.name = 'ConnectTimeoutError'; } util.inherits(ConnectTimeoutError, Error); function rawRequest(opts, cb) { assert.object(opts, 'options'); assert.object(opts.log, 'options.log'); assert.func(cb, 'callback'); cb = once(cb); var id = dtrace.nextId(); var log = opts.log; var proto = opts.protocol === 'https:' ? https : http; var timer; if (opts.cert && opts.key) opts.agent = false; if (opts.connectTimeout) { timer = setTimeout(function connectTimeout() { timer = null; if (req) { req.abort(); } var err = new ConnectTimeoutError(opts.connectTimeout); dtrace._rstfy_probes['client-error'].fire(function () { return ([id, err.toString()]); }); cb(err, req); }, opts.connectTimeout); } dtrace._rstfy_probes['client-request'].fire(function () { return ([ opts.method, opts.path, opts.headers, id ]); }); var req = proto.request(opts, function onResponse(res) { clearTimeout(timer); dtrace._rstfy_probes['client-response'].fire(function () { return ([ id, res.statusCode, res.headers ]); }); log.trace({client_res: res}, 'Response received'); res.log = log; var err; if (res.statusCode >= 400) err = errors.codeToHttpError(res.statusCode); req.removeAllListeners('error'); req.removeAllListeners('socket'); req.emit('result', (err || null), res); }); req.log = log; req.on('error', function onError(err) { dtrace._rstfy_probes['client-error'].fire(function () { return ([id, (err || {}).toString()]); }); log.trace({err: err}, 'Request failed'); clearTimeout(timer); cb(err, req); if (req) { process.nextTick(function () { req.emit('result', err, null); }); } }); req.once('socket', function onSocket(socket) { if (socket.writable && !socket._connecting) { clearTimeout(timer); cb(null, req); return; } socket.once('connect', function onConnect() { clearTimeout(timer); cb(null, req); }); }); if (opts.signRequest) opts.signRequest(req); } // end `rawRequest` ///--- API function HttpClient(options) { assert.object(options, 'options'); assert.optionalObject(options.headers, 'options.headers'); assert.object(options.log, 'options.log'); assert.optionalFunc(options.signRequest, 'options.signRequest'); assert.optionalString(options.socketPath, 'options.socketPath'); assert.optionalString(options.url, 'options.url'); EventEmitter.call(this); this.agent = options.agent; this.cert = options.cert; this.connectTimeout = options.connectTimeout || false; this.headers = options.headers || {}; this.log = options.log; this.key = options.key; this.name = options.name || 'HttpClient'; this.retry = cloneRetryOptions(options.retry); this.signRequest = options.signRequest || false; this.socketPath = options.socketPath || false; this.url = options.url ? url.parse(options.url) : {}; if (options.accept) { if (options.accept.indexOf('/') === -1) options.accept = mime.lookup(options.accept); this.headers.accept = options.accept; } if (options.contentType) { if (options.contentType.indexOf('/') === -1) options.type = mime.lookup(options.contentType); this.headers['content-type'] = options.contentType; } if (options.userAgent !== false) { this.headers['user-agent'] = options.userAgent || defaultUserAgent(); } if (options.version) this.headers['accept-version'] = options.version; if (this.agent === undefined) { var Agent; var maxSockets; if (this.url.protocol === 'https:') { Agent = KeepAliveAgent.Secure; maxSockets = https.globalAgent.maxSockets; } else { Agent = KeepAliveAgent; maxSockets = http.globalAgent.maxSockets; } this.agent = new Agent({ maxSockets: maxSockets, maxKeepAliveRequests: 0, maxKeepAliveTime: 0 }); } } util.inherits(HttpClient, EventEmitter); module.exports = HttpClient; HttpClient.prototype.close = function close() { var sockets = this.agent.sockets; Object.keys((sockets || {})).forEach(function (k) { sockets[k].forEach(function (s) { s.end(); }); }); sockets = this.agent.idleSockets; Object.keys((sockets || {})).forEach(function (k) { sockets[k].forEach(function (s) { s.end(); }); }); }; HttpClient.prototype.del = function del(options, callback) { var opts = this._options('DELETE', options); return (this.read(opts, callback)); }; HttpClient.prototype.get = function get(options, callback) { var opts = this._options('GET', options); return (this.read(opts, callback)); }; HttpClient.prototype.head = function head(options, callback) { var opts = this._options('HEAD', options); return (this.read(opts, callback)); }; HttpClient.prototype.opts = function http_options(options, callback) { var _opts = this._options('OPTIONS', options); return (this.read(_opts, callback)); }; HttpClient.prototype.post = function post(options, callback) { var opts = this._options('POST', options); return (this.request(opts, callback)); }; HttpClient.prototype.put = function put(options, callback) { var opts = this._options('PUT', options); return (this.request(opts, callback)); }; HttpClient.prototype.read = function read(options, callback) { var r = this.request(options, function readRequestCallback(err, req) { if (!err) req.end(); return (callback(err, req)); }); return (r); }; HttpClient.prototype.basicAuth = function basicAuth(username, password) { if (username === false) { delete this.headers.authorization; } else { assert.string(username, 'username'); assert.string(password, 'password'); var buffer = new Buffer(username + ':' + password, 'utf8'); this.headers.authorization = 'Basic ' + buffer.toString('base64'); } return (this); }; HttpClient.prototype.request = function request(opts, cb) { assert.object(opts, 'options'); assert.func(cb, 'callback'); cb = once(cb); var call; var retry = cloneRetryOptions(opts.retry); call = backoff.call(rawRequest, opts, cb); call.setStrategy(new backoff.ExponentialStrategy({ initialDelay: retry.minTimeout, maxDelay: retry.maxTimeout })); call.failAfter(retry.retries); call.on('backoff', this.emit.bind(this, 'attempt')); call.start(); }; HttpClient.prototype._options = function (method, options) { if (typeof (options) !== 'object') options = { path: options }; var self = this; var opts = { agent: options.agent || self.agent, cert: options.cert || self.cert, connectTimeout: options.connectTimeout || self.connectTimeout, headers: options.headers || {}, key: options.key || self.key, log: options.log || self.log, method: method, path: options.path || self.path, retry: options.retry || self.retry, signRequest: options.signRequest || self.signRequest }; // Backwards compatibility with restify < 1.0 if (options.query && Object.keys(options.query).length && opts.path.indexOf('?') === -1) { opts.path += '?' + querystring.stringify(options.query); } if (this.socketPath) opts.socketPath = this.socketPath; Object.keys(self.url).forEach(function (k) { if (!opts[k]) opts[k] = self.url[k]; }); Object.keys(self.headers).forEach(function (k) { if (!opts.headers[k]) opts.headers[k] = self.headers[k]; }); if (!opts.headers.date) opts.headers.date = new Date().toUTCString(); if (method === 'GET' || method === 'HEAD' || method === 'DELETE') { if (opts.headers['content-type']) delete opts.headers['content-type']; if (opts.headers['content-md5']) delete opts.headers['content-md5']; if (opts.headers['content-length']) delete opts.headers['content-length']; if (opts.headers['transfer-encoding']) delete opts.headers['transfer-encoding']; } return (opts); };
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > Check For Statement for automatic semicolon insertion. If automatic insertion semicolon would become one of the two semicolons in the header of a For Statement. Don`t use semicolons es5id: 7.9_A6.3_T7 description: For header is (\n false \n false \n false \n) negative: SyntaxError ---*/ //CHECK#1 for( false false false ) { break; }