repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
aframevr/aframe
src/components/raycaster.js
function (length) { var data = this.data; var el = this.el; var endVec3; // Switch each time vector so line update triggered and to avoid unnecessary vector clone. endVec3 = this.lineData.end === this.lineEndVec3 ? this.otherLineEndVec3 : this.lineEndVec3; // Treat Infinity as 1000m for the line. if (length === undefined) { length = data.far === Infinity ? 1000 : data.far; } // Update the length of the line if given. `unitLineEndVec3` is the direction // given by data.direction, then we apply a scalar to give it a length. this.lineData.start = data.origin; this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length); el.setAttribute('line', this.lineData); }
javascript
function (length) { var data = this.data; var el = this.el; var endVec3; // Switch each time vector so line update triggered and to avoid unnecessary vector clone. endVec3 = this.lineData.end === this.lineEndVec3 ? this.otherLineEndVec3 : this.lineEndVec3; // Treat Infinity as 1000m for the line. if (length === undefined) { length = data.far === Infinity ? 1000 : data.far; } // Update the length of the line if given. `unitLineEndVec3` is the direction // given by data.direction, then we apply a scalar to give it a length. this.lineData.start = data.origin; this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length); el.setAttribute('line', this.lineData); }
[ "function", "(", "length", ")", "{", "var", "data", "=", "this", ".", "data", ";", "var", "el", "=", "this", ".", "el", ";", "var", "endVec3", ";", "endVec3", "=", "this", ".", "lineData", ".", "end", "===", "this", ".", "lineEndVec3", "?", "this", ".", "otherLineEndVec3", ":", "this", ".", "lineEndVec3", ";", "if", "(", "length", "===", "undefined", ")", "{", "length", "=", "data", ".", "far", "===", "Infinity", "?", "1000", ":", "data", ".", "far", ";", "}", "this", ".", "lineData", ".", "start", "=", "data", ".", "origin", ";", "this", ".", "lineData", ".", "end", "=", "endVec3", ".", "copy", "(", "this", ".", "unitLineEndVec3", ")", ".", "multiplyScalar", "(", "length", ")", ";", "el", ".", "setAttribute", "(", "'line'", ",", "this", ".", "lineData", ")", ";", "}" ]
Create or update line to give raycaster visual representation. Customize the line through through line component. We draw the line in the raycaster component to customize the line to the raycaster's origin, direction, and far. Unlike the raycaster, we create the line as a child of the object. The line will be affected by the transforms of the objects, so we don't have to calculate transforms like we do with the raycaster. @param {number} length - Length of line. Pass in to shorten the line to the intersection point. If not provided, length will default to the max length, `raycaster.far`.
[ "Create", "or", "update", "line", "to", "give", "raycaster", "visual", "representation", ".", "Customize", "the", "line", "through", "through", "line", "component", ".", "We", "draw", "the", "line", "in", "the", "raycaster", "component", "to", "customize", "the", "line", "to", "the", "raycaster", "s", "origin", "direction", "and", "far", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/raycaster.js#L362-L382
train
aframevr/aframe
src/core/schema.js
processPropertyDefinition
function processPropertyDefinition (propDefinition, componentName) { var defaultVal = propDefinition.default; var isCustomType; var propType; var typeName = propDefinition.type; // Type inference. if (!propDefinition.type) { if (defaultVal !== undefined && (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) { // Type inference. typeName = typeof defaultVal; } else if (Array.isArray(defaultVal)) { typeName = 'array'; } else { // Fall back to string. typeName = 'string'; } } else if (propDefinition.type === 'bool') { typeName = 'boolean'; } else if (propDefinition.type === 'float') { typeName = 'number'; } propType = propertyTypes[typeName]; if (!propType) { warn('Unknown property type for component `' + componentName + '`: ' + typeName); } // Fill in parse and stringify using property types. isCustomType = !!propDefinition.parse; propDefinition.parse = propDefinition.parse || propType.parse; propDefinition.stringify = propDefinition.stringify || propType.stringify; // Fill in type name. propDefinition.type = typeName; // Check that default value exists. if ('default' in propDefinition) { // Check that default values are valid. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) { warn('Default value `' + defaultVal + '` does not match type `' + typeName + '` in component `' + componentName + '`'); } } else { // Fill in default value. propDefinition.default = propType.default; } return propDefinition; }
javascript
function processPropertyDefinition (propDefinition, componentName) { var defaultVal = propDefinition.default; var isCustomType; var propType; var typeName = propDefinition.type; // Type inference. if (!propDefinition.type) { if (defaultVal !== undefined && (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) { // Type inference. typeName = typeof defaultVal; } else if (Array.isArray(defaultVal)) { typeName = 'array'; } else { // Fall back to string. typeName = 'string'; } } else if (propDefinition.type === 'bool') { typeName = 'boolean'; } else if (propDefinition.type === 'float') { typeName = 'number'; } propType = propertyTypes[typeName]; if (!propType) { warn('Unknown property type for component `' + componentName + '`: ' + typeName); } // Fill in parse and stringify using property types. isCustomType = !!propDefinition.parse; propDefinition.parse = propDefinition.parse || propType.parse; propDefinition.stringify = propDefinition.stringify || propType.stringify; // Fill in type name. propDefinition.type = typeName; // Check that default value exists. if ('default' in propDefinition) { // Check that default values are valid. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) { warn('Default value `' + defaultVal + '` does not match type `' + typeName + '` in component `' + componentName + '`'); } } else { // Fill in default value. propDefinition.default = propType.default; } return propDefinition; }
[ "function", "processPropertyDefinition", "(", "propDefinition", ",", "componentName", ")", "{", "var", "defaultVal", "=", "propDefinition", ".", "default", ";", "var", "isCustomType", ";", "var", "propType", ";", "var", "typeName", "=", "propDefinition", ".", "type", ";", "if", "(", "!", "propDefinition", ".", "type", ")", "{", "if", "(", "defaultVal", "!==", "undefined", "&&", "(", "typeof", "defaultVal", "===", "'boolean'", "||", "typeof", "defaultVal", "===", "'number'", ")", ")", "{", "typeName", "=", "typeof", "defaultVal", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "defaultVal", ")", ")", "{", "typeName", "=", "'array'", ";", "}", "else", "{", "typeName", "=", "'string'", ";", "}", "}", "else", "if", "(", "propDefinition", ".", "type", "===", "'bool'", ")", "{", "typeName", "=", "'boolean'", ";", "}", "else", "if", "(", "propDefinition", ".", "type", "===", "'float'", ")", "{", "typeName", "=", "'number'", ";", "}", "propType", "=", "propertyTypes", "[", "typeName", "]", ";", "if", "(", "!", "propType", ")", "{", "warn", "(", "'Unknown property type for component `'", "+", "componentName", "+", "'`: '", "+", "typeName", ")", ";", "}", "isCustomType", "=", "!", "!", "propDefinition", ".", "parse", ";", "propDefinition", ".", "parse", "=", "propDefinition", ".", "parse", "||", "propType", ".", "parse", ";", "propDefinition", ".", "stringify", "=", "propDefinition", ".", "stringify", "||", "propType", ".", "stringify", ";", "propDefinition", ".", "type", "=", "typeName", ";", "if", "(", "'default'", "in", "propDefinition", ")", "{", "if", "(", "!", "isCustomType", "&&", "!", "isValidDefaultValue", "(", "typeName", ",", "defaultVal", ")", ")", "{", "warn", "(", "'Default value `'", "+", "defaultVal", "+", "'` does not match type `'", "+", "typeName", "+", "'` in component `'", "+", "componentName", "+", "'`'", ")", ";", "}", "}", "else", "{", "propDefinition", ".", "default", "=", "propType", ".", "default", ";", "}", "return", "propDefinition", ";", "}" ]
Inject default value, parser, stringifier for single property. @param {object} propDefinition @param {string} componentName
[ "Inject", "default", "value", "parser", "stringifier", "for", "single", "property", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/schema.js#L52-L102
train
aframevr/aframe
src/core/schema.js
parseProperty
function parseProperty (value, propDefinition) { // Use default value if value is falsy. if (value === undefined || value === null || value === '') { value = propDefinition.default; if (Array.isArray(value)) { value = value.slice(); } } // Invoke property type parser. return propDefinition.parse(value, propDefinition.default); }
javascript
function parseProperty (value, propDefinition) { // Use default value if value is falsy. if (value === undefined || value === null || value === '') { value = propDefinition.default; if (Array.isArray(value)) { value = value.slice(); } } // Invoke property type parser. return propDefinition.parse(value, propDefinition.default); }
[ "function", "parseProperty", "(", "value", ",", "propDefinition", ")", "{", "if", "(", "value", "===", "undefined", "||", "value", "===", "null", "||", "value", "===", "''", ")", "{", "value", "=", "propDefinition", ".", "default", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "value", "=", "value", ".", "slice", "(", ")", ";", "}", "}", "return", "propDefinition", ".", "parse", "(", "value", ",", "propDefinition", ".", "default", ")", ";", "}" ]
Deserialize a single property.
[ "Deserialize", "a", "single", "property", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/schema.js#L155-L163
train
aframevr/aframe
src/core/schema.js
stringifyProperty
function stringifyProperty (value, propDefinition) { // This function stringifies but it's used in a context where // there's always second stringification pass. By returning the original // value when it's not an object we save one unnecessary call // to JSON.stringify. if (typeof value !== 'object') { return value; } // if there's no schema for the property we use standar JSON stringify if (!propDefinition || value === null) { return JSON.stringify(value); } return propDefinition.stringify(value); }
javascript
function stringifyProperty (value, propDefinition) { // This function stringifies but it's used in a context where // there's always second stringification pass. By returning the original // value when it's not an object we save one unnecessary call // to JSON.stringify. if (typeof value !== 'object') { return value; } // if there's no schema for the property we use standar JSON stringify if (!propDefinition || value === null) { return JSON.stringify(value); } return propDefinition.stringify(value); }
[ "function", "stringifyProperty", "(", "value", ",", "propDefinition", ")", "{", "if", "(", "typeof", "value", "!==", "'object'", ")", "{", "return", "value", ";", "}", "if", "(", "!", "propDefinition", "||", "value", "===", "null", ")", "{", "return", "JSON", ".", "stringify", "(", "value", ")", ";", "}", "return", "propDefinition", ".", "stringify", "(", "value", ")", ";", "}" ]
Serialize a single property.
[ "Serialize", "a", "single", "property", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/schema.js#L192-L201
train
aframevr/aframe
src/core/a-assets.js
mediaElementLoaded
function mediaElementLoaded (el) { if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') { return; } // If media specifies autoplay or preload, wait until media is completely buffered. return new Promise(function (resolve, reject) { if (el.readyState === 4) { return resolve(); } // Already loaded. if (el.error) { return reject(); } // Error. el.addEventListener('loadeddata', checkProgress, false); el.addEventListener('progress', checkProgress, false); el.addEventListener('error', reject, false); function checkProgress () { // Add up the seconds buffered. var secondsBuffered = 0; for (var i = 0; i < el.buffered.length; i++) { secondsBuffered += el.buffered.end(i) - el.buffered.start(i); } // Compare seconds buffered to media duration. if (secondsBuffered >= el.duration) { // Set in cache because we won't be needing to call three.js loader if we have. // a loaded media element. // Store video elements only. three.js loader is used for audio elements. // See assetParse too. if (el.tagName === 'VIDEO') { THREE.Cache.files[el.getAttribute('src')] = el; } resolve(); } } }); }
javascript
function mediaElementLoaded (el) { if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') { return; } // If media specifies autoplay or preload, wait until media is completely buffered. return new Promise(function (resolve, reject) { if (el.readyState === 4) { return resolve(); } // Already loaded. if (el.error) { return reject(); } // Error. el.addEventListener('loadeddata', checkProgress, false); el.addEventListener('progress', checkProgress, false); el.addEventListener('error', reject, false); function checkProgress () { // Add up the seconds buffered. var secondsBuffered = 0; for (var i = 0; i < el.buffered.length; i++) { secondsBuffered += el.buffered.end(i) - el.buffered.start(i); } // Compare seconds buffered to media duration. if (secondsBuffered >= el.duration) { // Set in cache because we won't be needing to call three.js loader if we have. // a loaded media element. // Store video elements only. three.js loader is used for audio elements. // See assetParse too. if (el.tagName === 'VIDEO') { THREE.Cache.files[el.getAttribute('src')] = el; } resolve(); } } }); }
[ "function", "mediaElementLoaded", "(", "el", ")", "{", "if", "(", "!", "el", ".", "hasAttribute", "(", "'autoplay'", ")", "&&", "el", ".", "getAttribute", "(", "'preload'", ")", "!==", "'auto'", ")", "{", "return", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "el", ".", "readyState", "===", "4", ")", "{", "return", "resolve", "(", ")", ";", "}", "if", "(", "el", ".", "error", ")", "{", "return", "reject", "(", ")", ";", "}", "el", ".", "addEventListener", "(", "'loadeddata'", ",", "checkProgress", ",", "false", ")", ";", "el", ".", "addEventListener", "(", "'progress'", ",", "checkProgress", ",", "false", ")", ";", "el", ".", "addEventListener", "(", "'error'", ",", "reject", ",", "false", ")", ";", "function", "checkProgress", "(", ")", "{", "var", "secondsBuffered", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "el", ".", "buffered", ".", "length", ";", "i", "++", ")", "{", "secondsBuffered", "+=", "el", ".", "buffered", ".", "end", "(", "i", ")", "-", "el", ".", "buffered", ".", "start", "(", "i", ")", ";", "}", "if", "(", "secondsBuffered", ">=", "el", ".", "duration", ")", "{", "if", "(", "el", ".", "tagName", "===", "'VIDEO'", ")", "{", "THREE", ".", "Cache", ".", "files", "[", "el", ".", "getAttribute", "(", "'src'", ")", "]", "=", "el", ";", "}", "resolve", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Create a Promise that resolves once the media element has finished buffering. @param {Element} el - HTMLMediaElement. @returns {Promise}
[ "Create", "a", "Promise", "that", "resolves", "once", "the", "media", "element", "has", "finished", "buffering", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-assets.js#L140-L174
train
aframevr/aframe
src/core/a-assets.js
fixUpMediaElement
function fixUpMediaElement (mediaEl) { // Cross-origin. var newMediaEl = setCrossOrigin(mediaEl); // Plays inline for mobile. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') { newMediaEl.setAttribute('playsinline', ''); newMediaEl.setAttribute('webkit-playsinline', ''); } if (newMediaEl !== mediaEl) { mediaEl.parentNode.appendChild(newMediaEl); mediaEl.parentNode.removeChild(mediaEl); } return newMediaEl; }
javascript
function fixUpMediaElement (mediaEl) { // Cross-origin. var newMediaEl = setCrossOrigin(mediaEl); // Plays inline for mobile. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') { newMediaEl.setAttribute('playsinline', ''); newMediaEl.setAttribute('webkit-playsinline', ''); } if (newMediaEl !== mediaEl) { mediaEl.parentNode.appendChild(newMediaEl); mediaEl.parentNode.removeChild(mediaEl); } return newMediaEl; }
[ "function", "fixUpMediaElement", "(", "mediaEl", ")", "{", "var", "newMediaEl", "=", "setCrossOrigin", "(", "mediaEl", ")", ";", "if", "(", "newMediaEl", ".", "tagName", "&&", "newMediaEl", ".", "tagName", ".", "toLowerCase", "(", ")", "===", "'video'", ")", "{", "newMediaEl", ".", "setAttribute", "(", "'playsinline'", ",", "''", ")", ";", "newMediaEl", ".", "setAttribute", "(", "'webkit-playsinline'", ",", "''", ")", ";", "}", "if", "(", "newMediaEl", "!==", "mediaEl", ")", "{", "mediaEl", ".", "parentNode", ".", "appendChild", "(", "newMediaEl", ")", ";", "mediaEl", ".", "parentNode", ".", "removeChild", "(", "mediaEl", ")", ";", "}", "return", "newMediaEl", ";", "}" ]
Automatically add attributes to media elements where convenient. crossorigin, playsinline.
[ "Automatically", "add", "attributes", "to", "media", "elements", "where", "convenient", ".", "crossorigin", "playsinline", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-assets.js#L180-L195
train
aframevr/aframe
src/core/a-assets.js
extractDomain
function extractDomain (url) { // Find and remove protocol (e.g., http, ftp, etc.) to get domain. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0]; // Find and remove port number. return domain.substring(0, domain.indexOf(':')); }
javascript
function extractDomain (url) { // Find and remove protocol (e.g., http, ftp, etc.) to get domain. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0]; // Find and remove port number. return domain.substring(0, domain.indexOf(':')); }
[ "function", "extractDomain", "(", "url", ")", "{", "var", "domain", "=", "url", ".", "indexOf", "(", "'://'", ")", ">", "-", "1", "?", "url", ".", "split", "(", "'/'", ")", "[", "2", "]", ":", "url", ".", "split", "(", "'/'", ")", "[", "0", "]", ";", "return", "domain", ".", "substring", "(", "0", ",", "domain", ".", "indexOf", "(", "':'", ")", ")", ";", "}" ]
Extract domain out of URL. @param {string} url @returns {string}
[ "Extract", "domain", "out", "of", "URL", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-assets.js#L236-L242
train
aframevr/aframe
src/components/cursor.js
function (evt) { // Raycast again for touch. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') { this.onMouseMove(evt); this.el.components.raycaster.checkIntersections(); evt.preventDefault(); } this.twoWayEmit(EVENTS.MOUSEDOWN); this.cursorDownEl = this.intersectedEl; }
javascript
function (evt) { // Raycast again for touch. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') { this.onMouseMove(evt); this.el.components.raycaster.checkIntersections(); evt.preventDefault(); } this.twoWayEmit(EVENTS.MOUSEDOWN); this.cursorDownEl = this.intersectedEl; }
[ "function", "(", "evt", ")", "{", "if", "(", "this", ".", "data", ".", "rayOrigin", "===", "'mouse'", "&&", "evt", ".", "type", "===", "'touchstart'", ")", "{", "this", ".", "onMouseMove", "(", "evt", ")", ";", "this", ".", "el", ".", "components", ".", "raycaster", ".", "checkIntersections", "(", ")", ";", "evt", ".", "preventDefault", "(", ")", ";", "}", "this", ".", "twoWayEmit", "(", "EVENTS", ".", "MOUSEDOWN", ")", ";", "this", ".", "cursorDownEl", "=", "this", ".", "intersectedEl", ";", "}" ]
Trigger mousedown and keep track of the mousedowned entity.
[ "Trigger", "mousedown", "and", "keep", "track", "of", "the", "mousedowned", "entity", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/cursor.js#L225-L235
train
aframevr/aframe
src/components/cursor.js
function (evt) { var currentIntersection; var cursorEl = this.el; var index; var intersectedEl; var intersection; // Select closest object, excluding the cursor. index = evt.detail.els[0] === cursorEl ? 1 : 0; intersection = evt.detail.intersections[index]; intersectedEl = evt.detail.els[index]; // If cursor is the only intersected object, ignore the event. if (!intersectedEl) { return; } // Already intersecting this entity. if (this.intersectedEl === intersectedEl) { return; } // Ignore events further away than active intersection. if (this.intersectedEl) { currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl); if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; } } // Unset current intersection. this.clearCurrentIntersection(true); this.setIntersection(intersectedEl, intersection); }
javascript
function (evt) { var currentIntersection; var cursorEl = this.el; var index; var intersectedEl; var intersection; // Select closest object, excluding the cursor. index = evt.detail.els[0] === cursorEl ? 1 : 0; intersection = evt.detail.intersections[index]; intersectedEl = evt.detail.els[index]; // If cursor is the only intersected object, ignore the event. if (!intersectedEl) { return; } // Already intersecting this entity. if (this.intersectedEl === intersectedEl) { return; } // Ignore events further away than active intersection. if (this.intersectedEl) { currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl); if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; } } // Unset current intersection. this.clearCurrentIntersection(true); this.setIntersection(intersectedEl, intersection); }
[ "function", "(", "evt", ")", "{", "var", "currentIntersection", ";", "var", "cursorEl", "=", "this", ".", "el", ";", "var", "index", ";", "var", "intersectedEl", ";", "var", "intersection", ";", "index", "=", "evt", ".", "detail", ".", "els", "[", "0", "]", "===", "cursorEl", "?", "1", ":", "0", ";", "intersection", "=", "evt", ".", "detail", ".", "intersections", "[", "index", "]", ";", "intersectedEl", "=", "evt", ".", "detail", ".", "els", "[", "index", "]", ";", "if", "(", "!", "intersectedEl", ")", "{", "return", ";", "}", "if", "(", "this", ".", "intersectedEl", "===", "intersectedEl", ")", "{", "return", ";", "}", "if", "(", "this", ".", "intersectedEl", ")", "{", "currentIntersection", "=", "this", ".", "el", ".", "components", ".", "raycaster", ".", "getIntersection", "(", "this", ".", "intersectedEl", ")", ";", "if", "(", "currentIntersection", "&&", "currentIntersection", ".", "distance", "<=", "intersection", ".", "distance", ")", "{", "return", ";", "}", "}", "this", ".", "clearCurrentIntersection", "(", "true", ")", ";", "this", ".", "setIntersection", "(", "intersectedEl", ",", "intersection", ")", ";", "}" ]
Handle intersection.
[ "Handle", "intersection", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/cursor.js#L267-L295
train
aframevr/aframe
src/core/shader.js
function (data) { this.attributes = this.initVariables(data, 'attribute'); this.uniforms = this.initVariables(data, 'uniform'); this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({ // attributes: this.attributes, uniforms: this.uniforms, vertexShader: this.vertexShader, fragmentShader: this.fragmentShader }); return this.material; }
javascript
function (data) { this.attributes = this.initVariables(data, 'attribute'); this.uniforms = this.initVariables(data, 'uniform'); this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({ // attributes: this.attributes, uniforms: this.uniforms, vertexShader: this.vertexShader, fragmentShader: this.fragmentShader }); return this.material; }
[ "function", "(", "data", ")", "{", "this", ".", "attributes", "=", "this", ".", "initVariables", "(", "data", ",", "'attribute'", ")", ";", "this", ".", "uniforms", "=", "this", ".", "initVariables", "(", "data", ",", "'uniform'", ")", ";", "this", ".", "material", "=", "new", "(", "this", ".", "raw", "?", "THREE", ".", "RawShaderMaterial", ":", "THREE", ".", "ShaderMaterial", ")", "(", "{", "uniforms", ":", "this", ".", "uniforms", ",", "vertexShader", ":", "this", ".", "vertexShader", ",", "fragmentShader", ":", "this", ".", "fragmentShader", "}", ")", ";", "return", "this", ".", "material", ";", "}" ]
Init handler. Similar to attachedCallback. Called during shader initialization and is only run once.
[ "Init", "handler", ".", "Similar", "to", "attachedCallback", ".", "Called", "during", "shader", "initialization", "and", "is", "only", "run", "once", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/shader.js#L52-L62
train
aframevr/aframe
src/extras/primitives/primitives.js
extend
function extend (base, extension) { if (isUndefined(base)) { return copy(extension); } if (isUndefined(extension)) { return copy(base); } if (isPureObject(base) && isPureObject(extension)) { return utils.extendDeep(base, extension); } return copy(extension); }
javascript
function extend (base, extension) { if (isUndefined(base)) { return copy(extension); } if (isUndefined(extension)) { return copy(base); } if (isPureObject(base) && isPureObject(extension)) { return utils.extendDeep(base, extension); } return copy(extension); }
[ "function", "extend", "(", "base", ",", "extension", ")", "{", "if", "(", "isUndefined", "(", "base", ")", ")", "{", "return", "copy", "(", "extension", ")", ";", "}", "if", "(", "isUndefined", "(", "extension", ")", ")", "{", "return", "copy", "(", "base", ")", ";", "}", "if", "(", "isPureObject", "(", "base", ")", "&&", "isPureObject", "(", "extension", ")", ")", "{", "return", "utils", ".", "extendDeep", "(", "base", ",", "extension", ")", ";", "}", "return", "copy", "(", "extension", ")", ";", "}" ]
For the base to be extensible, both objects must be pure JavaScript objects. The function assumes that base is undefined, or null or a pure object.
[ "For", "the", "base", "to", "be", "extensible", "both", "objects", "must", "be", "pure", "JavaScript", "objects", ".", "The", "function", "assumes", "that", "base", "is", "undefined", "or", "null", "or", "a", "pure", "object", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/extras/primitives/primitives.js#L108-L119
train
aframevr/aframe
src/extras/primitives/primitives.js
addComponentMapping
function addComponentMapping (componentName, mappings) { var schema = components[componentName].schema; Object.keys(schema).map(function (prop) { // Hyphenate where there is camelCase. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); // If there is a mapping collision, prefix with component name and hyphen. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; } mappings[attrName] = componentName + '.' + prop; }); }
javascript
function addComponentMapping (componentName, mappings) { var schema = components[componentName].schema; Object.keys(schema).map(function (prop) { // Hyphenate where there is camelCase. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); // If there is a mapping collision, prefix with component name and hyphen. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; } mappings[attrName] = componentName + '.' + prop; }); }
[ "function", "addComponentMapping", "(", "componentName", ",", "mappings", ")", "{", "var", "schema", "=", "components", "[", "componentName", "]", ".", "schema", ";", "Object", ".", "keys", "(", "schema", ")", ".", "map", "(", "function", "(", "prop", ")", "{", "var", "attrName", "=", "prop", ".", "replace", "(", "/", "([a-z])([A-Z])", "/", "g", ",", "'$1-$2'", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "mappings", "[", "attrName", "]", "!==", "undefined", ")", "{", "attrName", "=", "componentName", "+", "'-'", "+", "prop", ";", "}", "mappings", "[", "attrName", "]", "=", "componentName", "+", "'.'", "+", "prop", ";", "}", ")", ";", "}" ]
Add component mappings using schema.
[ "Add", "component", "mappings", "using", "schema", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/extras/primitives/primitives.js#L168-L177
train
aframevr/aframe
src/extras/primitives/primitives.js
definePrimitive
function definePrimitive (tagName, defaultComponents, mappings) { // If no initial mappings provided, start from empty map. mappings = mappings || {}; // From the default components, add mapping automagically. Object.keys(defaultComponents).map(function buildMappings (componentName) { addComponentMapping(componentName, mappings); }); // Register the primitive. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, { defaultComponents: defaultComponents, mappings: mappings })); }
javascript
function definePrimitive (tagName, defaultComponents, mappings) { // If no initial mappings provided, start from empty map. mappings = mappings || {}; // From the default components, add mapping automagically. Object.keys(defaultComponents).map(function buildMappings (componentName) { addComponentMapping(componentName, mappings); }); // Register the primitive. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, { defaultComponents: defaultComponents, mappings: mappings })); }
[ "function", "definePrimitive", "(", "tagName", ",", "defaultComponents", ",", "mappings", ")", "{", "mappings", "=", "mappings", "||", "{", "}", ";", "Object", ".", "keys", "(", "defaultComponents", ")", ".", "map", "(", "function", "buildMappings", "(", "componentName", ")", "{", "addComponentMapping", "(", "componentName", ",", "mappings", ")", ";", "}", ")", ";", "module", ".", "exports", ".", "registerPrimitive", "(", "tagName", ",", "utils", ".", "extendDeep", "(", "{", "}", ",", "null", ",", "{", "defaultComponents", ":", "defaultComponents", ",", "mappings", ":", "mappings", "}", ")", ")", ";", "}" ]
Helper to define a primitive, building mappings using a component schema.
[ "Helper", "to", "define", "a", "primitive", "building", "mappings", "using", "a", "component", "schema", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/extras/primitives/primitives.js#L182-L196
train
aframevr/aframe
src/core/propertyTypes.js
registerPropertyType
function registerPropertyType (type, defaultValue, parse, stringify) { if ('type' in propertyTypes) { error('Property type ' + type + ' is already registered.'); return; } propertyTypes[type] = { default: defaultValue, parse: parse || defaultParse, stringify: stringify || defaultStringify }; }
javascript
function registerPropertyType (type, defaultValue, parse, stringify) { if ('type' in propertyTypes) { error('Property type ' + type + ' is already registered.'); return; } propertyTypes[type] = { default: defaultValue, parse: parse || defaultParse, stringify: stringify || defaultStringify }; }
[ "function", "registerPropertyType", "(", "type", ",", "defaultValue", ",", "parse", ",", "stringify", ")", "{", "if", "(", "'type'", "in", "propertyTypes", ")", "{", "error", "(", "'Property type '", "+", "type", "+", "' is already registered.'", ")", ";", "return", ";", "}", "propertyTypes", "[", "type", "]", "=", "{", "default", ":", "defaultValue", ",", "parse", ":", "parse", "||", "defaultParse", ",", "stringify", ":", "stringify", "||", "defaultStringify", "}", ";", "}" ]
Register a parser for re-use such that when someone uses `type` in the schema, `schema.process` will set the property `parse` and `stringify`. @param {string} type - Type name. @param [defaultValue=null] - Default value to use if component does not define default value. @param {function} [parse=defaultParse] - Parse string function. @param {function} [stringify=defaultStringify] - Stringify to DOM function.
[ "Register", "a", "parser", "for", "re", "-", "use", "such", "that", "when", "someone", "uses", "type", "in", "the", "schema", "schema", ".", "process", "will", "set", "the", "property", "parse", "and", "stringify", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/propertyTypes.js#L40-L51
train
aframevr/aframe
src/core/propertyTypes.js
assetParse
function assetParse (value) { var el; var parsedUrl; // If an element was provided (e.g. canvas or video), just return it. if (typeof value !== 'string') { return value; } // Wrapped `url()` in case of data URI. parsedUrl = value.match(urlRegex); if (parsedUrl) { return parsedUrl[1]; } // ID. if (value.charAt(0) === '#') { el = document.getElementById(value.substring(1)); if (el) { // Pass through media elements. If we have the elements, we don't have to call // three.js loaders which would re-request the assets. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') { return el; } return el.getAttribute('src'); } warn('"' + value + '" asset not found.'); return; } // Non-wrapped url(). return value; }
javascript
function assetParse (value) { var el; var parsedUrl; // If an element was provided (e.g. canvas or video), just return it. if (typeof value !== 'string') { return value; } // Wrapped `url()` in case of data URI. parsedUrl = value.match(urlRegex); if (parsedUrl) { return parsedUrl[1]; } // ID. if (value.charAt(0) === '#') { el = document.getElementById(value.substring(1)); if (el) { // Pass through media elements. If we have the elements, we don't have to call // three.js loaders which would re-request the assets. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') { return el; } return el.getAttribute('src'); } warn('"' + value + '" asset not found.'); return; } // Non-wrapped url(). return value; }
[ "function", "assetParse", "(", "value", ")", "{", "var", "el", ";", "var", "parsedUrl", ";", "if", "(", "typeof", "value", "!==", "'string'", ")", "{", "return", "value", ";", "}", "parsedUrl", "=", "value", ".", "match", "(", "urlRegex", ")", ";", "if", "(", "parsedUrl", ")", "{", "return", "parsedUrl", "[", "1", "]", ";", "}", "if", "(", "value", ".", "charAt", "(", "0", ")", "===", "'#'", ")", "{", "el", "=", "document", ".", "getElementById", "(", "value", ".", "substring", "(", "1", ")", ")", ";", "if", "(", "el", ")", "{", "if", "(", "el", ".", "tagName", "===", "'CANVAS'", "||", "el", ".", "tagName", "===", "'VIDEO'", "||", "el", ".", "tagName", "===", "'IMG'", ")", "{", "return", "el", ";", "}", "return", "el", ".", "getAttribute", "(", "'src'", ")", ";", "}", "warn", "(", "'\"'", "+", "value", "+", "'\" asset not found.'", ")", ";", "return", ";", "}", "return", "value", ";", "}" ]
For general assets. @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or just string. @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or just string.
[ "For", "general", "assets", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/propertyTypes.js#L73-L101
train
aframevr/aframe
src/core/propertyTypes.js
isValidDefaultValue
function isValidDefaultValue (type, defaultVal) { if (type === 'audio' && typeof defaultVal !== 'string') { return false; } if (type === 'array' && !Array.isArray(defaultVal)) { return false; } if (type === 'asset' && typeof defaultVal !== 'string') { return false; } if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; } if (type === 'color' && typeof defaultVal !== 'string') { return false; } if (type === 'int' && typeof defaultVal !== 'number') { return false; } if (type === 'number' && typeof defaultVal !== 'number') { return false; } if (type === 'map' && typeof defaultVal !== 'string') { return false; } if (type === 'model' && typeof defaultVal !== 'string') { return false; } if (type === 'selector' && typeof defaultVal !== 'string' && defaultVal !== null) { return false; } if (type === 'selectorAll' && typeof defaultVal !== 'string' && defaultVal !== null) { return false; } if (type === 'src' && typeof defaultVal !== 'string') { return false; } if (type === 'string' && typeof defaultVal !== 'string') { return false; } if (type === 'time' && typeof defaultVal !== 'number') { return false; } if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); } if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); } if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); } return true; }
javascript
function isValidDefaultValue (type, defaultVal) { if (type === 'audio' && typeof defaultVal !== 'string') { return false; } if (type === 'array' && !Array.isArray(defaultVal)) { return false; } if (type === 'asset' && typeof defaultVal !== 'string') { return false; } if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; } if (type === 'color' && typeof defaultVal !== 'string') { return false; } if (type === 'int' && typeof defaultVal !== 'number') { return false; } if (type === 'number' && typeof defaultVal !== 'number') { return false; } if (type === 'map' && typeof defaultVal !== 'string') { return false; } if (type === 'model' && typeof defaultVal !== 'string') { return false; } if (type === 'selector' && typeof defaultVal !== 'string' && defaultVal !== null) { return false; } if (type === 'selectorAll' && typeof defaultVal !== 'string' && defaultVal !== null) { return false; } if (type === 'src' && typeof defaultVal !== 'string') { return false; } if (type === 'string' && typeof defaultVal !== 'string') { return false; } if (type === 'time' && typeof defaultVal !== 'number') { return false; } if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); } if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); } if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); } return true; }
[ "function", "isValidDefaultValue", "(", "type", ",", "defaultVal", ")", "{", "if", "(", "type", "===", "'audio'", "&&", "typeof", "defaultVal", "!==", "'string'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'array'", "&&", "!", "Array", ".", "isArray", "(", "defaultVal", ")", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'asset'", "&&", "typeof", "defaultVal", "!==", "'string'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'boolean'", "&&", "typeof", "defaultVal", "!==", "'boolean'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'color'", "&&", "typeof", "defaultVal", "!==", "'string'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'int'", "&&", "typeof", "defaultVal", "!==", "'number'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'number'", "&&", "typeof", "defaultVal", "!==", "'number'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'map'", "&&", "typeof", "defaultVal", "!==", "'string'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'model'", "&&", "typeof", "defaultVal", "!==", "'string'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'selector'", "&&", "typeof", "defaultVal", "!==", "'string'", "&&", "defaultVal", "!==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'selectorAll'", "&&", "typeof", "defaultVal", "!==", "'string'", "&&", "defaultVal", "!==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'src'", "&&", "typeof", "defaultVal", "!==", "'string'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'string'", "&&", "typeof", "defaultVal", "!==", "'string'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'time'", "&&", "typeof", "defaultVal", "!==", "'number'", ")", "{", "return", "false", ";", "}", "if", "(", "type", "===", "'vec2'", ")", "{", "return", "isValidDefaultCoordinate", "(", "defaultVal", ",", "2", ")", ";", "}", "if", "(", "type", "===", "'vec3'", ")", "{", "return", "isValidDefaultCoordinate", "(", "defaultVal", ",", "3", ")", ";", "}", "if", "(", "type", "===", "'vec4'", ")", "{", "return", "isValidDefaultCoordinate", "(", "defaultVal", ",", "4", ")", ";", "}", "return", "true", ";", "}" ]
Validate the default values in a schema to match their type. @param {string} type - Property type name. @param defaultVal - Property type default value. @returns {boolean} Whether default value is accurate given the type.
[ "Validate", "the", "default", "values", "in", "a", "schema", "to", "match", "their", "type", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/propertyTypes.js#L173-L194
train
aframevr/aframe
src/core/propertyTypes.js
isValidDefaultCoordinate
function isValidDefaultCoordinate (possibleCoordinates, dimensions) { if (possibleCoordinates === null) { return true; } if (typeof possibleCoordinates !== 'object') { return false; } if (Object.keys(possibleCoordinates).length !== dimensions) { return false; } else { var x = possibleCoordinates.x; var y = possibleCoordinates.y; var z = possibleCoordinates.z; var w = possibleCoordinates.w; if (typeof x !== 'number' || typeof y !== 'number') { return false; } if (dimensions > 2 && typeof z !== 'number') { return false; } if (dimensions > 3 && typeof w !== 'number') { return false; } } return true; }
javascript
function isValidDefaultCoordinate (possibleCoordinates, dimensions) { if (possibleCoordinates === null) { return true; } if (typeof possibleCoordinates !== 'object') { return false; } if (Object.keys(possibleCoordinates).length !== dimensions) { return false; } else { var x = possibleCoordinates.x; var y = possibleCoordinates.y; var z = possibleCoordinates.z; var w = possibleCoordinates.w; if (typeof x !== 'number' || typeof y !== 'number') { return false; } if (dimensions > 2 && typeof z !== 'number') { return false; } if (dimensions > 3 && typeof w !== 'number') { return false; } } return true; }
[ "function", "isValidDefaultCoordinate", "(", "possibleCoordinates", ",", "dimensions", ")", "{", "if", "(", "possibleCoordinates", "===", "null", ")", "{", "return", "true", ";", "}", "if", "(", "typeof", "possibleCoordinates", "!==", "'object'", ")", "{", "return", "false", ";", "}", "if", "(", "Object", ".", "keys", "(", "possibleCoordinates", ")", ".", "length", "!==", "dimensions", ")", "{", "return", "false", ";", "}", "else", "{", "var", "x", "=", "possibleCoordinates", ".", "x", ";", "var", "y", "=", "possibleCoordinates", ".", "y", ";", "var", "z", "=", "possibleCoordinates", ".", "z", ";", "var", "w", "=", "possibleCoordinates", ".", "w", ";", "if", "(", "typeof", "x", "!==", "'number'", "||", "typeof", "y", "!==", "'number'", ")", "{", "return", "false", ";", "}", "if", "(", "dimensions", ">", "2", "&&", "typeof", "z", "!==", "'number'", ")", "{", "return", "false", ";", "}", "if", "(", "dimensions", ">", "3", "&&", "typeof", "w", "!==", "'number'", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if default coordinates are valid. @param possibleCoordinates @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector. @returns {boolean} Whether coordinates are parsed correctly.
[ "Checks", "if", "default", "coordinates", "are", "valid", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/propertyTypes.js#L204-L222
train
aframevr/aframe
src/systems/tracked-controls-webvr.js
function () { var controllers = this.controllers; var gamepad; var gamepads; var i; var prevCount; gamepads = navigator.getGamepads && navigator.getGamepads(); if (!gamepads) { return; } prevCount = controllers.length; controllers.length = 0; for (i = 0; i < gamepads.length; ++i) { gamepad = gamepads[i]; if (gamepad && gamepad.pose) { controllers.push(gamepad); } } if (controllers.length !== prevCount) { this.el.emit('controllersupdated', undefined, false); } }
javascript
function () { var controllers = this.controllers; var gamepad; var gamepads; var i; var prevCount; gamepads = navigator.getGamepads && navigator.getGamepads(); if (!gamepads) { return; } prevCount = controllers.length; controllers.length = 0; for (i = 0; i < gamepads.length; ++i) { gamepad = gamepads[i]; if (gamepad && gamepad.pose) { controllers.push(gamepad); } } if (controllers.length !== prevCount) { this.el.emit('controllersupdated', undefined, false); } }
[ "function", "(", ")", "{", "var", "controllers", "=", "this", ".", "controllers", ";", "var", "gamepad", ";", "var", "gamepads", ";", "var", "i", ";", "var", "prevCount", ";", "gamepads", "=", "navigator", ".", "getGamepads", "&&", "navigator", ".", "getGamepads", "(", ")", ";", "if", "(", "!", "gamepads", ")", "{", "return", ";", "}", "prevCount", "=", "controllers", ".", "length", ";", "controllers", ".", "length", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "gamepads", ".", "length", ";", "++", "i", ")", "{", "gamepad", "=", "gamepads", "[", "i", "]", ";", "if", "(", "gamepad", "&&", "gamepad", ".", "pose", ")", "{", "controllers", ".", "push", "(", "gamepad", ")", ";", "}", "}", "if", "(", "controllers", ".", "length", "!==", "prevCount", ")", "{", "this", ".", "el", ".", "emit", "(", "'controllersupdated'", ",", "undefined", ",", "false", ")", ";", "}", "}" ]
Update controller list.
[ "Update", "controller", "list", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/tracked-controls-webvr.js#L39-L61
train
aframevr/aframe
src/utils/src-loader.js
validateSrc
function validateSrc (src, isImageCb, isVideoCb) { checkIsImage(src, function isAnImageUrl (isImage) { if (isImage) { isImageCb(src); return; } isVideoCb(src); }); }
javascript
function validateSrc (src, isImageCb, isVideoCb) { checkIsImage(src, function isAnImageUrl (isImage) { if (isImage) { isImageCb(src); return; } isVideoCb(src); }); }
[ "function", "validateSrc", "(", "src", ",", "isImageCb", ",", "isVideoCb", ")", "{", "checkIsImage", "(", "src", ",", "function", "isAnImageUrl", "(", "isImage", ")", "{", "if", "(", "isImage", ")", "{", "isImageCb", "(", "src", ")", ";", "return", ";", "}", "isVideoCb", "(", "src", ")", ";", "}", ")", ";", "}" ]
Validate a texture, either as a selector or as a URL. Detects whether `src` is pointing to an image or video and invokes the appropriate callback. `src` will be passed into the callback @params {string|Element} src - URL or media element. @params {function} isImageCb - callback if texture is an image. @params {function} isVideoCb - callback if texture is a video.
[ "Validate", "a", "texture", "either", "as", "a", "selector", "or", "as", "a", "URL", ".", "Detects", "whether", "src", "is", "pointing", "to", "an", "image", "or", "video", "and", "invokes", "the", "appropriate", "callback", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/src-loader.js#L17-L25
train
aframevr/aframe
src/utils/src-loader.js
validateCubemapSrc
function validateCubemapSrc (src, cb) { var aCubemap; var cubemapSrcRegex = ''; var i; var urls; var validatedUrls = []; for (i = 0; i < 5; i++) { cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)'; } cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)'; urls = src.match(new RegExp(cubemapSrcRegex)); // `src` is a comma-separated list of URLs. // In this case, re-use validateSrc for each side of the cube. function isImageCb (url) { validatedUrls.push(url); if (validatedUrls.length === 6) { cb(validatedUrls); } } if (urls) { for (i = 1; i < 7; i++) { validateSrc(parseUrl(urls[i]), isImageCb); } return; } // `src` is a query selector to <a-cubemap> containing six $([src])s. aCubemap = validateAndGetQuerySelector(src); if (!aCubemap) { return; } if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) { return cb(aCubemap.srcs); } // Else if aCubeMap is not a <a-cubemap>. warn('Selector "%s" does not point to <a-cubemap>', src); }
javascript
function validateCubemapSrc (src, cb) { var aCubemap; var cubemapSrcRegex = ''; var i; var urls; var validatedUrls = []; for (i = 0; i < 5; i++) { cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)'; } cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)'; urls = src.match(new RegExp(cubemapSrcRegex)); // `src` is a comma-separated list of URLs. // In this case, re-use validateSrc for each side of the cube. function isImageCb (url) { validatedUrls.push(url); if (validatedUrls.length === 6) { cb(validatedUrls); } } if (urls) { for (i = 1; i < 7; i++) { validateSrc(parseUrl(urls[i]), isImageCb); } return; } // `src` is a query selector to <a-cubemap> containing six $([src])s. aCubemap = validateAndGetQuerySelector(src); if (!aCubemap) { return; } if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) { return cb(aCubemap.srcs); } // Else if aCubeMap is not a <a-cubemap>. warn('Selector "%s" does not point to <a-cubemap>', src); }
[ "function", "validateCubemapSrc", "(", "src", ",", "cb", ")", "{", "var", "aCubemap", ";", "var", "cubemapSrcRegex", "=", "''", ";", "var", "i", ";", "var", "urls", ";", "var", "validatedUrls", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "5", ";", "i", "++", ")", "{", "cubemapSrcRegex", "+=", "'(url\\\\((?:[^\\\\)]+)\\\\),\\\\s*)'", ";", "}", "\\\\", "\\\\", "\\\\", "\\\\", "cubemapSrcRegex", "+=", "'(url\\\\((?:[^\\\\)]+)\\\\)\\\\s*)'", ";", "\\\\", "\\\\", "\\\\", "}" ]
Validates six images as a cubemap, either as selector or comma-separated URLs. @param {string} src - A selector or comma-separated image URLs. Image URLs must be wrapped by `url()`. @param {string} src - A selector or comma-separated image URLs. Image URLs must be wrapped by `url()`.
[ "Validates", "six", "images", "as", "a", "cubemap", "either", "as", "selector", "or", "comma", "-", "separated", "URLs", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/src-loader.js#L36-L72
train
aframevr/aframe
src/utils/src-loader.js
checkIsImage
function checkIsImage (src, onResult) { var request; if (src.tagName) { onResult(src.tagName === 'IMG'); return; } request = new XMLHttpRequest(); // Try to send HEAD request to check if image first. request.open('HEAD', src); request.addEventListener('load', function (event) { var contentType; if (request.status >= 200 && request.status < 300) { contentType = request.getResponseHeader('Content-Type'); if (contentType == null) { checkIsImageFallback(src, onResult); } else { if (contentType.startsWith('image')) { onResult(true); } else { onResult(false); } } } else { checkIsImageFallback(src, onResult); } request.abort(); }); request.send(); }
javascript
function checkIsImage (src, onResult) { var request; if (src.tagName) { onResult(src.tagName === 'IMG'); return; } request = new XMLHttpRequest(); // Try to send HEAD request to check if image first. request.open('HEAD', src); request.addEventListener('load', function (event) { var contentType; if (request.status >= 200 && request.status < 300) { contentType = request.getResponseHeader('Content-Type'); if (contentType == null) { checkIsImageFallback(src, onResult); } else { if (contentType.startsWith('image')) { onResult(true); } else { onResult(false); } } } else { checkIsImageFallback(src, onResult); } request.abort(); }); request.send(); }
[ "function", "checkIsImage", "(", "src", ",", "onResult", ")", "{", "var", "request", ";", "if", "(", "src", ".", "tagName", ")", "{", "onResult", "(", "src", ".", "tagName", "===", "'IMG'", ")", ";", "return", ";", "}", "request", "=", "new", "XMLHttpRequest", "(", ")", ";", "request", ".", "open", "(", "'HEAD'", ",", "src", ")", ";", "request", ".", "addEventListener", "(", "'load'", ",", "function", "(", "event", ")", "{", "var", "contentType", ";", "if", "(", "request", ".", "status", ">=", "200", "&&", "request", ".", "status", "<", "300", ")", "{", "contentType", "=", "request", ".", "getResponseHeader", "(", "'Content-Type'", ")", ";", "if", "(", "contentType", "==", "null", ")", "{", "checkIsImageFallback", "(", "src", ",", "onResult", ")", ";", "}", "else", "{", "if", "(", "contentType", ".", "startsWith", "(", "'image'", ")", ")", "{", "onResult", "(", "true", ")", ";", "}", "else", "{", "onResult", "(", "false", ")", ";", "}", "}", "}", "else", "{", "checkIsImageFallback", "(", "src", ",", "onResult", ")", ";", "}", "request", ".", "abort", "(", ")", ";", "}", ")", ";", "request", ".", "send", "(", ")", ";", "}" ]
Call back whether `src` is an image. @param {string|Element} src - URL or element that will be tested. @param {function} onResult - Callback with whether `src` is an image.
[ "Call", "back", "whether", "src", "is", "an", "image", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/src-loader.js#L91-L121
train
aframevr/aframe
src/utils/src-loader.js
validateAndGetQuerySelector
function validateAndGetQuerySelector (selector) { try { var el = document.querySelector(selector); if (!el) { warn('No element was found matching the selector: "%s"', selector); } return el; } catch (e) { // Capture exception if it's not a valid selector. warn('"%s" is not a valid selector', selector); return undefined; } }
javascript
function validateAndGetQuerySelector (selector) { try { var el = document.querySelector(selector); if (!el) { warn('No element was found matching the selector: "%s"', selector); } return el; } catch (e) { // Capture exception if it's not a valid selector. warn('"%s" is not a valid selector', selector); return undefined; } }
[ "function", "validateAndGetQuerySelector", "(", "selector", ")", "{", "try", "{", "var", "el", "=", "document", ".", "querySelector", "(", "selector", ")", ";", "if", "(", "!", "el", ")", "{", "warn", "(", "'No element was found matching the selector: \"%s\"'", ",", "selector", ")", ";", "}", "return", "el", ";", "}", "catch", "(", "e", ")", "{", "warn", "(", "'\"%s\" is not a valid selector'", ",", "selector", ")", ";", "return", "undefined", ";", "}", "}" ]
Query and validate a query selector, @param {string} selector - DOM selector. @return {object|null|undefined} Selected DOM element if exists. null if query yields no results. undefined if `selector` is not a valid selector.
[ "Query", "and", "validate", "a", "query", "selector" ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/src-loader.js#L140-L151
train
aframevr/aframe
src/systems/material.js
function (src, data, cb) { var self = this; // Canvas. if (src.tagName === 'CANVAS') { this.loadCanvas(src, data, cb); return; } // Video element. if (src.tagName === 'VIDEO') { if (!src.src && !src.srcObject && !src.childElementCount) { warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.'); } this.loadVideo(src, data, cb); return; } utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb); function loadImageCb (src) { self.loadImage(src, data, cb); } function loadVideoCb (src) { self.loadVideo(src, data, cb); } }
javascript
function (src, data, cb) { var self = this; // Canvas. if (src.tagName === 'CANVAS') { this.loadCanvas(src, data, cb); return; } // Video element. if (src.tagName === 'VIDEO') { if (!src.src && !src.srcObject && !src.childElementCount) { warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.'); } this.loadVideo(src, data, cb); return; } utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb); function loadImageCb (src) { self.loadImage(src, data, cb); } function loadVideoCb (src) { self.loadVideo(src, data, cb); } }
[ "function", "(", "src", ",", "data", ",", "cb", ")", "{", "var", "self", "=", "this", ";", "if", "(", "src", ".", "tagName", "===", "'CANVAS'", ")", "{", "this", ".", "loadCanvas", "(", "src", ",", "data", ",", "cb", ")", ";", "return", ";", "}", "if", "(", "src", ".", "tagName", "===", "'VIDEO'", ")", "{", "if", "(", "!", "src", ".", "src", "&&", "!", "src", ".", "srcObject", "&&", "!", "src", ".", "childElementCount", ")", "{", "warn", "(", "'Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.'", ")", ";", "}", "this", ".", "loadVideo", "(", "src", ",", "data", ",", "cb", ")", ";", "return", ";", "}", "utils", ".", "srcLoader", ".", "validateSrc", "(", "src", ",", "loadImageCb", ",", "loadVideoCb", ")", ";", "function", "loadImageCb", "(", "src", ")", "{", "self", ".", "loadImage", "(", "src", ",", "data", ",", "cb", ")", ";", "}", "function", "loadVideoCb", "(", "src", ")", "{", "self", ".", "loadVideo", "(", "src", ",", "data", ",", "cb", ")", ";", "}", "}" ]
Determine whether `src` is a image or video. Then try to load the asset, then call back. @param {string, or element} src - Texture URL or element. @param {string} data - Relevant texture data used for caching. @param {function} cb - Callback to pass texture to.
[ "Determine", "whether", "src", "is", "a", "image", "or", "video", ".", "Then", "try", "to", "load", "the", "asset", "then", "call", "back", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L49-L70
train
aframevr/aframe
src/systems/material.js
function (data) { if (data.src.tagName) { // Since `data.src` can be an element, parse out the string if necessary for the hash. data = utils.extendDeep({}, data); data.src = data.src.src; } return JSON.stringify(data); }
javascript
function (data) { if (data.src.tagName) { // Since `data.src` can be an element, parse out the string if necessary for the hash. data = utils.extendDeep({}, data); data.src = data.src.src; } return JSON.stringify(data); }
[ "function", "(", "data", ")", "{", "if", "(", "data", ".", "src", ".", "tagName", ")", "{", "data", "=", "utils", ".", "extendDeep", "(", "{", "}", ",", "data", ")", ";", "data", ".", "src", "=", "data", ".", "src", ".", "src", ";", "}", "return", "JSON", ".", "stringify", "(", "data", ")", ";", "}" ]
Create a hash of the material properties for texture cache key.
[ "Create", "a", "hash", "of", "the", "material", "properties", "for", "texture", "cache", "key", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L179-L186
train
aframevr/aframe
src/systems/material.js
function (material) { delete this.materials[material.uuid]; // If any textures on this material are no longer in use, dispose of them. var textureCounts = this.textureCounts; Object.keys(material) .filter(function (propName) { return material[propName] && material[propName].isTexture; }) .forEach(function (mapName) { textureCounts[material[mapName].uuid]--; if (textureCounts[material[mapName].uuid] <= 0) { material[mapName].dispose(); } }); }
javascript
function (material) { delete this.materials[material.uuid]; // If any textures on this material are no longer in use, dispose of them. var textureCounts = this.textureCounts; Object.keys(material) .filter(function (propName) { return material[propName] && material[propName].isTexture; }) .forEach(function (mapName) { textureCounts[material[mapName].uuid]--; if (textureCounts[material[mapName].uuid] <= 0) { material[mapName].dispose(); } }); }
[ "function", "(", "material", ")", "{", "delete", "this", ".", "materials", "[", "material", ".", "uuid", "]", ";", "var", "textureCounts", "=", "this", ".", "textureCounts", ";", "Object", ".", "keys", "(", "material", ")", ".", "filter", "(", "function", "(", "propName", ")", "{", "return", "material", "[", "propName", "]", "&&", "material", "[", "propName", "]", ".", "isTexture", ";", "}", ")", ".", "forEach", "(", "function", "(", "mapName", ")", "{", "textureCounts", "[", "material", "[", "mapName", "]", ".", "uuid", "]", "--", ";", "if", "(", "textureCounts", "[", "material", "[", "mapName", "]", ".", "uuid", "]", "<=", "0", ")", "{", "material", "[", "mapName", "]", ".", "dispose", "(", ")", ";", "}", "}", ")", ";", "}" ]
Stop tracking material, and dispose of any textures not being used by another material component. @param {object} material
[ "Stop", "tracking", "material", "and", "dispose", "of", "any", "textures", "not", "being", "used", "by", "another", "material", "component", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L207-L222
train
aframevr/aframe
src/systems/material.js
function (material) { var materials = this.materials; Object.keys(materials).forEach(function (uuid) { materials[uuid].needsUpdate = true; }); }
javascript
function (material) { var materials = this.materials; Object.keys(materials).forEach(function (uuid) { materials[uuid].needsUpdate = true; }); }
[ "function", "(", "material", ")", "{", "var", "materials", "=", "this", ".", "materials", ";", "Object", ".", "keys", "(", "materials", ")", ".", "forEach", "(", "function", "(", "uuid", ")", "{", "materials", "[", "uuid", "]", ".", "needsUpdate", "=", "true", ";", "}", ")", ";", "}" ]
Trigger update to all registered materials.
[ "Trigger", "update", "to", "all", "registered", "materials", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L227-L232
train
aframevr/aframe
src/systems/material.js
loadImageTexture
function loadImageTexture (src, data) { return new Promise(doLoadImageTexture); function doLoadImageTexture (resolve, reject) { var isEl = typeof src !== 'string'; function resolveTexture (texture) { setTextureProperties(texture, data); texture.needsUpdate = true; resolve(texture); } // Create texture from an element. if (isEl) { resolveTexture(new THREE.Texture(src)); return; } // Request and load texture from src string. THREE will create underlying element. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture. TextureLoader.load( src, resolveTexture, function () { /* no-op */ }, function (xhr) { error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status, xhr.statusText); } ); } }
javascript
function loadImageTexture (src, data) { return new Promise(doLoadImageTexture); function doLoadImageTexture (resolve, reject) { var isEl = typeof src !== 'string'; function resolveTexture (texture) { setTextureProperties(texture, data); texture.needsUpdate = true; resolve(texture); } // Create texture from an element. if (isEl) { resolveTexture(new THREE.Texture(src)); return; } // Request and load texture from src string. THREE will create underlying element. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture. TextureLoader.load( src, resolveTexture, function () { /* no-op */ }, function (xhr) { error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status, xhr.statusText); } ); } }
[ "function", "loadImageTexture", "(", "src", ",", "data", ")", "{", "return", "new", "Promise", "(", "doLoadImageTexture", ")", ";", "function", "doLoadImageTexture", "(", "resolve", ",", "reject", ")", "{", "var", "isEl", "=", "typeof", "src", "!==", "'string'", ";", "function", "resolveTexture", "(", "texture", ")", "{", "setTextureProperties", "(", "texture", ",", "data", ")", ";", "texture", ".", "needsUpdate", "=", "true", ";", "resolve", "(", "texture", ")", ";", "}", "if", "(", "isEl", ")", "{", "resolveTexture", "(", "new", "THREE", ".", "Texture", "(", "src", ")", ")", ";", "return", ";", "}", "TextureLoader", ".", "load", "(", "src", ",", "resolveTexture", ",", "function", "(", ")", "{", "}", ",", "function", "(", "xhr", ")", "{", "error", "(", "'`$s` could not be fetched (Error code: %s; Response: %s)'", ",", "xhr", ".", "status", ",", "xhr", ".", "statusText", ")", ";", "}", ")", ";", "}", "}" ]
Load image texture. @private @param {string|object} src - An <img> element or url to an image file. @param {object} data - Data to set texture properties like `repeat`. @returns {Promise} Resolves once texture is loaded.
[ "Load", "image", "texture", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L288-L318
train
aframevr/aframe
src/systems/material.js
setTextureProperties
function setTextureProperties (texture, data) { var offset = data.offset || {x: 0, y: 0}; var repeat = data.repeat || {x: 1, y: 1}; var npot = data.npot || false; // To support NPOT textures, wrap must be ClampToEdge (not Repeat), // and filters must not use mipmaps (i.e. Nearest or Linear). if (npot) { texture.wrapS = THREE.ClampToEdgeWrapping; texture.wrapT = THREE.ClampToEdgeWrapping; texture.magFilter = THREE.LinearFilter; texture.minFilter = THREE.LinearFilter; } // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat. if (repeat.x !== 1 || repeat.y !== 1) { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.set(repeat.x, repeat.y); } // Don't bother setting offset if it is 0/0. if (offset.x !== 0 || offset.y !== 0) { texture.offset.set(offset.x, offset.y); } }
javascript
function setTextureProperties (texture, data) { var offset = data.offset || {x: 0, y: 0}; var repeat = data.repeat || {x: 1, y: 1}; var npot = data.npot || false; // To support NPOT textures, wrap must be ClampToEdge (not Repeat), // and filters must not use mipmaps (i.e. Nearest or Linear). if (npot) { texture.wrapS = THREE.ClampToEdgeWrapping; texture.wrapT = THREE.ClampToEdgeWrapping; texture.magFilter = THREE.LinearFilter; texture.minFilter = THREE.LinearFilter; } // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat. if (repeat.x !== 1 || repeat.y !== 1) { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.set(repeat.x, repeat.y); } // Don't bother setting offset if it is 0/0. if (offset.x !== 0 || offset.y !== 0) { texture.offset.set(offset.x, offset.y); } }
[ "function", "setTextureProperties", "(", "texture", ",", "data", ")", "{", "var", "offset", "=", "data", ".", "offset", "||", "{", "x", ":", "0", ",", "y", ":", "0", "}", ";", "var", "repeat", "=", "data", ".", "repeat", "||", "{", "x", ":", "1", ",", "y", ":", "1", "}", ";", "var", "npot", "=", "data", ".", "npot", "||", "false", ";", "if", "(", "npot", ")", "{", "texture", ".", "wrapS", "=", "THREE", ".", "ClampToEdgeWrapping", ";", "texture", ".", "wrapT", "=", "THREE", ".", "ClampToEdgeWrapping", ";", "texture", ".", "magFilter", "=", "THREE", ".", "LinearFilter", ";", "texture", ".", "minFilter", "=", "THREE", ".", "LinearFilter", ";", "}", "if", "(", "repeat", ".", "x", "!==", "1", "||", "repeat", ".", "y", "!==", "1", ")", "{", "texture", ".", "wrapS", "=", "THREE", ".", "RepeatWrapping", ";", "texture", ".", "wrapT", "=", "THREE", ".", "RepeatWrapping", ";", "texture", ".", "repeat", ".", "set", "(", "repeat", ".", "x", ",", "repeat", ".", "y", ")", ";", "}", "if", "(", "offset", ".", "x", "!==", "0", "||", "offset", ".", "y", "!==", "0", ")", "{", "texture", ".", "offset", ".", "set", "(", "offset", ".", "x", ",", "offset", ".", "y", ")", ";", "}", "}" ]
Set texture properties such as repeat and offset. @param {object} data - With keys like `repeat`.
[ "Set", "texture", "properties", "such", "as", "repeat", "and", "offset", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L325-L349
train
aframevr/aframe
src/systems/material.js
createVideoEl
function createVideoEl (src, width, height) { var videoEl = document.createElement('video'); videoEl.width = width; videoEl.height = height; // Support inline videos for iOS webviews. videoEl.setAttribute('playsinline', ''); videoEl.setAttribute('webkit-playsinline', ''); videoEl.autoplay = true; videoEl.loop = true; videoEl.crossOrigin = 'anonymous'; videoEl.addEventListener('error', function () { warn('`$s` is not a valid video', src); }, true); videoEl.src = src; return videoEl; }
javascript
function createVideoEl (src, width, height) { var videoEl = document.createElement('video'); videoEl.width = width; videoEl.height = height; // Support inline videos for iOS webviews. videoEl.setAttribute('playsinline', ''); videoEl.setAttribute('webkit-playsinline', ''); videoEl.autoplay = true; videoEl.loop = true; videoEl.crossOrigin = 'anonymous'; videoEl.addEventListener('error', function () { warn('`$s` is not a valid video', src); }, true); videoEl.src = src; return videoEl; }
[ "function", "createVideoEl", "(", "src", ",", "width", ",", "height", ")", "{", "var", "videoEl", "=", "document", ".", "createElement", "(", "'video'", ")", ";", "videoEl", ".", "width", "=", "width", ";", "videoEl", ".", "height", "=", "height", ";", "videoEl", ".", "setAttribute", "(", "'playsinline'", ",", "''", ")", ";", "videoEl", ".", "setAttribute", "(", "'webkit-playsinline'", ",", "''", ")", ";", "videoEl", ".", "autoplay", "=", "true", ";", "videoEl", ".", "loop", "=", "true", ";", "videoEl", ".", "crossOrigin", "=", "'anonymous'", ";", "videoEl", ".", "addEventListener", "(", "'error'", ",", "function", "(", ")", "{", "warn", "(", "'`$s` is not a valid video'", ",", "src", ")", ";", "}", ",", "true", ")", ";", "videoEl", ".", "src", "=", "src", ";", "return", "videoEl", ";", "}" ]
Create video element to be used as a texture. @param {string} src - Url to a video file. @param {number} width - Width of the video. @param {number} height - Height of the video. @returns {Element} Video element.
[ "Create", "video", "element", "to", "be", "used", "as", "a", "texture", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L359-L374
train
aframevr/aframe
src/systems/material.js
fixVideoAttributes
function fixVideoAttributes (videoEl) { videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false'; videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false'; if (videoEl.getAttribute('loop') === 'false') { videoEl.removeAttribute('loop'); } if (videoEl.getAttribute('preload') === 'false') { videoEl.preload = 'none'; } videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous'; // To support inline videos in iOS webviews. videoEl.setAttribute('playsinline', ''); videoEl.setAttribute('webkit-playsinline', ''); return videoEl; }
javascript
function fixVideoAttributes (videoEl) { videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false'; videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false'; if (videoEl.getAttribute('loop') === 'false') { videoEl.removeAttribute('loop'); } if (videoEl.getAttribute('preload') === 'false') { videoEl.preload = 'none'; } videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous'; // To support inline videos in iOS webviews. videoEl.setAttribute('playsinline', ''); videoEl.setAttribute('webkit-playsinline', ''); return videoEl; }
[ "function", "fixVideoAttributes", "(", "videoEl", ")", "{", "videoEl", ".", "autoplay", "=", "videoEl", ".", "hasAttribute", "(", "'autoplay'", ")", "&&", "videoEl", ".", "getAttribute", "(", "'autoplay'", ")", "!==", "'false'", ";", "videoEl", ".", "controls", "=", "videoEl", ".", "hasAttribute", "(", "'controls'", ")", "&&", "videoEl", ".", "getAttribute", "(", "'controls'", ")", "!==", "'false'", ";", "if", "(", "videoEl", ".", "getAttribute", "(", "'loop'", ")", "===", "'false'", ")", "{", "videoEl", ".", "removeAttribute", "(", "'loop'", ")", ";", "}", "if", "(", "videoEl", ".", "getAttribute", "(", "'preload'", ")", "===", "'false'", ")", "{", "videoEl", ".", "preload", "=", "'none'", ";", "}", "videoEl", ".", "crossOrigin", "=", "videoEl", ".", "crossOrigin", "||", "'anonymous'", ";", "videoEl", ".", "setAttribute", "(", "'playsinline'", ",", "''", ")", ";", "videoEl", ".", "setAttribute", "(", "'webkit-playsinline'", ",", "''", ")", ";", "return", "videoEl", ";", "}" ]
Fixes a video element's attributes to prevent developers from accidentally passing the wrong attribute values to commonly misused video attributes. <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as as booleans. Existence of those attributes will mean truthy. For example, translates <video loop="false"> to <video>. @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes @param {Element} videoEl - Video element. @returns {Element} Video element with the correct properties updated.
[ "Fixes", "a", "video", "element", "s", "attributes", "to", "prevent", "developers", "from", "accidentally", "passing", "the", "wrong", "attribute", "values", "to", "commonly", "misused", "video", "attributes", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/material.js#L389-L403
train
aframevr/aframe
src/components/sound.js
function (oldEvt) { var el = this.el; if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); } el.addEventListener(this.data.on, this.playSoundBound); }
javascript
function (oldEvt) { var el = this.el; if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); } el.addEventListener(this.data.on, this.playSoundBound); }
[ "function", "(", "oldEvt", ")", "{", "var", "el", "=", "this", ".", "el", ";", "if", "(", "oldEvt", ")", "{", "el", ".", "removeEventListener", "(", "oldEvt", ",", "this", ".", "playSoundBound", ")", ";", "}", "el", ".", "addEventListener", "(", "this", ".", "data", ".", "on", ",", "this", ".", "playSoundBound", ")", ";", "}" ]
Update listener attached to the user defined on event.
[ "Update", "listener", "attached", "to", "the", "user", "defined", "on", "event", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/sound.js#L123-L127
train
aframevr/aframe
src/components/sound.js
function () { var el = this.el; var i; var sceneEl = el.sceneEl; var self = this; var sound; if (this.pool.children.length > 0) { this.stopSound(); el.removeObject3D('sound'); } // Only want one AudioListener. Cache it on the scene. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener(); sceneEl.audioListener = listener; if (sceneEl.camera) { sceneEl.camera.add(listener); } // Wait for camera if necessary. sceneEl.addEventListener('camera-set-active', function (evt) { evt.detail.cameraEl.getObject3D('camera').add(listener); }); // Create [poolSize] audio instances and attach them to pool this.pool = new THREE.Group(); for (i = 0; i < this.data.poolSize; i++) { sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener); this.pool.add(sound); } el.setObject3D(this.attrName, this.pool); for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; sound.onEnded = function () { this.isPlaying = false; self.el.emit('sound-ended', self.evtDetail, false); }; } }
javascript
function () { var el = this.el; var i; var sceneEl = el.sceneEl; var self = this; var sound; if (this.pool.children.length > 0) { this.stopSound(); el.removeObject3D('sound'); } // Only want one AudioListener. Cache it on the scene. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener(); sceneEl.audioListener = listener; if (sceneEl.camera) { sceneEl.camera.add(listener); } // Wait for camera if necessary. sceneEl.addEventListener('camera-set-active', function (evt) { evt.detail.cameraEl.getObject3D('camera').add(listener); }); // Create [poolSize] audio instances and attach them to pool this.pool = new THREE.Group(); for (i = 0; i < this.data.poolSize; i++) { sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener); this.pool.add(sound); } el.setObject3D(this.attrName, this.pool); for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; sound.onEnded = function () { this.isPlaying = false; self.el.emit('sound-ended', self.evtDetail, false); }; } }
[ "function", "(", ")", "{", "var", "el", "=", "this", ".", "el", ";", "var", "i", ";", "var", "sceneEl", "=", "el", ".", "sceneEl", ";", "var", "self", "=", "this", ";", "var", "sound", ";", "if", "(", "this", ".", "pool", ".", "children", ".", "length", ">", "0", ")", "{", "this", ".", "stopSound", "(", ")", ";", "el", ".", "removeObject3D", "(", "'sound'", ")", ";", "}", "var", "listener", "=", "this", ".", "listener", "=", "sceneEl", ".", "audioListener", "||", "new", "THREE", ".", "AudioListener", "(", ")", ";", "sceneEl", ".", "audioListener", "=", "listener", ";", "if", "(", "sceneEl", ".", "camera", ")", "{", "sceneEl", ".", "camera", ".", "add", "(", "listener", ")", ";", "}", "sceneEl", ".", "addEventListener", "(", "'camera-set-active'", ",", "function", "(", "evt", ")", "{", "evt", ".", "detail", ".", "cameraEl", ".", "getObject3D", "(", "'camera'", ")", ".", "add", "(", "listener", ")", ";", "}", ")", ";", "this", ".", "pool", "=", "new", "THREE", ".", "Group", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "data", ".", "poolSize", ";", "i", "++", ")", "{", "sound", "=", "this", ".", "data", ".", "positional", "?", "new", "THREE", ".", "PositionalAudio", "(", "listener", ")", ":", "new", "THREE", ".", "Audio", "(", "listener", ")", ";", "this", ".", "pool", ".", "add", "(", "sound", ")", ";", "}", "el", ".", "setObject3D", "(", "this", ".", "attrName", ",", "this", ".", "pool", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "pool", ".", "children", ".", "length", ";", "i", "++", ")", "{", "sound", "=", "this", ".", "pool", ".", "children", "[", "i", "]", ";", "sound", ".", "onEnded", "=", "function", "(", ")", "{", "this", ".", "isPlaying", "=", "false", ";", "self", ".", "el", ".", "emit", "(", "'sound-ended'", ",", "self", ".", "evtDetail", ",", "false", ")", ";", "}", ";", "}", "}" ]
Removes current sound object, creates new sound object, adds to entity. @returns {object} sound
[ "Removes", "current", "sound", "object", "creates", "new", "sound", "object", "adds", "to", "entity", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/sound.js#L138-L180
train
aframevr/aframe
src/components/sound.js
function () { var i; var sound; this.isPlaying = false; for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { continue; } sound.isPaused = true; sound.pause(); } }
javascript
function () { var i; var sound; this.isPlaying = false; for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { continue; } sound.isPaused = true; sound.pause(); } }
[ "function", "(", ")", "{", "var", "i", ";", "var", "sound", ";", "this", ".", "isPlaying", "=", "false", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "pool", ".", "children", ".", "length", ";", "i", "++", ")", "{", "sound", "=", "this", ".", "pool", ".", "children", "[", "i", "]", ";", "if", "(", "!", "sound", ".", "source", "||", "!", "sound", ".", "source", ".", "buffer", "||", "!", "sound", ".", "isPlaying", "||", "sound", ".", "isPaused", ")", "{", "continue", ";", "}", "sound", ".", "isPaused", "=", "true", ";", "sound", ".", "pause", "(", ")", ";", "}", "}" ]
Pause all the sounds in the pool.
[ "Pause", "all", "the", "sounds", "in", "the", "pool", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/sound.js#L185-L198
train
aframevr/aframe
src/components/sound.js
function (processSound) { var found; var i; var sound; if (!this.loaded) { warn('Sound not loaded yet. It will be played once it finished loading'); this.mustPlay = true; return; } found = false; this.isPlaying = true; for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; if (!sound.isPlaying && sound.buffer && !found) { if (processSound) { processSound(sound); } sound.play(); sound.isPaused = false; found = true; continue; } } if (!found) { warn('All the sounds are playing. If you need to play more sounds simultaneously ' + 'consider increasing the size of pool with the `poolSize` attribute.', this.el); return; } this.mustPlay = false; }
javascript
function (processSound) { var found; var i; var sound; if (!this.loaded) { warn('Sound not loaded yet. It will be played once it finished loading'); this.mustPlay = true; return; } found = false; this.isPlaying = true; for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; if (!sound.isPlaying && sound.buffer && !found) { if (processSound) { processSound(sound); } sound.play(); sound.isPaused = false; found = true; continue; } } if (!found) { warn('All the sounds are playing. If you need to play more sounds simultaneously ' + 'consider increasing the size of pool with the `poolSize` attribute.', this.el); return; } this.mustPlay = false; }
[ "function", "(", "processSound", ")", "{", "var", "found", ";", "var", "i", ";", "var", "sound", ";", "if", "(", "!", "this", ".", "loaded", ")", "{", "warn", "(", "'Sound not loaded yet. It will be played once it finished loading'", ")", ";", "this", ".", "mustPlay", "=", "true", ";", "return", ";", "}", "found", "=", "false", ";", "this", ".", "isPlaying", "=", "true", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "pool", ".", "children", ".", "length", ";", "i", "++", ")", "{", "sound", "=", "this", ".", "pool", ".", "children", "[", "i", "]", ";", "if", "(", "!", "sound", ".", "isPlaying", "&&", "sound", ".", "buffer", "&&", "!", "found", ")", "{", "if", "(", "processSound", ")", "{", "processSound", "(", "sound", ")", ";", "}", "sound", ".", "play", "(", ")", ";", "sound", ".", "isPaused", "=", "false", ";", "found", "=", "true", ";", "continue", ";", "}", "}", "if", "(", "!", "found", ")", "{", "warn", "(", "'All the sounds are playing. If you need to play more sounds simultaneously '", "+", "'consider increasing the size of pool with the `poolSize` attribute.'", ",", "this", ".", "el", ")", ";", "return", ";", "}", "this", ".", "mustPlay", "=", "false", ";", "}" ]
Look for an unused sound in the pool and play it if found.
[ "Look", "for", "an", "unused", "sound", "in", "the", "pool", "and", "play", "it", "if", "found", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/sound.js#L203-L234
train
aframevr/aframe
src/components/sound.js
function () { var i; var sound; this.isPlaying = false; for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; if (!sound.source || !sound.source.buffer) { return; } sound.stop(); } }
javascript
function () { var i; var sound; this.isPlaying = false; for (i = 0; i < this.pool.children.length; i++) { sound = this.pool.children[i]; if (!sound.source || !sound.source.buffer) { return; } sound.stop(); } }
[ "function", "(", ")", "{", "var", "i", ";", "var", "sound", ";", "this", ".", "isPlaying", "=", "false", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "pool", ".", "children", ".", "length", ";", "i", "++", ")", "{", "sound", "=", "this", ".", "pool", ".", "children", "[", "i", "]", ";", "if", "(", "!", "sound", ".", "source", "||", "!", "sound", ".", "source", ".", "buffer", ")", "{", "return", ";", "}", "sound", ".", "stop", "(", ")", ";", "}", "}" ]
Stop all the sounds in the pool.
[ "Stop", "all", "the", "sounds", "in", "the", "pool", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/sound.js#L239-L248
train
aframevr/aframe
src/components/vive-controls.js
function (evt) { var button = this.mapping.buttons[evt.detail.id]; var buttonMeshes = this.buttonMeshes; var analogValue; if (!button) { return; } if (button === 'trigger') { analogValue = evt.detail.state.value; // Update trigger rotation depending on button value. if (buttonMeshes && buttonMeshes.trigger) { buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12); } } // Pass along changed event with button state, using button mapping for convenience. this.el.emit(button + 'changed', evt.detail.state); }
javascript
function (evt) { var button = this.mapping.buttons[evt.detail.id]; var buttonMeshes = this.buttonMeshes; var analogValue; if (!button) { return; } if (button === 'trigger') { analogValue = evt.detail.state.value; // Update trigger rotation depending on button value. if (buttonMeshes && buttonMeshes.trigger) { buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12); } } // Pass along changed event with button state, using button mapping for convenience. this.el.emit(button + 'changed', evt.detail.state); }
[ "function", "(", "evt", ")", "{", "var", "button", "=", "this", ".", "mapping", ".", "buttons", "[", "evt", ".", "detail", ".", "id", "]", ";", "var", "buttonMeshes", "=", "this", ".", "buttonMeshes", ";", "var", "analogValue", ";", "if", "(", "!", "button", ")", "{", "return", ";", "}", "if", "(", "button", "===", "'trigger'", ")", "{", "analogValue", "=", "evt", ".", "detail", ".", "state", ".", "value", ";", "if", "(", "buttonMeshes", "&&", "buttonMeshes", ".", "trigger", ")", "{", "buttonMeshes", ".", "trigger", ".", "rotation", ".", "x", "=", "-", "analogValue", "*", "(", "Math", ".", "PI", "/", "12", ")", ";", "}", "}", "this", ".", "el", ".", "emit", "(", "button", "+", "'changed'", ",", "evt", ".", "detail", ".", "state", ")", ";", "}" ]
Rotate the trigger button based on how hard the trigger is pressed.
[ "Rotate", "the", "trigger", "button", "based", "on", "how", "hard", "the", "trigger", "is", "pressed", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/vive-controls.js#L146-L163
train
aframevr/aframe
src/core/a-register-element.js
wrapANodeMethods
function wrapANodeMethods (obj) { var newObj = {}; var ANodeMethods = [ 'attachedCallback', 'attributeChangedCallback', 'createdCallback', 'detachedCallback' ]; wrapMethods(newObj, ANodeMethods, obj, ANode.prototype); copyProperties(obj, newObj); return newObj; }
javascript
function wrapANodeMethods (obj) { var newObj = {}; var ANodeMethods = [ 'attachedCallback', 'attributeChangedCallback', 'createdCallback', 'detachedCallback' ]; wrapMethods(newObj, ANodeMethods, obj, ANode.prototype); copyProperties(obj, newObj); return newObj; }
[ "function", "wrapANodeMethods", "(", "obj", ")", "{", "var", "newObj", "=", "{", "}", ";", "var", "ANodeMethods", "=", "[", "'attachedCallback'", ",", "'attributeChangedCallback'", ",", "'createdCallback'", ",", "'detachedCallback'", "]", ";", "wrapMethods", "(", "newObj", ",", "ANodeMethods", ",", "obj", ",", "ANode", ".", "prototype", ")", ";", "copyProperties", "(", "obj", ",", "newObj", ")", ";", "return", "newObj", ";", "}" ]
Wrap some obj methods to call those on `ANode` base prototype. @param {object} obj - Object that contains the methods that will be wrapped. @return {object} An object with the same properties as the input parameter but with some of methods wrapped.
[ "Wrap", "some", "obj", "methods", "to", "call", "those", "on", "ANode", "base", "prototype", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-register-element.js#L79-L90
train
aframevr/aframe
src/core/a-register-element.js
wrapAEntityMethods
function wrapAEntityMethods (obj) { var newObj = {}; var ANodeMethods = [ 'attachedCallback', 'attributeChangedCallback', 'createdCallback', 'detachedCallback' ]; var AEntityMethods = [ 'attachedCallback', 'attributeChangedCallback', 'createdCallback', 'detachedCallback' ]; wrapMethods(newObj, ANodeMethods, obj, ANode.prototype); wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype); // Copies the remaining properties into the new object. copyProperties(obj, newObj); return newObj; }
javascript
function wrapAEntityMethods (obj) { var newObj = {}; var ANodeMethods = [ 'attachedCallback', 'attributeChangedCallback', 'createdCallback', 'detachedCallback' ]; var AEntityMethods = [ 'attachedCallback', 'attributeChangedCallback', 'createdCallback', 'detachedCallback' ]; wrapMethods(newObj, ANodeMethods, obj, ANode.prototype); wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype); // Copies the remaining properties into the new object. copyProperties(obj, newObj); return newObj; }
[ "function", "wrapAEntityMethods", "(", "obj", ")", "{", "var", "newObj", "=", "{", "}", ";", "var", "ANodeMethods", "=", "[", "'attachedCallback'", ",", "'attributeChangedCallback'", ",", "'createdCallback'", ",", "'detachedCallback'", "]", ";", "var", "AEntityMethods", "=", "[", "'attachedCallback'", ",", "'attributeChangedCallback'", ",", "'createdCallback'", ",", "'detachedCallback'", "]", ";", "wrapMethods", "(", "newObj", ",", "ANodeMethods", ",", "obj", ",", "ANode", ".", "prototype", ")", ";", "wrapMethods", "(", "newObj", ",", "AEntityMethods", ",", "obj", ",", "AEntity", ".", "prototype", ")", ";", "copyProperties", "(", "obj", ",", "newObj", ")", ";", "return", "newObj", ";", "}" ]
This wraps some of the obj methods to call those on `AEntity` base prototype. @param {object} obj - The objects that contains the methods that will be wrapped. @return {object} - An object with the same properties as the input parameter but with some of methods wrapped.
[ "This", "wraps", "some", "of", "the", "obj", "methods", "to", "call", "those", "on", "AEntity", "base", "prototype", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-register-element.js#L99-L119
train
aframevr/aframe
src/core/a-register-element.js
wrapMethods
function wrapMethods (targetObj, methodList, derivedObj, baseObj) { methodList.forEach(function (methodName) { wrapMethod(targetObj, methodName, derivedObj, baseObj); }); }
javascript
function wrapMethods (targetObj, methodList, derivedObj, baseObj) { methodList.forEach(function (methodName) { wrapMethod(targetObj, methodName, derivedObj, baseObj); }); }
[ "function", "wrapMethods", "(", "targetObj", ",", "methodList", ",", "derivedObj", ",", "baseObj", ")", "{", "methodList", ".", "forEach", "(", "function", "(", "methodName", ")", "{", "wrapMethod", "(", "targetObj", ",", "methodName", ",", "derivedObj", ",", "baseObj", ")", ";", "}", ")", ";", "}" ]
Wrap a list a methods to ensure that those in the base prototype are called before the derived one. @param {object} targetObj - Object that will contain the wrapped methods. @param {array} methodList - List of methods from the derivedObj that will be wrapped. @param {object} derivedObject - Object that inherits from the baseObj. @param {object} baseObj - Object that derivedObj inherits from.
[ "Wrap", "a", "list", "a", "methods", "to", "ensure", "that", "those", "in", "the", "base", "prototype", "are", "called", "before", "the", "derived", "one", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-register-element.js#L130-L134
train
aframevr/aframe
src/core/a-register-element.js
wrapMethod
function wrapMethod (obj, methodName, derivedObj, baseObj) { var derivedMethod = derivedObj[methodName]; var baseMethod = baseObj[methodName]; // Derived prototype does not define method, no need to wrap. if (!derivedMethod || !baseMethod) { return; } // Derived prototype doesn't override the one in the base one, no need to wrap. if (derivedMethod === baseMethod) { return; } // Wrap to ensure the base method is called before the one in the derived prototype. obj[methodName] = { value: function wrappedMethod () { baseMethod.apply(this, arguments); return derivedMethod.apply(this, arguments); }, writable: window.debug }; }
javascript
function wrapMethod (obj, methodName, derivedObj, baseObj) { var derivedMethod = derivedObj[methodName]; var baseMethod = baseObj[methodName]; // Derived prototype does not define method, no need to wrap. if (!derivedMethod || !baseMethod) { return; } // Derived prototype doesn't override the one in the base one, no need to wrap. if (derivedMethod === baseMethod) { return; } // Wrap to ensure the base method is called before the one in the derived prototype. obj[methodName] = { value: function wrappedMethod () { baseMethod.apply(this, arguments); return derivedMethod.apply(this, arguments); }, writable: window.debug }; }
[ "function", "wrapMethod", "(", "obj", ",", "methodName", ",", "derivedObj", ",", "baseObj", ")", "{", "var", "derivedMethod", "=", "derivedObj", "[", "methodName", "]", ";", "var", "baseMethod", "=", "baseObj", "[", "methodName", "]", ";", "if", "(", "!", "derivedMethod", "||", "!", "baseMethod", ")", "{", "return", ";", "}", "if", "(", "derivedMethod", "===", "baseMethod", ")", "{", "return", ";", "}", "obj", "[", "methodName", "]", "=", "{", "value", ":", "function", "wrappedMethod", "(", ")", "{", "baseMethod", ".", "apply", "(", "this", ",", "arguments", ")", ";", "return", "derivedMethod", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ",", "writable", ":", "window", ".", "debug", "}", ";", "}" ]
Wrap one method to ensure that the one in the base prototype is called before the one in the derived one. @param {object} obj - Object that will contain the wrapped method. @param {string} methodName - The name of the method that will be wrapped. @param {object} derivedObject - Object that inherits from the baseObj. @param {object} baseObj - Object that derivedObj inherits from.
[ "Wrap", "one", "method", "to", "ensure", "that", "the", "one", "in", "the", "base", "prototype", "is", "called", "before", "the", "one", "in", "the", "derived", "one", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-register-element.js#L146-L164
train
aframevr/aframe
src/core/a-register-element.js
copyProperties
function copyProperties (source, destination) { var props = Object.getOwnPropertyNames(source); props.forEach(function (prop) { var desc; if (!destination[prop]) { desc = Object.getOwnPropertyDescriptor(source, prop); destination[prop] = {value: source[prop], writable: desc.writable}; } }); }
javascript
function copyProperties (source, destination) { var props = Object.getOwnPropertyNames(source); props.forEach(function (prop) { var desc; if (!destination[prop]) { desc = Object.getOwnPropertyDescriptor(source, prop); destination[prop] = {value: source[prop], writable: desc.writable}; } }); }
[ "function", "copyProperties", "(", "source", ",", "destination", ")", "{", "var", "props", "=", "Object", ".", "getOwnPropertyNames", "(", "source", ")", ";", "props", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "desc", ";", "if", "(", "!", "destination", "[", "prop", "]", ")", "{", "desc", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "source", ",", "prop", ")", ";", "destination", "[", "prop", "]", "=", "{", "value", ":", "source", "[", "prop", "]", ",", "writable", ":", "desc", ".", "writable", "}", ";", "}", "}", ")", ";", "}" ]
It copies the properties from source to destination object if they don't exist already. @param {object} source - The object where properties are copied from. @param {type} destination - The object where properties are copied to.
[ "It", "copies", "the", "properties", "from", "source", "to", "destination", "object", "if", "they", "don", "t", "exist", "already", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-register-element.js#L173-L182
train
aframevr/aframe
src/systems/camera.js
function () { var cameraEls; var i; var sceneEl = this.sceneEl; var self = this; // Camera already defined or the one defined it is an spectator one. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) { sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el}); return; } // Search for initial user-defined camera. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]'); // No user cameras, create default one. if (!cameraEls.length) { this.createDefaultCamera(); return; } this.numUserCameras = cameraEls.length; for (i = 0; i < cameraEls.length; i++) { cameraEls[i].addEventListener('object3dset', function (evt) { if (evt.detail.type !== 'camera') { return; } self.checkUserCamera(this); }); // Load camera and wait for camera to initialize. if (cameraEls[i].isNode) { cameraEls[i].load(); } else { cameraEls[i].addEventListener('nodeready', function () { this.load(); }); } } }
javascript
function () { var cameraEls; var i; var sceneEl = this.sceneEl; var self = this; // Camera already defined or the one defined it is an spectator one. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) { sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el}); return; } // Search for initial user-defined camera. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]'); // No user cameras, create default one. if (!cameraEls.length) { this.createDefaultCamera(); return; } this.numUserCameras = cameraEls.length; for (i = 0; i < cameraEls.length; i++) { cameraEls[i].addEventListener('object3dset', function (evt) { if (evt.detail.type !== 'camera') { return; } self.checkUserCamera(this); }); // Load camera and wait for camera to initialize. if (cameraEls[i].isNode) { cameraEls[i].load(); } else { cameraEls[i].addEventListener('nodeready', function () { this.load(); }); } } }
[ "function", "(", ")", "{", "var", "cameraEls", ";", "var", "i", ";", "var", "sceneEl", "=", "this", ".", "sceneEl", ";", "var", "self", "=", "this", ";", "if", "(", "sceneEl", ".", "camera", "&&", "!", "sceneEl", ".", "camera", ".", "el", ".", "getAttribute", "(", "'camera'", ")", ".", "spectator", ")", "{", "sceneEl", ".", "emit", "(", "'cameraready'", ",", "{", "cameraEl", ":", "sceneEl", ".", "camera", ".", "el", "}", ")", ";", "return", ";", "}", "cameraEls", "=", "sceneEl", ".", "querySelectorAll", "(", "'a-camera, [camera]'", ")", ";", "if", "(", "!", "cameraEls", ".", "length", ")", "{", "this", ".", "createDefaultCamera", "(", ")", ";", "return", ";", "}", "this", ".", "numUserCameras", "=", "cameraEls", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "cameraEls", ".", "length", ";", "i", "++", ")", "{", "cameraEls", "[", "i", "]", ".", "addEventListener", "(", "'object3dset'", ",", "function", "(", "evt", ")", "{", "if", "(", "evt", ".", "detail", ".", "type", "!==", "'camera'", ")", "{", "return", ";", "}", "self", ".", "checkUserCamera", "(", "this", ")", ";", "}", ")", ";", "if", "(", "cameraEls", "[", "i", "]", ".", "isNode", ")", "{", "cameraEls", "[", "i", "]", ".", "load", "(", ")", ";", "}", "else", "{", "cameraEls", "[", "i", "]", ".", "addEventListener", "(", "'nodeready'", ",", "function", "(", ")", "{", "this", ".", "load", "(", ")", ";", "}", ")", ";", "}", "}", "}" ]
Setup initial camera, either searching for camera or creating a default camera if user has not added one during the initial scene traversal. We want sceneEl.camera to be ready, set, and initialized before the rest of the scene loads. Default camera offset height is at average eye level (~1.6m).
[ "Setup", "initial", "camera", "either", "searching", "for", "camera", "or", "creating", "a", "default", "camera", "if", "user", "has", "not", "added", "one", "during", "the", "initial", "scene", "traversal", ".", "We", "want", "sceneEl", ".", "camera", "to", "be", "ready", "set", "and", "initialized", "before", "the", "rest", "of", "the", "scene", "loads", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/camera.js#L33-L70
train
aframevr/aframe
src/systems/camera.js
function (newCameraEl) { var newCamera; var previousCamera = this.spectatorCameraEl; var sceneEl = this.sceneEl; var spectatorCameraEl; // Same camera. newCamera = newCameraEl.getObject3D('camera'); if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; } // Disable current camera if (previousCamera) { previousCamera.setAttribute('camera', 'spectator', false); } spectatorCameraEl = this.spectatorCameraEl = newCameraEl; sceneEl.addEventListener('enter-vr', this.wrapRender); sceneEl.addEventListener('exit-vr', this.unwrapRender); spectatorCameraEl.setAttribute('camera', 'active', false); spectatorCameraEl.play(); sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl}); }
javascript
function (newCameraEl) { var newCamera; var previousCamera = this.spectatorCameraEl; var sceneEl = this.sceneEl; var spectatorCameraEl; // Same camera. newCamera = newCameraEl.getObject3D('camera'); if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; } // Disable current camera if (previousCamera) { previousCamera.setAttribute('camera', 'spectator', false); } spectatorCameraEl = this.spectatorCameraEl = newCameraEl; sceneEl.addEventListener('enter-vr', this.wrapRender); sceneEl.addEventListener('exit-vr', this.unwrapRender); spectatorCameraEl.setAttribute('camera', 'active', false); spectatorCameraEl.play(); sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl}); }
[ "function", "(", "newCameraEl", ")", "{", "var", "newCamera", ";", "var", "previousCamera", "=", "this", ".", "spectatorCameraEl", ";", "var", "sceneEl", "=", "this", ".", "sceneEl", ";", "var", "spectatorCameraEl", ";", "newCamera", "=", "newCameraEl", ".", "getObject3D", "(", "'camera'", ")", ";", "if", "(", "!", "newCamera", "||", "newCameraEl", "===", "this", ".", "spectatorCameraEl", ")", "{", "return", ";", "}", "if", "(", "previousCamera", ")", "{", "previousCamera", ".", "setAttribute", "(", "'camera'", ",", "'spectator'", ",", "false", ")", ";", "}", "spectatorCameraEl", "=", "this", ".", "spectatorCameraEl", "=", "newCameraEl", ";", "sceneEl", ".", "addEventListener", "(", "'enter-vr'", ",", "this", ".", "wrapRender", ")", ";", "sceneEl", ".", "addEventListener", "(", "'exit-vr'", ",", "this", ".", "unwrapRender", ")", ";", "spectatorCameraEl", ".", "setAttribute", "(", "'camera'", ",", "'active'", ",", "false", ")", ";", "spectatorCameraEl", ".", "play", "(", ")", ";", "sceneEl", ".", "emit", "(", "'camera-set-spectator'", ",", "{", "cameraEl", ":", "newCameraEl", "}", ")", ";", "}" ]
Set spectator camera to render the scene on a 2D display. @param {Element} newCameraEl - Entity with camera component.
[ "Set", "spectator", "camera", "to", "render", "the", "scene", "on", "a", "2D", "display", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/camera.js#L193-L217
train
aframevr/aframe
src/systems/camera.js
removeDefaultCamera
function removeDefaultCamera (sceneEl) { var defaultCamera; var camera = sceneEl.camera; if (!camera) { return; } // Remove default camera if present. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']'); if (!defaultCamera) { return; } sceneEl.removeChild(defaultCamera); }
javascript
function removeDefaultCamera (sceneEl) { var defaultCamera; var camera = sceneEl.camera; if (!camera) { return; } // Remove default camera if present. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']'); if (!defaultCamera) { return; } sceneEl.removeChild(defaultCamera); }
[ "function", "removeDefaultCamera", "(", "sceneEl", ")", "{", "var", "defaultCamera", ";", "var", "camera", "=", "sceneEl", ".", "camera", ";", "if", "(", "!", "camera", ")", "{", "return", ";", "}", "defaultCamera", "=", "sceneEl", ".", "querySelector", "(", "'['", "+", "DEFAULT_CAMERA_ATTR", "+", "']'", ")", ";", "if", "(", "!", "defaultCamera", ")", "{", "return", ";", "}", "sceneEl", ".", "removeChild", "(", "defaultCamera", ")", ";", "}" ]
Remove injected default camera from scene, if present. @param {Element} sceneEl
[ "Remove", "injected", "default", "camera", "from", "scene", "if", "present", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/camera.js#L262-L271
train
aframevr/aframe
src/components/look-controls.js
function () { this.mouseDown = false; this.pitchObject = new THREE.Object3D(); this.yawObject = new THREE.Object3D(); this.yawObject.position.y = 10; this.yawObject.add(this.pitchObject); }
javascript
function () { this.mouseDown = false; this.pitchObject = new THREE.Object3D(); this.yawObject = new THREE.Object3D(); this.yawObject.position.y = 10; this.yawObject.add(this.pitchObject); }
[ "function", "(", ")", "{", "this", ".", "mouseDown", "=", "false", ";", "this", ".", "pitchObject", "=", "new", "THREE", ".", "Object3D", "(", ")", ";", "this", ".", "yawObject", "=", "new", "THREE", ".", "Object3D", "(", ")", ";", "this", ".", "yawObject", ".", "position", ".", "y", "=", "10", ";", "this", ".", "yawObject", ".", "add", "(", "this", ".", "pitchObject", ")", ";", "}" ]
Set up states and Object3Ds needed to store rotation data.
[ "Set", "up", "states", "and", "Object3Ds", "needed", "to", "store", "rotation", "data", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L110-L116
train
aframevr/aframe
src/components/look-controls.js
function () { var sceneEl = this.el.sceneEl; var canvasEl = sceneEl.canvas; // Wait for canvas to load. if (!canvasEl) { sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this)); return; } // Mouse events. canvasEl.addEventListener('mousedown', this.onMouseDown, false); window.addEventListener('mousemove', this.onMouseMove, false); window.addEventListener('mouseup', this.onMouseUp, false); // Touch events. canvasEl.addEventListener('touchstart', this.onTouchStart); window.addEventListener('touchmove', this.onTouchMove); window.addEventListener('touchend', this.onTouchEnd); // sceneEl events. sceneEl.addEventListener('enter-vr', this.onEnterVR); sceneEl.addEventListener('exit-vr', this.onExitVR); // Pointer Lock events. if (this.data.pointerLockEnabled) { document.addEventListener('pointerlockchange', this.onPointerLockChange, false); document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false); document.addEventListener('pointerlockerror', this.onPointerLockError, false); } }
javascript
function () { var sceneEl = this.el.sceneEl; var canvasEl = sceneEl.canvas; // Wait for canvas to load. if (!canvasEl) { sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this)); return; } // Mouse events. canvasEl.addEventListener('mousedown', this.onMouseDown, false); window.addEventListener('mousemove', this.onMouseMove, false); window.addEventListener('mouseup', this.onMouseUp, false); // Touch events. canvasEl.addEventListener('touchstart', this.onTouchStart); window.addEventListener('touchmove', this.onTouchMove); window.addEventListener('touchend', this.onTouchEnd); // sceneEl events. sceneEl.addEventListener('enter-vr', this.onEnterVR); sceneEl.addEventListener('exit-vr', this.onExitVR); // Pointer Lock events. if (this.data.pointerLockEnabled) { document.addEventListener('pointerlockchange', this.onPointerLockChange, false); document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false); document.addEventListener('pointerlockerror', this.onPointerLockError, false); } }
[ "function", "(", ")", "{", "var", "sceneEl", "=", "this", ".", "el", ".", "sceneEl", ";", "var", "canvasEl", "=", "sceneEl", ".", "canvas", ";", "if", "(", "!", "canvasEl", ")", "{", "sceneEl", ".", "addEventListener", "(", "'render-target-loaded'", ",", "bind", "(", "this", ".", "addEventListeners", ",", "this", ")", ")", ";", "return", ";", "}", "canvasEl", ".", "addEventListener", "(", "'mousedown'", ",", "this", ".", "onMouseDown", ",", "false", ")", ";", "window", ".", "addEventListener", "(", "'mousemove'", ",", "this", ".", "onMouseMove", ",", "false", ")", ";", "window", ".", "addEventListener", "(", "'mouseup'", ",", "this", ".", "onMouseUp", ",", "false", ")", ";", "canvasEl", ".", "addEventListener", "(", "'touchstart'", ",", "this", ".", "onTouchStart", ")", ";", "window", ".", "addEventListener", "(", "'touchmove'", ",", "this", ".", "onTouchMove", ")", ";", "window", ".", "addEventListener", "(", "'touchend'", ",", "this", ".", "onTouchEnd", ")", ";", "sceneEl", ".", "addEventListener", "(", "'enter-vr'", ",", "this", ".", "onEnterVR", ")", ";", "sceneEl", ".", "addEventListener", "(", "'exit-vr'", ",", "this", ".", "onExitVR", ")", ";", "if", "(", "this", ".", "data", ".", "pointerLockEnabled", ")", "{", "document", ".", "addEventListener", "(", "'pointerlockchange'", ",", "this", ".", "onPointerLockChange", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'mozpointerlockchange'", ",", "this", ".", "onPointerLockChange", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'pointerlockerror'", ",", "this", ".", "onPointerLockError", ",", "false", ")", ";", "}", "}" ]
Add mouse and touch event listeners to canvas.
[ "Add", "mouse", "and", "touch", "event", "listeners", "to", "canvas", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L121-L151
train
aframevr/aframe
src/components/look-controls.js
function () { var sceneEl = this.el.sceneEl; var canvasEl = sceneEl && sceneEl.canvas; if (!canvasEl) { return; } // Mouse events. canvasEl.removeEventListener('mousedown', this.onMouseDown); window.removeEventListener('mousemove', this.onMouseMove); window.removeEventListener('mouseup', this.onMouseUp); // Touch events. canvasEl.removeEventListener('touchstart', this.onTouchStart); window.removeEventListener('touchmove', this.onTouchMove); window.removeEventListener('touchend', this.onTouchEnd); // sceneEl events. sceneEl.removeEventListener('enter-vr', this.onEnterVR); sceneEl.removeEventListener('exit-vr', this.onExitVR); // Pointer Lock events. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false); document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false); document.removeEventListener('pointerlockerror', this.onPointerLockError, false); }
javascript
function () { var sceneEl = this.el.sceneEl; var canvasEl = sceneEl && sceneEl.canvas; if (!canvasEl) { return; } // Mouse events. canvasEl.removeEventListener('mousedown', this.onMouseDown); window.removeEventListener('mousemove', this.onMouseMove); window.removeEventListener('mouseup', this.onMouseUp); // Touch events. canvasEl.removeEventListener('touchstart', this.onTouchStart); window.removeEventListener('touchmove', this.onTouchMove); window.removeEventListener('touchend', this.onTouchEnd); // sceneEl events. sceneEl.removeEventListener('enter-vr', this.onEnterVR); sceneEl.removeEventListener('exit-vr', this.onExitVR); // Pointer Lock events. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false); document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false); document.removeEventListener('pointerlockerror', this.onPointerLockError, false); }
[ "function", "(", ")", "{", "var", "sceneEl", "=", "this", ".", "el", ".", "sceneEl", ";", "var", "canvasEl", "=", "sceneEl", "&&", "sceneEl", ".", "canvas", ";", "if", "(", "!", "canvasEl", ")", "{", "return", ";", "}", "canvasEl", ".", "removeEventListener", "(", "'mousedown'", ",", "this", ".", "onMouseDown", ")", ";", "window", ".", "removeEventListener", "(", "'mousemove'", ",", "this", ".", "onMouseMove", ")", ";", "window", ".", "removeEventListener", "(", "'mouseup'", ",", "this", ".", "onMouseUp", ")", ";", "canvasEl", ".", "removeEventListener", "(", "'touchstart'", ",", "this", ".", "onTouchStart", ")", ";", "window", ".", "removeEventListener", "(", "'touchmove'", ",", "this", ".", "onTouchMove", ")", ";", "window", ".", "removeEventListener", "(", "'touchend'", ",", "this", ".", "onTouchEnd", ")", ";", "sceneEl", ".", "removeEventListener", "(", "'enter-vr'", ",", "this", ".", "onEnterVR", ")", ";", "sceneEl", ".", "removeEventListener", "(", "'exit-vr'", ",", "this", ".", "onExitVR", ")", ";", "document", ".", "removeEventListener", "(", "'pointerlockchange'", ",", "this", ".", "onPointerLockChange", ",", "false", ")", ";", "document", ".", "removeEventListener", "(", "'mozpointerlockchange'", ",", "this", ".", "onPointerLockChange", ",", "false", ")", ";", "document", ".", "removeEventListener", "(", "'pointerlockerror'", ",", "this", ".", "onPointerLockError", ",", "false", ")", ";", "}" ]
Remove mouse and touch event listeners from canvas.
[ "Remove", "mouse", "and", "touch", "event", "listeners", "from", "canvas", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L156-L180
train
aframevr/aframe
src/components/look-controls.js
function (event) { var direction; var movementX; var movementY; var pitchObject = this.pitchObject; var previousMouseEvent = this.previousMouseEvent; var yawObject = this.yawObject; // Not dragging or not enabled. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; } // Calculate delta. if (this.pointerLocked) { movementX = event.movementX || event.mozMovementX || 0; movementY = event.movementY || event.mozMovementY || 0; } else { movementX = event.screenX - previousMouseEvent.screenX; movementY = event.screenY - previousMouseEvent.screenY; } this.previousMouseEvent = event; // Calculate rotation. direction = this.data.reverseMouseDrag ? 1 : -1; yawObject.rotation.y += movementX * 0.002 * direction; pitchObject.rotation.x += movementY * 0.002 * direction; pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x)); }
javascript
function (event) { var direction; var movementX; var movementY; var pitchObject = this.pitchObject; var previousMouseEvent = this.previousMouseEvent; var yawObject = this.yawObject; // Not dragging or not enabled. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; } // Calculate delta. if (this.pointerLocked) { movementX = event.movementX || event.mozMovementX || 0; movementY = event.movementY || event.mozMovementY || 0; } else { movementX = event.screenX - previousMouseEvent.screenX; movementY = event.screenY - previousMouseEvent.screenY; } this.previousMouseEvent = event; // Calculate rotation. direction = this.data.reverseMouseDrag ? 1 : -1; yawObject.rotation.y += movementX * 0.002 * direction; pitchObject.rotation.x += movementY * 0.002 * direction; pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x)); }
[ "function", "(", "event", ")", "{", "var", "direction", ";", "var", "movementX", ";", "var", "movementY", ";", "var", "pitchObject", "=", "this", ".", "pitchObject", ";", "var", "previousMouseEvent", "=", "this", ".", "previousMouseEvent", ";", "var", "yawObject", "=", "this", ".", "yawObject", ";", "if", "(", "!", "this", ".", "data", ".", "enabled", "||", "(", "!", "this", ".", "mouseDown", "&&", "!", "this", ".", "pointerLocked", ")", ")", "{", "return", ";", "}", "if", "(", "this", ".", "pointerLocked", ")", "{", "movementX", "=", "event", ".", "movementX", "||", "event", ".", "mozMovementX", "||", "0", ";", "movementY", "=", "event", ".", "movementY", "||", "event", ".", "mozMovementY", "||", "0", ";", "}", "else", "{", "movementX", "=", "event", ".", "screenX", "-", "previousMouseEvent", ".", "screenX", ";", "movementY", "=", "event", ".", "screenY", "-", "previousMouseEvent", ".", "screenY", ";", "}", "this", ".", "previousMouseEvent", "=", "event", ";", "direction", "=", "this", ".", "data", ".", "reverseMouseDrag", "?", "1", ":", "-", "1", ";", "yawObject", ".", "rotation", ".", "y", "+=", "movementX", "*", "0.002", "*", "direction", ";", "pitchObject", ".", "rotation", ".", "x", "+=", "movementY", "*", "0.002", "*", "direction", ";", "pitchObject", ".", "rotation", ".", "x", "=", "Math", ".", "max", "(", "-", "PI_2", ",", "Math", ".", "min", "(", "PI_2", ",", "pitchObject", ".", "rotation", ".", "x", ")", ")", ";", "}" ]
Translate mouse drag into rotation. Dragging up and down rotates the camera around the X-axis (yaw). Dragging left and right rotates the camera around the Y-axis (pitch).
[ "Translate", "mouse", "drag", "into", "rotation", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L227-L253
train
aframevr/aframe
src/components/look-controls.js
function (evt) { if (!this.data.enabled) { return; } // Handle only primary button. if (evt.button !== 0) { return; } var sceneEl = this.el.sceneEl; var canvasEl = sceneEl && sceneEl.canvas; this.mouseDown = true; this.previousMouseEvent = evt; this.showGrabbingCursor(); if (this.data.pointerLockEnabled && !this.pointerLocked) { if (canvasEl.requestPointerLock) { canvasEl.requestPointerLock(); } else if (canvasEl.mozRequestPointerLock) { canvasEl.mozRequestPointerLock(); } } }
javascript
function (evt) { if (!this.data.enabled) { return; } // Handle only primary button. if (evt.button !== 0) { return; } var sceneEl = this.el.sceneEl; var canvasEl = sceneEl && sceneEl.canvas; this.mouseDown = true; this.previousMouseEvent = evt; this.showGrabbingCursor(); if (this.data.pointerLockEnabled && !this.pointerLocked) { if (canvasEl.requestPointerLock) { canvasEl.requestPointerLock(); } else if (canvasEl.mozRequestPointerLock) { canvasEl.mozRequestPointerLock(); } } }
[ "function", "(", "evt", ")", "{", "if", "(", "!", "this", ".", "data", ".", "enabled", ")", "{", "return", ";", "}", "if", "(", "evt", ".", "button", "!==", "0", ")", "{", "return", ";", "}", "var", "sceneEl", "=", "this", ".", "el", ".", "sceneEl", ";", "var", "canvasEl", "=", "sceneEl", "&&", "sceneEl", ".", "canvas", ";", "this", ".", "mouseDown", "=", "true", ";", "this", ".", "previousMouseEvent", "=", "evt", ";", "this", ".", "showGrabbingCursor", "(", ")", ";", "if", "(", "this", ".", "data", ".", "pointerLockEnabled", "&&", "!", "this", ".", "pointerLocked", ")", "{", "if", "(", "canvasEl", ".", "requestPointerLock", ")", "{", "canvasEl", ".", "requestPointerLock", "(", ")", ";", "}", "else", "if", "(", "canvasEl", ".", "mozRequestPointerLock", ")", "{", "canvasEl", ".", "mozRequestPointerLock", "(", ")", ";", "}", "}", "}" ]
Register mouse down to detect mouse drag.
[ "Register", "mouse", "down", "to", "detect", "mouse", "drag", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L258-L277
train
aframevr/aframe
src/components/look-controls.js
function (evt) { if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; } this.touchStart = { x: evt.touches[0].pageX, y: evt.touches[0].pageY }; this.touchStarted = true; }
javascript
function (evt) { if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; } this.touchStart = { x: evt.touches[0].pageX, y: evt.touches[0].pageY }; this.touchStarted = true; }
[ "function", "(", "evt", ")", "{", "if", "(", "evt", ".", "touches", ".", "length", "!==", "1", "||", "!", "this", ".", "data", ".", "touchEnabled", ")", "{", "return", ";", "}", "this", ".", "touchStart", "=", "{", "x", ":", "evt", ".", "touches", "[", "0", "]", ".", "pageX", ",", "y", ":", "evt", ".", "touches", "[", "0", "]", ".", "pageY", "}", ";", "this", ".", "touchStarted", "=", "true", ";", "}" ]
Register touch down to detect touch drag.
[ "Register", "touch", "down", "to", "detect", "touch", "drag", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L304-L311
train
aframevr/aframe
src/components/look-controls.js
function (evt) { var direction; var canvas = this.el.sceneEl.canvas; var deltaY; var yawObject = this.yawObject; if (!this.touchStarted || !this.data.touchEnabled) { return; } deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth; direction = this.data.reverseTouchDrag ? 1 : -1; // Limit touch orientaion to to yaw (y axis). yawObject.rotation.y -= deltaY * 0.5 * direction; this.touchStart = { x: evt.touches[0].pageX, y: evt.touches[0].pageY }; }
javascript
function (evt) { var direction; var canvas = this.el.sceneEl.canvas; var deltaY; var yawObject = this.yawObject; if (!this.touchStarted || !this.data.touchEnabled) { return; } deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth; direction = this.data.reverseTouchDrag ? 1 : -1; // Limit touch orientaion to to yaw (y axis). yawObject.rotation.y -= deltaY * 0.5 * direction; this.touchStart = { x: evt.touches[0].pageX, y: evt.touches[0].pageY }; }
[ "function", "(", "evt", ")", "{", "var", "direction", ";", "var", "canvas", "=", "this", ".", "el", ".", "sceneEl", ".", "canvas", ";", "var", "deltaY", ";", "var", "yawObject", "=", "this", ".", "yawObject", ";", "if", "(", "!", "this", ".", "touchStarted", "||", "!", "this", ".", "data", ".", "touchEnabled", ")", "{", "return", ";", "}", "deltaY", "=", "2", "*", "Math", ".", "PI", "*", "(", "evt", ".", "touches", "[", "0", "]", ".", "pageX", "-", "this", ".", "touchStart", ".", "x", ")", "/", "canvas", ".", "clientWidth", ";", "direction", "=", "this", ".", "data", ".", "reverseTouchDrag", "?", "1", ":", "-", "1", ";", "yawObject", ".", "rotation", ".", "y", "-=", "deltaY", "*", "0.5", "*", "direction", ";", "this", ".", "touchStart", "=", "{", "x", ":", "evt", ".", "touches", "[", "0", "]", ".", "pageX", ",", "y", ":", "evt", ".", "touches", "[", "0", "]", ".", "pageY", "}", ";", "}" ]
Translate touch move to Y-axis rotation.
[ "Translate", "touch", "move", "to", "Y", "-", "axis", "rotation", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L316-L333
train
aframevr/aframe
src/components/look-controls.js
function () { if (!this.el.sceneEl.checkHeadsetConnected()) { return; } this.saveCameraPose(); this.el.object3D.position.set(0, 0, 0); this.el.object3D.updateMatrix(); }
javascript
function () { if (!this.el.sceneEl.checkHeadsetConnected()) { return; } this.saveCameraPose(); this.el.object3D.position.set(0, 0, 0); this.el.object3D.updateMatrix(); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "el", ".", "sceneEl", ".", "checkHeadsetConnected", "(", ")", ")", "{", "return", ";", "}", "this", ".", "saveCameraPose", "(", ")", ";", "this", ".", "el", ".", "object3D", ".", "position", ".", "set", "(", "0", ",", "0", ",", "0", ")", ";", "this", ".", "el", ".", "object3D", ".", "updateMatrix", "(", ")", ";", "}" ]
Save pose.
[ "Save", "pose", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L345-L350
train
aframevr/aframe
src/components/look-controls.js
function () { var el = this.el; this.savedPose.position.copy(el.object3D.position); this.savedPose.rotation.copy(el.object3D.rotation); this.hasSavedPose = true; }
javascript
function () { var el = this.el; this.savedPose.position.copy(el.object3D.position); this.savedPose.rotation.copy(el.object3D.rotation); this.hasSavedPose = true; }
[ "function", "(", ")", "{", "var", "el", "=", "this", ".", "el", ";", "this", ".", "savedPose", ".", "position", ".", "copy", "(", "el", ".", "object3D", ".", "position", ")", ";", "this", ".", "savedPose", ".", "rotation", ".", "copy", "(", "el", ".", "object3D", ".", "rotation", ")", ";", "this", ".", "hasSavedPose", "=", "true", ";", "}" ]
Save camera pose before entering VR to restore later if exiting.
[ "Save", "camera", "pose", "before", "entering", "VR", "to", "restore", "later", "if", "exiting", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L409-L415
train
aframevr/aframe
src/components/look-controls.js
function () { var el = this.el; var savedPose = this.savedPose; if (!this.hasSavedPose) { return; } // Reset camera orientation. el.object3D.position.copy(savedPose.position); el.object3D.rotation.copy(savedPose.rotation); this.hasSavedPose = false; }
javascript
function () { var el = this.el; var savedPose = this.savedPose; if (!this.hasSavedPose) { return; } // Reset camera orientation. el.object3D.position.copy(savedPose.position); el.object3D.rotation.copy(savedPose.rotation); this.hasSavedPose = false; }
[ "function", "(", ")", "{", "var", "el", "=", "this", ".", "el", ";", "var", "savedPose", "=", "this", ".", "savedPose", ";", "if", "(", "!", "this", ".", "hasSavedPose", ")", "{", "return", ";", "}", "el", ".", "object3D", ".", "position", ".", "copy", "(", "savedPose", ".", "position", ")", ";", "el", ".", "object3D", ".", "rotation", ".", "copy", "(", "savedPose", ".", "rotation", ")", ";", "this", ".", "hasSavedPose", "=", "false", ";", "}" ]
Reset camera pose to before entering VR.
[ "Reset", "camera", "pose", "to", "before", "entering", "VR", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/look-controls.js#L420-L430
train
aframevr/aframe
src/components/scene/vr-mode-ui.js
createEnterVRButton
function createEnterVRButton (onClick) { var vrButton; var wrapper; // Create elements. wrapper = document.createElement('div'); wrapper.classList.add(ENTER_VR_CLASS); wrapper.setAttribute(constants.AFRAME_INJECTED, ''); vrButton = document.createElement('button'); vrButton.className = ENTER_VR_BTN_CLASS; vrButton.setAttribute('title', 'Enter VR mode with a headset or fullscreen mode on a desktop. ' + 'Visit https://webvr.rocks or https://webvr.info for more information.'); vrButton.setAttribute(constants.AFRAME_INJECTED, ''); // Insert elements. wrapper.appendChild(vrButton); vrButton.addEventListener('click', function (evt) { onClick(); evt.stopPropagation(); }); return wrapper; }
javascript
function createEnterVRButton (onClick) { var vrButton; var wrapper; // Create elements. wrapper = document.createElement('div'); wrapper.classList.add(ENTER_VR_CLASS); wrapper.setAttribute(constants.AFRAME_INJECTED, ''); vrButton = document.createElement('button'); vrButton.className = ENTER_VR_BTN_CLASS; vrButton.setAttribute('title', 'Enter VR mode with a headset or fullscreen mode on a desktop. ' + 'Visit https://webvr.rocks or https://webvr.info for more information.'); vrButton.setAttribute(constants.AFRAME_INJECTED, ''); // Insert elements. wrapper.appendChild(vrButton); vrButton.addEventListener('click', function (evt) { onClick(); evt.stopPropagation(); }); return wrapper; }
[ "function", "createEnterVRButton", "(", "onClick", ")", "{", "var", "vrButton", ";", "var", "wrapper", ";", "wrapper", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "wrapper", ".", "classList", ".", "add", "(", "ENTER_VR_CLASS", ")", ";", "wrapper", ".", "setAttribute", "(", "constants", ".", "AFRAME_INJECTED", ",", "''", ")", ";", "vrButton", "=", "document", ".", "createElement", "(", "'button'", ")", ";", "vrButton", ".", "className", "=", "ENTER_VR_BTN_CLASS", ";", "vrButton", ".", "setAttribute", "(", "'title'", ",", "'Enter VR mode with a headset or fullscreen mode on a desktop. '", "+", "'Visit https://webvr.rocks or https://webvr.info for more information.'", ")", ";", "vrButton", ".", "setAttribute", "(", "constants", ".", "AFRAME_INJECTED", ",", "''", ")", ";", "wrapper", ".", "appendChild", "(", "vrButton", ")", ";", "vrButton", ".", "addEventListener", "(", "'click'", ",", "function", "(", "evt", ")", "{", "onClick", "(", ")", ";", "evt", ".", "stopPropagation", "(", ")", ";", "}", ")", ";", "return", "wrapper", ";", "}" ]
Create a button that when clicked will enter into stereo-rendering mode for VR. Structure: <div><button></div> @param {function} onClick - click event handler @returns {Element} Wrapper <div>.
[ "Create", "a", "button", "that", "when", "clicked", "will", "enter", "into", "stereo", "-", "rendering", "mode", "for", "VR", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/vr-mode-ui.js#L138-L160
train
aframevr/aframe
src/components/scene/vr-mode-ui.js
createOrientationModal
function createOrientationModal (onClick) { var modal = document.createElement('div'); modal.className = ORIENTATION_MODAL_CLASS; modal.classList.add(HIDDEN_CLASS); modal.setAttribute(constants.AFRAME_INJECTED, ''); var exit = document.createElement('button'); exit.setAttribute(constants.AFRAME_INJECTED, ''); exit.innerHTML = 'Exit VR'; // Exit VR on close. exit.addEventListener('click', onClick); modal.appendChild(exit); return modal; }
javascript
function createOrientationModal (onClick) { var modal = document.createElement('div'); modal.className = ORIENTATION_MODAL_CLASS; modal.classList.add(HIDDEN_CLASS); modal.setAttribute(constants.AFRAME_INJECTED, ''); var exit = document.createElement('button'); exit.setAttribute(constants.AFRAME_INJECTED, ''); exit.innerHTML = 'Exit VR'; // Exit VR on close. exit.addEventListener('click', onClick); modal.appendChild(exit); return modal; }
[ "function", "createOrientationModal", "(", "onClick", ")", "{", "var", "modal", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "modal", ".", "className", "=", "ORIENTATION_MODAL_CLASS", ";", "modal", ".", "classList", ".", "add", "(", "HIDDEN_CLASS", ")", ";", "modal", ".", "setAttribute", "(", "constants", ".", "AFRAME_INJECTED", ",", "''", ")", ";", "var", "exit", "=", "document", ".", "createElement", "(", "'button'", ")", ";", "exit", ".", "setAttribute", "(", "constants", ".", "AFRAME_INJECTED", ",", "''", ")", ";", "exit", ".", "innerHTML", "=", "'Exit VR'", ";", "exit", ".", "addEventListener", "(", "'click'", ",", "onClick", ")", ";", "modal", ".", "appendChild", "(", "exit", ")", ";", "return", "modal", ";", "}" ]
Creates a modal dialog to request the user to switch to landscape orientation. @param {function} onClick - click event handler @returns {Element} Wrapper <div>.
[ "Creates", "a", "modal", "dialog", "to", "request", "the", "user", "to", "switch", "to", "landscape", "orientation", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/vr-mode-ui.js#L168-L184
train
aframevr/aframe
src/components/text.js
function () { this.geometry.dispose(); this.geometry = null; this.el.removeObject3D(this.attrName); this.material.dispose(); this.material = null; this.texture.dispose(); this.texture = null; if (this.shaderObject) { delete this.shaderObject; } }
javascript
function () { this.geometry.dispose(); this.geometry = null; this.el.removeObject3D(this.attrName); this.material.dispose(); this.material = null; this.texture.dispose(); this.texture = null; if (this.shaderObject) { delete this.shaderObject; } }
[ "function", "(", ")", "{", "this", ".", "geometry", ".", "dispose", "(", ")", ";", "this", ".", "geometry", "=", "null", ";", "this", ".", "el", ".", "removeObject3D", "(", "this", ".", "attrName", ")", ";", "this", ".", "material", ".", "dispose", "(", ")", ";", "this", ".", "material", "=", "null", ";", "this", ".", "texture", ".", "dispose", "(", ")", ";", "this", ".", "texture", "=", "null", ";", "if", "(", "this", ".", "shaderObject", ")", "{", "delete", "this", ".", "shaderObject", ";", "}", "}" ]
Clean up geometry, material, texture, mesh, objects.
[ "Clean", "up", "geometry", "material", "texture", "mesh", "objects", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/text.js#L129-L140
train
aframevr/aframe
src/components/text.js
function () { var data = this.data; var hasChangedShader; var material = this.material; var NewShader; var shaderData = this.shaderData; var shaderName; // Infer shader if using a stock font (or from `-msdf` filename convention). shaderName = data.shader; if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) { shaderName = 'msdf'; } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) { shaderName = 'sdf'; } hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName; shaderData.alphaTest = data.alphaTest; shaderData.color = data.color; shaderData.map = this.texture; shaderData.opacity = data.opacity; shaderData.side = parseSide(data.side); shaderData.transparent = data.transparent; shaderData.negate = data.negate; // Shader has not changed, do an update. if (!hasChangedShader) { // Update shader material. this.shaderObject.update(shaderData); // Apparently, was not set on `init` nor `update`. material.transparent = shaderData.transparent; material.side = shaderData.side; return; } // Shader has changed. Create a shader material. NewShader = createShader(this.el, shaderName, shaderData); this.material = NewShader.material; this.shaderObject = NewShader.shader; // Set new shader material. this.material.side = shaderData.side; if (this.mesh) { this.mesh.material = this.material; } }
javascript
function () { var data = this.data; var hasChangedShader; var material = this.material; var NewShader; var shaderData = this.shaderData; var shaderName; // Infer shader if using a stock font (or from `-msdf` filename convention). shaderName = data.shader; if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) { shaderName = 'msdf'; } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) { shaderName = 'sdf'; } hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName; shaderData.alphaTest = data.alphaTest; shaderData.color = data.color; shaderData.map = this.texture; shaderData.opacity = data.opacity; shaderData.side = parseSide(data.side); shaderData.transparent = data.transparent; shaderData.negate = data.negate; // Shader has not changed, do an update. if (!hasChangedShader) { // Update shader material. this.shaderObject.update(shaderData); // Apparently, was not set on `init` nor `update`. material.transparent = shaderData.transparent; material.side = shaderData.side; return; } // Shader has changed. Create a shader material. NewShader = createShader(this.el, shaderName, shaderData); this.material = NewShader.material; this.shaderObject = NewShader.shader; // Set new shader material. this.material.side = shaderData.side; if (this.mesh) { this.mesh.material = this.material; } }
[ "function", "(", ")", "{", "var", "data", "=", "this", ".", "data", ";", "var", "hasChangedShader", ";", "var", "material", "=", "this", ".", "material", ";", "var", "NewShader", ";", "var", "shaderData", "=", "this", ".", "shaderData", ";", "var", "shaderName", ";", "shaderName", "=", "data", ".", "shader", ";", "if", "(", "MSDF_FONTS", ".", "indexOf", "(", "data", ".", "font", ")", "!==", "-", "1", "||", "data", ".", "font", ".", "indexOf", "(", "'-msdf.'", ")", ">=", "0", ")", "{", "shaderName", "=", "'msdf'", ";", "}", "else", "if", "(", "data", ".", "font", "in", "FONTS", "&&", "MSDF_FONTS", ".", "indexOf", "(", "data", ".", "font", ")", "===", "-", "1", ")", "{", "shaderName", "=", "'sdf'", ";", "}", "hasChangedShader", "=", "(", "this", ".", "shaderObject", "&&", "this", ".", "shaderObject", ".", "name", ")", "!==", "shaderName", ";", "shaderData", ".", "alphaTest", "=", "data", ".", "alphaTest", ";", "shaderData", ".", "color", "=", "data", ".", "color", ";", "shaderData", ".", "map", "=", "this", ".", "texture", ";", "shaderData", ".", "opacity", "=", "data", ".", "opacity", ";", "shaderData", ".", "side", "=", "parseSide", "(", "data", ".", "side", ")", ";", "shaderData", ".", "transparent", "=", "data", ".", "transparent", ";", "shaderData", ".", "negate", "=", "data", ".", "negate", ";", "if", "(", "!", "hasChangedShader", ")", "{", "this", ".", "shaderObject", ".", "update", "(", "shaderData", ")", ";", "material", ".", "transparent", "=", "shaderData", ".", "transparent", ";", "material", ".", "side", "=", "shaderData", ".", "side", ";", "return", ";", "}", "NewShader", "=", "createShader", "(", "this", ".", "el", ",", "shaderName", ",", "shaderData", ")", ";", "this", ".", "material", "=", "NewShader", ".", "material", ";", "this", ".", "shaderObject", "=", "NewShader", ".", "shader", ";", "this", ".", "material", ".", "side", "=", "shaderData", ".", "side", ";", "if", "(", "this", ".", "mesh", ")", "{", "this", ".", "mesh", ".", "material", "=", "this", ".", "material", ";", "}", "}" ]
Update the shader of the material.
[ "Update", "the", "shader", "of", "the", "material", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/text.js#L145-L189
train
aframevr/aframe
src/components/text.js
function () { var data = this.data; var el = this.el; var fontSrc; var geometry = this.geometry; var self = this; if (!data.font) { warn('No font specified. Using the default font.'); } // Make invisible during font swap. this.mesh.visible = false; // Look up font URL to use, and perform cached load. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font; cache.get(fontSrc, function doLoadFont () { return loadFont(fontSrc, data.yOffset); }).then(function setFont (font) { var fontImgSrc; if (font.pages.length !== 1) { throw new Error('Currently only single-page bitmap fonts are supported.'); } if (!fontWidthFactors[fontSrc]) { font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font); } // Update geometry given font metrics. self.updateGeometry(geometry, font); // Set font and update layout. self.currentFont = font; self.updateLayout(); // Look up font image URL to use, and perform cached load. fontImgSrc = self.getFontImageSrc(); cache.get(fontImgSrc, function () { return loadTexture(fontImgSrc); }).then(function (image) { // Make mesh visible and apply font image as texture. var texture = self.texture; texture.image = image; texture.needsUpdate = true; textures[data.font] = texture; self.texture = texture; self.mesh.visible = true; el.emit('textfontset', {font: data.font, fontObj: font}); }).catch(function (err) { error(err.message); error(err.stack); }); }).catch(function (err) { error(err.message); error(err.stack); }); }
javascript
function () { var data = this.data; var el = this.el; var fontSrc; var geometry = this.geometry; var self = this; if (!data.font) { warn('No font specified. Using the default font.'); } // Make invisible during font swap. this.mesh.visible = false; // Look up font URL to use, and perform cached load. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font; cache.get(fontSrc, function doLoadFont () { return loadFont(fontSrc, data.yOffset); }).then(function setFont (font) { var fontImgSrc; if (font.pages.length !== 1) { throw new Error('Currently only single-page bitmap fonts are supported.'); } if (!fontWidthFactors[fontSrc]) { font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font); } // Update geometry given font metrics. self.updateGeometry(geometry, font); // Set font and update layout. self.currentFont = font; self.updateLayout(); // Look up font image URL to use, and perform cached load. fontImgSrc = self.getFontImageSrc(); cache.get(fontImgSrc, function () { return loadTexture(fontImgSrc); }).then(function (image) { // Make mesh visible and apply font image as texture. var texture = self.texture; texture.image = image; texture.needsUpdate = true; textures[data.font] = texture; self.texture = texture; self.mesh.visible = true; el.emit('textfontset', {font: data.font, fontObj: font}); }).catch(function (err) { error(err.message); error(err.stack); }); }).catch(function (err) { error(err.message); error(err.stack); }); }
[ "function", "(", ")", "{", "var", "data", "=", "this", ".", "data", ";", "var", "el", "=", "this", ".", "el", ";", "var", "fontSrc", ";", "var", "geometry", "=", "this", ".", "geometry", ";", "var", "self", "=", "this", ";", "if", "(", "!", "data", ".", "font", ")", "{", "warn", "(", "'No font specified. Using the default font.'", ")", ";", "}", "this", ".", "mesh", ".", "visible", "=", "false", ";", "fontSrc", "=", "this", ".", "lookupFont", "(", "data", ".", "font", "||", "DEFAULT_FONT", ")", "||", "data", ".", "font", ";", "cache", ".", "get", "(", "fontSrc", ",", "function", "doLoadFont", "(", ")", "{", "return", "loadFont", "(", "fontSrc", ",", "data", ".", "yOffset", ")", ";", "}", ")", ".", "then", "(", "function", "setFont", "(", "font", ")", "{", "var", "fontImgSrc", ";", "if", "(", "font", ".", "pages", ".", "length", "!==", "1", ")", "{", "throw", "new", "Error", "(", "'Currently only single-page bitmap fonts are supported.'", ")", ";", "}", "if", "(", "!", "fontWidthFactors", "[", "fontSrc", "]", ")", "{", "font", ".", "widthFactor", "=", "fontWidthFactors", "[", "font", "]", "=", "computeFontWidthFactor", "(", "font", ")", ";", "}", "self", ".", "updateGeometry", "(", "geometry", ",", "font", ")", ";", "self", ".", "currentFont", "=", "font", ";", "self", ".", "updateLayout", "(", ")", ";", "fontImgSrc", "=", "self", ".", "getFontImageSrc", "(", ")", ";", "cache", ".", "get", "(", "fontImgSrc", ",", "function", "(", ")", "{", "return", "loadTexture", "(", "fontImgSrc", ")", ";", "}", ")", ".", "then", "(", "function", "(", "image", ")", "{", "var", "texture", "=", "self", ".", "texture", ";", "texture", ".", "image", "=", "image", ";", "texture", ".", "needsUpdate", "=", "true", ";", "textures", "[", "data", ".", "font", "]", "=", "texture", ";", "self", ".", "texture", "=", "texture", ";", "self", ".", "mesh", ".", "visible", "=", "true", ";", "el", ".", "emit", "(", "'textfontset'", ",", "{", "font", ":", "data", ".", "font", ",", "fontObj", ":", "font", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "error", "(", "err", ".", "message", ")", ";", "error", "(", "err", ".", "stack", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "error", "(", "err", ".", "message", ")", ";", "error", "(", "err", ".", "stack", ")", ";", "}", ")", ";", "}" ]
Load font for geometry, load font image for material, and apply.
[ "Load", "font", "for", "geometry", "load", "font", "image", "for", "material", "and", "apply", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/text.js#L194-L249
train
aframevr/aframe
src/components/text.js
function () { var anchor; var baseline; var el = this.el; var data = this.data; var geometry = this.geometry; var geometryComponent; var height; var layout; var mesh = this.mesh; var textRenderWidth; var textScale; var width; var x; var y; if (!geometry.layout) { return; } // Determine width to use (defined width, geometry's width, or default width). geometryComponent = el.getAttribute('geometry'); width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH; // Determine wrap pixel count. Either specified or by experimental fudge factor. // Note that experimental factor will never be correct for variable width fonts. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount, this.currentFont.widthFactor); textScale = width / textRenderWidth; // Determine height to use. layout = geometry.layout; height = textScale * (layout.height + layout.descender); // Update geometry dimensions to match text layout if width and height are set to 0. // For example, scales a plane to fit text. if (geometryComponent && geometryComponent.primitive === 'plane') { if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); } if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); } } // Calculate X position to anchor text left, center, or right. anchor = data.anchor === 'align' ? data.align : data.anchor; if (anchor === 'left') { x = 0; } else if (anchor === 'right') { x = -1 * layout.width; } else if (anchor === 'center') { x = -1 * layout.width / 2; } else { throw new TypeError('Invalid text.anchor property value', anchor); } // Calculate Y position to anchor text top, center, or bottom. baseline = data.baseline; if (baseline === 'bottom') { y = 0; } else if (baseline === 'top') { y = -1 * layout.height + layout.ascender; } else if (baseline === 'center') { y = -1 * layout.height / 2; } else { throw new TypeError('Invalid text.baseline property value', baseline); } // Position and scale mesh to apply layout. mesh.position.x = x * textScale + data.xOffset; mesh.position.y = y * textScale; // Place text slightly in front to avoid Z-fighting. mesh.position.z = data.zOffset; mesh.scale.set(textScale, -1 * textScale, textScale); }
javascript
function () { var anchor; var baseline; var el = this.el; var data = this.data; var geometry = this.geometry; var geometryComponent; var height; var layout; var mesh = this.mesh; var textRenderWidth; var textScale; var width; var x; var y; if (!geometry.layout) { return; } // Determine width to use (defined width, geometry's width, or default width). geometryComponent = el.getAttribute('geometry'); width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH; // Determine wrap pixel count. Either specified or by experimental fudge factor. // Note that experimental factor will never be correct for variable width fonts. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount, this.currentFont.widthFactor); textScale = width / textRenderWidth; // Determine height to use. layout = geometry.layout; height = textScale * (layout.height + layout.descender); // Update geometry dimensions to match text layout if width and height are set to 0. // For example, scales a plane to fit text. if (geometryComponent && geometryComponent.primitive === 'plane') { if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); } if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); } } // Calculate X position to anchor text left, center, or right. anchor = data.anchor === 'align' ? data.align : data.anchor; if (anchor === 'left') { x = 0; } else if (anchor === 'right') { x = -1 * layout.width; } else if (anchor === 'center') { x = -1 * layout.width / 2; } else { throw new TypeError('Invalid text.anchor property value', anchor); } // Calculate Y position to anchor text top, center, or bottom. baseline = data.baseline; if (baseline === 'bottom') { y = 0; } else if (baseline === 'top') { y = -1 * layout.height + layout.ascender; } else if (baseline === 'center') { y = -1 * layout.height / 2; } else { throw new TypeError('Invalid text.baseline property value', baseline); } // Position and scale mesh to apply layout. mesh.position.x = x * textScale + data.xOffset; mesh.position.y = y * textScale; // Place text slightly in front to avoid Z-fighting. mesh.position.z = data.zOffset; mesh.scale.set(textScale, -1 * textScale, textScale); }
[ "function", "(", ")", "{", "var", "anchor", ";", "var", "baseline", ";", "var", "el", "=", "this", ".", "el", ";", "var", "data", "=", "this", ".", "data", ";", "var", "geometry", "=", "this", ".", "geometry", ";", "var", "geometryComponent", ";", "var", "height", ";", "var", "layout", ";", "var", "mesh", "=", "this", ".", "mesh", ";", "var", "textRenderWidth", ";", "var", "textScale", ";", "var", "width", ";", "var", "x", ";", "var", "y", ";", "if", "(", "!", "geometry", ".", "layout", ")", "{", "return", ";", "}", "geometryComponent", "=", "el", ".", "getAttribute", "(", "'geometry'", ")", ";", "width", "=", "data", ".", "width", "||", "(", "geometryComponent", "&&", "geometryComponent", ".", "width", ")", "||", "DEFAULT_WIDTH", ";", "textRenderWidth", "=", "computeWidth", "(", "data", ".", "wrapPixels", ",", "data", ".", "wrapCount", ",", "this", ".", "currentFont", ".", "widthFactor", ")", ";", "textScale", "=", "width", "/", "textRenderWidth", ";", "layout", "=", "geometry", ".", "layout", ";", "height", "=", "textScale", "*", "(", "layout", ".", "height", "+", "layout", ".", "descender", ")", ";", "if", "(", "geometryComponent", "&&", "geometryComponent", ".", "primitive", "===", "'plane'", ")", "{", "if", "(", "!", "geometryComponent", ".", "width", ")", "{", "el", ".", "setAttribute", "(", "'geometry'", ",", "'width'", ",", "width", ")", ";", "}", "if", "(", "!", "geometryComponent", ".", "height", ")", "{", "el", ".", "setAttribute", "(", "'geometry'", ",", "'height'", ",", "height", ")", ";", "}", "}", "anchor", "=", "data", ".", "anchor", "===", "'align'", "?", "data", ".", "align", ":", "data", ".", "anchor", ";", "if", "(", "anchor", "===", "'left'", ")", "{", "x", "=", "0", ";", "}", "else", "if", "(", "anchor", "===", "'right'", ")", "{", "x", "=", "-", "1", "*", "layout", ".", "width", ";", "}", "else", "if", "(", "anchor", "===", "'center'", ")", "{", "x", "=", "-", "1", "*", "layout", ".", "width", "/", "2", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'Invalid text.anchor property value'", ",", "anchor", ")", ";", "}", "baseline", "=", "data", ".", "baseline", ";", "if", "(", "baseline", "===", "'bottom'", ")", "{", "y", "=", "0", ";", "}", "else", "if", "(", "baseline", "===", "'top'", ")", "{", "y", "=", "-", "1", "*", "layout", ".", "height", "+", "layout", ".", "ascender", ";", "}", "else", "if", "(", "baseline", "===", "'center'", ")", "{", "y", "=", "-", "1", "*", "layout", ".", "height", "/", "2", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'Invalid text.baseline property value'", ",", "baseline", ")", ";", "}", "mesh", ".", "position", ".", "x", "=", "x", "*", "textScale", "+", "data", ".", "xOffset", ";", "mesh", ".", "position", ".", "y", "=", "y", "*", "textScale", ";", "mesh", ".", "position", ".", "z", "=", "data", ".", "zOffset", ";", "mesh", ".", "scale", ".", "set", "(", "textScale", ",", "-", "1", "*", "textScale", ",", "textScale", ")", ";", "}" ]
Update layout with anchor, alignment, baseline, and considering any meshes.
[ "Update", "layout", "with", "anchor", "alignment", "baseline", "and", "considering", "any", "meshes", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/text.js#L266-L335
train
aframevr/aframe
src/components/text.js
computeFontWidthFactor
function computeFontWidthFactor (font) { var sum = 0; var digitsum = 0; var digits = 0; font.chars.map(function (ch) { sum += ch.xadvance; if (ch.id >= 48 && ch.id <= 57) { digits++; digitsum += ch.xadvance; } }); return digits ? digitsum / digits : sum / font.chars.length; }
javascript
function computeFontWidthFactor (font) { var sum = 0; var digitsum = 0; var digits = 0; font.chars.map(function (ch) { sum += ch.xadvance; if (ch.id >= 48 && ch.id <= 57) { digits++; digitsum += ch.xadvance; } }); return digits ? digitsum / digits : sum / font.chars.length; }
[ "function", "computeFontWidthFactor", "(", "font", ")", "{", "var", "sum", "=", "0", ";", "var", "digitsum", "=", "0", ";", "var", "digits", "=", "0", ";", "font", ".", "chars", ".", "map", "(", "function", "(", "ch", ")", "{", "sum", "+=", "ch", ".", "xadvance", ";", "if", "(", "ch", ".", "id", ">=", "48", "&&", "ch", ".", "id", "<=", "57", ")", "{", "digits", "++", ";", "digitsum", "+=", "ch", ".", "xadvance", ";", "}", "}", ")", ";", "return", "digits", "?", "digitsum", "/", "digits", ":", "sum", "/", "font", ".", "chars", ".", "length", ";", "}" ]
Compute default font width factor to use.
[ "Compute", "default", "font", "width", "factor", "to", "use", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/text.js#L455-L467
train
aframevr/aframe
src/components/text.js
PromiseCache
function PromiseCache () { var cache = this.cache = {}; this.get = function (key, promiseGenerator) { if (key in cache) { return cache[key]; } cache[key] = promiseGenerator(); return cache[key]; }; }
javascript
function PromiseCache () { var cache = this.cache = {}; this.get = function (key, promiseGenerator) { if (key in cache) { return cache[key]; } cache[key] = promiseGenerator(); return cache[key]; }; }
[ "function", "PromiseCache", "(", ")", "{", "var", "cache", "=", "this", ".", "cache", "=", "{", "}", ";", "this", ".", "get", "=", "function", "(", "key", ",", "promiseGenerator", ")", "{", "if", "(", "key", "in", "cache", ")", "{", "return", "cache", "[", "key", "]", ";", "}", "cache", "[", "key", "]", "=", "promiseGenerator", "(", ")", ";", "return", "cache", "[", "key", "]", ";", "}", ";", "}" ]
Get or create a promise given a key and promise generator. @todo Move to a utility and use in other parts of A-Frame.
[ "Get", "or", "create", "a", "promise", "given", "a", "key", "and", "promise", "generator", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/text.js#L473-L483
train
aframevr/aframe
src/utils/tracked-controls.js
findMatchingControllerWebVR
function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand, filterControllerIndex) { var controller; var i; var matchingControllerOccurence = 0; var targetControllerMatch = filterControllerIndex || 0; for (i = 0; i < controllers.length; i++) { controller = controllers[i]; // Determine if the controller ID matches our criteria. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) { continue; } if (!filterIdPrefix && controller.id !== filterIdExact) { continue; } // If the hand filter and controller handedness are defined we compare them. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; } // If we have detected an unhanded controller and the component was asking // for a particular hand, we need to treat the controllers in the array as // pairs of controllers. This effectively means that we need to skip // NUM_HANDS matches for each controller number, instead of 1. if (filterHand && !controller.hand) { targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1); } // We are looking for the nth occurence of a matching controller // (n equals targetControllerMatch). if (matchingControllerOccurence === targetControllerMatch) { return controller; } ++matchingControllerOccurence; } return undefined; }
javascript
function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand, filterControllerIndex) { var controller; var i; var matchingControllerOccurence = 0; var targetControllerMatch = filterControllerIndex || 0; for (i = 0; i < controllers.length; i++) { controller = controllers[i]; // Determine if the controller ID matches our criteria. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) { continue; } if (!filterIdPrefix && controller.id !== filterIdExact) { continue; } // If the hand filter and controller handedness are defined we compare them. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; } // If we have detected an unhanded controller and the component was asking // for a particular hand, we need to treat the controllers in the array as // pairs of controllers. This effectively means that we need to skip // NUM_HANDS matches for each controller number, instead of 1. if (filterHand && !controller.hand) { targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1); } // We are looking for the nth occurence of a matching controller // (n equals targetControllerMatch). if (matchingControllerOccurence === targetControllerMatch) { return controller; } ++matchingControllerOccurence; } return undefined; }
[ "function", "findMatchingControllerWebVR", "(", "controllers", ",", "filterIdExact", ",", "filterIdPrefix", ",", "filterHand", ",", "filterControllerIndex", ")", "{", "var", "controller", ";", "var", "i", ";", "var", "matchingControllerOccurence", "=", "0", ";", "var", "targetControllerMatch", "=", "filterControllerIndex", "||", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "controllers", ".", "length", ";", "i", "++", ")", "{", "controller", "=", "controllers", "[", "i", "]", ";", "if", "(", "filterIdPrefix", "&&", "!", "controller", ".", "id", ".", "startsWith", "(", "filterIdPrefix", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "filterIdPrefix", "&&", "controller", ".", "id", "!==", "filterIdExact", ")", "{", "continue", ";", "}", "if", "(", "filterHand", "&&", "controller", ".", "hand", "&&", "filterHand", "!==", "controller", ".", "hand", ")", "{", "continue", ";", "}", "if", "(", "filterHand", "&&", "!", "controller", ".", "hand", ")", "{", "targetControllerMatch", "=", "NUM_HANDS", "*", "filterControllerIndex", "+", "(", "(", "filterHand", "===", "DEFAULT_HANDEDNESS", ")", "?", "0", ":", "1", ")", ";", "}", "if", "(", "matchingControllerOccurence", "===", "targetControllerMatch", ")", "{", "return", "controller", ";", "}", "++", "matchingControllerOccurence", ";", "}", "return", "undefined", ";", "}" ]
Walk through the given controllers to find any where the device ID equals filterIdExact, or startsWith filterIdPrefix. A controller where this considered true is considered a 'match'. For each matching controller: If filterHand is set, and the controller: is handed, we further verify that controller.hand equals filterHand. is unhanded (controller.hand is ''), we skip until we have found a number of matching controllers that equals filterControllerIndex If filterHand is not set, we skip until we have found the nth matching controller, where n equals filterControllerIndex The method should be called with one of: [filterIdExact, filterIdPrefix] AND one or both of: [filterHand, filterControllerIndex] @param {object} controllers - Array of gamepads to search @param {string} filterIdExact - If set, used to find controllers with id === this value @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value @param {object} filterHand - If set, further filters controllers with matching 'hand' property @param {object} filterControllerIndex - Find the nth matching controller, where n equals filterControllerIndex. defaults to 0.
[ "Walk", "through", "the", "given", "controllers", "to", "find", "any", "where", "the", "device", "ID", "equals", "filterIdExact", "or", "startsWith", "filterIdPrefix", ".", "A", "controller", "where", "this", "considered", "true", "is", "considered", "a", "match", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/tracked-controls.js#L115-L149
train
aframevr/aframe
src/components/tracked-controls-webvr.js
function (controllerPosition) { // Use controllerPosition and deltaControllerPosition to avoid creating variables. var controller = this.controller; var controllerEuler = this.controllerEuler; var controllerQuaternion = this.controllerQuaternion; var deltaControllerPosition = this.deltaControllerPosition; var hand; var headEl; var headObject3D; var pose; var userHeight; headEl = this.getHeadElement(); headObject3D = headEl.object3D; userHeight = this.defaultUserHeight(); pose = controller.pose; hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS; // Use camera position as head position. controllerPosition.copy(headObject3D.position); // Set offset for degenerate "arm model" to elbow. deltaControllerPosition.set( EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0), EYES_TO_ELBOW.y, // Lower than our eyes. EYES_TO_ELBOW.z); // Slightly out in front. // Scale offset by user height. deltaControllerPosition.multiplyScalar(userHeight); // Apply camera Y rotation (not X or Z, so you can look down at your hand). deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y); // Apply rotated offset to position. controllerPosition.add(deltaControllerPosition); // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z); // Scale offset by user height. deltaControllerPosition.multiplyScalar(userHeight); // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm). if (pose.orientation) { controllerQuaternion.fromArray(pose.orientation); } else { controllerQuaternion.copy(headObject3D.quaternion); } controllerEuler.setFromQuaternion(controllerQuaternion); controllerEuler.set(controllerEuler.x, controllerEuler.y, 0); deltaControllerPosition.applyEuler(controllerEuler); // Apply rotated offset to position. controllerPosition.add(deltaControllerPosition); }
javascript
function (controllerPosition) { // Use controllerPosition and deltaControllerPosition to avoid creating variables. var controller = this.controller; var controllerEuler = this.controllerEuler; var controllerQuaternion = this.controllerQuaternion; var deltaControllerPosition = this.deltaControllerPosition; var hand; var headEl; var headObject3D; var pose; var userHeight; headEl = this.getHeadElement(); headObject3D = headEl.object3D; userHeight = this.defaultUserHeight(); pose = controller.pose; hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS; // Use camera position as head position. controllerPosition.copy(headObject3D.position); // Set offset for degenerate "arm model" to elbow. deltaControllerPosition.set( EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0), EYES_TO_ELBOW.y, // Lower than our eyes. EYES_TO_ELBOW.z); // Slightly out in front. // Scale offset by user height. deltaControllerPosition.multiplyScalar(userHeight); // Apply camera Y rotation (not X or Z, so you can look down at your hand). deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y); // Apply rotated offset to position. controllerPosition.add(deltaControllerPosition); // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z); // Scale offset by user height. deltaControllerPosition.multiplyScalar(userHeight); // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm). if (pose.orientation) { controllerQuaternion.fromArray(pose.orientation); } else { controllerQuaternion.copy(headObject3D.quaternion); } controllerEuler.setFromQuaternion(controllerQuaternion); controllerEuler.set(controllerEuler.x, controllerEuler.y, 0); deltaControllerPosition.applyEuler(controllerEuler); // Apply rotated offset to position. controllerPosition.add(deltaControllerPosition); }
[ "function", "(", "controllerPosition", ")", "{", "var", "controller", "=", "this", ".", "controller", ";", "var", "controllerEuler", "=", "this", ".", "controllerEuler", ";", "var", "controllerQuaternion", "=", "this", ".", "controllerQuaternion", ";", "var", "deltaControllerPosition", "=", "this", ".", "deltaControllerPosition", ";", "var", "hand", ";", "var", "headEl", ";", "var", "headObject3D", ";", "var", "pose", ";", "var", "userHeight", ";", "headEl", "=", "this", ".", "getHeadElement", "(", ")", ";", "headObject3D", "=", "headEl", ".", "object3D", ";", "userHeight", "=", "this", ".", "defaultUserHeight", "(", ")", ";", "pose", "=", "controller", ".", "pose", ";", "hand", "=", "(", "controller", "?", "controller", ".", "hand", ":", "undefined", ")", "||", "DEFAULT_HANDEDNESS", ";", "controllerPosition", ".", "copy", "(", "headObject3D", ".", "position", ")", ";", "deltaControllerPosition", ".", "set", "(", "EYES_TO_ELBOW", ".", "x", "*", "(", "hand", "===", "'left'", "?", "-", "1", ":", "hand", "===", "'right'", "?", "1", ":", "0", ")", ",", "EYES_TO_ELBOW", ".", "y", ",", "EYES_TO_ELBOW", ".", "z", ")", ";", "deltaControllerPosition", ".", "multiplyScalar", "(", "userHeight", ")", ";", "deltaControllerPosition", ".", "applyAxisAngle", "(", "headObject3D", ".", "up", ",", "headObject3D", ".", "rotation", ".", "y", ")", ";", "controllerPosition", ".", "add", "(", "deltaControllerPosition", ")", ";", "deltaControllerPosition", ".", "set", "(", "FOREARM", ".", "x", ",", "FOREARM", ".", "y", ",", "FOREARM", ".", "z", ")", ";", "deltaControllerPosition", ".", "multiplyScalar", "(", "userHeight", ")", ";", "if", "(", "pose", ".", "orientation", ")", "{", "controllerQuaternion", ".", "fromArray", "(", "pose", ".", "orientation", ")", ";", "}", "else", "{", "controllerQuaternion", ".", "copy", "(", "headObject3D", ".", "quaternion", ")", ";", "}", "controllerEuler", ".", "setFromQuaternion", "(", "controllerQuaternion", ")", ";", "controllerEuler", ".", "set", "(", "controllerEuler", ".", "x", ",", "controllerEuler", ".", "y", ",", "0", ")", ";", "deltaControllerPosition", ".", "applyEuler", "(", "controllerEuler", ")", ";", "controllerPosition", ".", "add", "(", "deltaControllerPosition", ")", ";", "}" ]
Applies an artificial arm model to simulate elbow to wrist positioning based on the orientation of the controller. @param {object} controllerPosition - Existing vector to update with controller position.
[ "Applies", "an", "artificial", "arm", "model", "to", "simulate", "elbow", "to", "wrist", "positioning", "based", "on", "the", "orientation", "of", "the", "controller", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/tracked-controls-webvr.js#L116-L164
train
aframevr/aframe
src/components/tracked-controls-webvr.js
function () { var buttonState; var controller = this.controller; var id; if (!controller) { return; } // Check every button. for (id = 0; id < controller.buttons.length; ++id) { // Initialize button state. if (!this.buttonStates[id]) { this.buttonStates[id] = {pressed: false, touched: false, value: 0}; } if (!this.buttonEventDetails[id]) { this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]}; } buttonState = controller.buttons[id]; this.handleButton(id, buttonState); } // Check axes. this.handleAxes(); }
javascript
function () { var buttonState; var controller = this.controller; var id; if (!controller) { return; } // Check every button. for (id = 0; id < controller.buttons.length; ++id) { // Initialize button state. if (!this.buttonStates[id]) { this.buttonStates[id] = {pressed: false, touched: false, value: 0}; } if (!this.buttonEventDetails[id]) { this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]}; } buttonState = controller.buttons[id]; this.handleButton(id, buttonState); } // Check axes. this.handleAxes(); }
[ "function", "(", ")", "{", "var", "buttonState", ";", "var", "controller", "=", "this", ".", "controller", ";", "var", "id", ";", "if", "(", "!", "controller", ")", "{", "return", ";", "}", "for", "(", "id", "=", "0", ";", "id", "<", "controller", ".", "buttons", ".", "length", ";", "++", "id", ")", "{", "if", "(", "!", "this", ".", "buttonStates", "[", "id", "]", ")", "{", "this", ".", "buttonStates", "[", "id", "]", "=", "{", "pressed", ":", "false", ",", "touched", ":", "false", ",", "value", ":", "0", "}", ";", "}", "if", "(", "!", "this", ".", "buttonEventDetails", "[", "id", "]", ")", "{", "this", ".", "buttonEventDetails", "[", "id", "]", "=", "{", "id", ":", "id", ",", "state", ":", "this", ".", "buttonStates", "[", "id", "]", "}", ";", "}", "buttonState", "=", "controller", ".", "buttons", "[", "id", "]", ";", "this", ".", "handleButton", "(", "id", ",", "buttonState", ")", ";", "}", "this", ".", "handleAxes", "(", ")", ";", "}" ]
Handle button changes including axes, presses, touches, values.
[ "Handle", "button", "changes", "including", "axes", "presses", "touches", "values", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/tracked-controls-webvr.js#L209-L231
train
aframevr/aframe
src/components/tracked-controls-webvr.js
function (id, buttonState) { var changed; changed = this.handlePress(id, buttonState) | this.handleTouch(id, buttonState) | this.handleValue(id, buttonState); if (!changed) { return false; } this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false); return true; }
javascript
function (id, buttonState) { var changed; changed = this.handlePress(id, buttonState) | this.handleTouch(id, buttonState) | this.handleValue(id, buttonState); if (!changed) { return false; } this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false); return true; }
[ "function", "(", "id", ",", "buttonState", ")", "{", "var", "changed", ";", "changed", "=", "this", ".", "handlePress", "(", "id", ",", "buttonState", ")", "|", "this", ".", "handleTouch", "(", "id", ",", "buttonState", ")", "|", "this", ".", "handleValue", "(", "id", ",", "buttonState", ")", ";", "if", "(", "!", "changed", ")", "{", "return", "false", ";", "}", "this", ".", "el", ".", "emit", "(", "EVENTS", ".", "BUTTONCHANGED", ",", "this", ".", "buttonEventDetails", "[", "id", "]", ",", "false", ")", ";", "return", "true", ";", "}" ]
Handle presses and touches for a single button. @param {number} id - Index of button in Gamepad button array. @param {number} buttonState - Value of button state from 0 to 1. @returns {boolean} Whether button has changed in any way.
[ "Handle", "presses", "and", "touches", "for", "a", "single", "button", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/tracked-controls-webvr.js#L240-L248
train
aframevr/aframe
src/components/scene/screenshot.js
function (projection) { var el = this.el; var size; var camera; var cubeCamera; // Configure camera. if (projection === 'perspective') { // Quad is only used in equirectangular mode. Hide it in this case. this.quad.visible = false; // Use scene camera. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera; size = {width: this.data.width, height: this.data.height}; } else { // Use ortho camera. camera = this.camera; // Create cube camera and copy position from scene camera. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far, Math.min(this.cubeMapSize, 2048)); // Copy camera position into cube camera; el.camera.getWorldPosition(cubeCamera.position); el.camera.getWorldQuaternion(cubeCamera.quaternion); // Render scene with cube camera. cubeCamera.update(el.renderer, el.object3D); this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture; size = {width: this.data.width, height: this.data.height}; // Use quad to project image taken by the cube camera. this.quad.visible = true; } return { camera: camera, size: size, projection: projection }; }
javascript
function (projection) { var el = this.el; var size; var camera; var cubeCamera; // Configure camera. if (projection === 'perspective') { // Quad is only used in equirectangular mode. Hide it in this case. this.quad.visible = false; // Use scene camera. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera; size = {width: this.data.width, height: this.data.height}; } else { // Use ortho camera. camera = this.camera; // Create cube camera and copy position from scene camera. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far, Math.min(this.cubeMapSize, 2048)); // Copy camera position into cube camera; el.camera.getWorldPosition(cubeCamera.position); el.camera.getWorldQuaternion(cubeCamera.quaternion); // Render scene with cube camera. cubeCamera.update(el.renderer, el.object3D); this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture; size = {width: this.data.width, height: this.data.height}; // Use quad to project image taken by the cube camera. this.quad.visible = true; } return { camera: camera, size: size, projection: projection }; }
[ "function", "(", "projection", ")", "{", "var", "el", "=", "this", ".", "el", ";", "var", "size", ";", "var", "camera", ";", "var", "cubeCamera", ";", "if", "(", "projection", "===", "'perspective'", ")", "{", "this", ".", "quad", ".", "visible", "=", "false", ";", "camera", "=", "(", "this", ".", "data", ".", "camera", "&&", "this", ".", "data", ".", "camera", ".", "components", ".", "camera", ".", "camera", ")", "||", "el", ".", "camera", ";", "size", "=", "{", "width", ":", "this", ".", "data", ".", "width", ",", "height", ":", "this", ".", "data", ".", "height", "}", ";", "}", "else", "{", "camera", "=", "this", ".", "camera", ";", "cubeCamera", "=", "new", "THREE", ".", "CubeCamera", "(", "el", ".", "camera", ".", "near", ",", "el", ".", "camera", ".", "far", ",", "Math", ".", "min", "(", "this", ".", "cubeMapSize", ",", "2048", ")", ")", ";", "el", ".", "camera", ".", "getWorldPosition", "(", "cubeCamera", ".", "position", ")", ";", "el", ".", "camera", ".", "getWorldQuaternion", "(", "cubeCamera", ".", "quaternion", ")", ";", "cubeCamera", ".", "update", "(", "el", ".", "renderer", ",", "el", ".", "object3D", ")", ";", "this", ".", "quad", ".", "material", ".", "uniforms", ".", "map", ".", "value", "=", "cubeCamera", ".", "renderTarget", ".", "texture", ";", "size", "=", "{", "width", ":", "this", ".", "data", ".", "width", ",", "height", ":", "this", ".", "data", ".", "height", "}", ";", "this", ".", "quad", ".", "visible", "=", "true", ";", "}", "return", "{", "camera", ":", "camera", ",", "size", ":", "size", ",", "projection", ":", "projection", "}", ";", "}" ]
Capture a screenshot of the scene. @param {string} projection - Screenshot projection (equirectangular or perspective).
[ "Capture", "a", "screenshot", "of", "the", "scene", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/screenshot.js#L133-L166
train
aframevr/aframe
src/components/scene/screenshot.js
function (projection) { var isVREnabled = this.el.renderer.vr.enabled; var renderer = this.el.renderer; var params; // Disable VR. renderer.vr.enabled = false; params = this.setCapture(projection); this.renderCapture(params.camera, params.size, params.projection); // Trigger file download. this.saveCapture(); // Restore VR. renderer.vr.enabled = isVREnabled; }
javascript
function (projection) { var isVREnabled = this.el.renderer.vr.enabled; var renderer = this.el.renderer; var params; // Disable VR. renderer.vr.enabled = false; params = this.setCapture(projection); this.renderCapture(params.camera, params.size, params.projection); // Trigger file download. this.saveCapture(); // Restore VR. renderer.vr.enabled = isVREnabled; }
[ "function", "(", "projection", ")", "{", "var", "isVREnabled", "=", "this", ".", "el", ".", "renderer", ".", "vr", ".", "enabled", ";", "var", "renderer", "=", "this", ".", "el", ".", "renderer", ";", "var", "params", ";", "renderer", ".", "vr", ".", "enabled", "=", "false", ";", "params", "=", "this", ".", "setCapture", "(", "projection", ")", ";", "this", ".", "renderCapture", "(", "params", ".", "camera", ",", "params", ".", "size", ",", "params", ".", "projection", ")", ";", "this", ".", "saveCapture", "(", ")", ";", "renderer", ".", "vr", ".", "enabled", "=", "isVREnabled", ";", "}" ]
Maintained for backwards compatibility.
[ "Maintained", "for", "backwards", "compatibility", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/screenshot.js#L171-L183
train
aframevr/aframe
src/components/scene/screenshot.js
function () { this.canvas.toBlob(function (blob) { var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png'; var linkEl = document.createElement('a'); var url = URL.createObjectURL(blob); linkEl.href = url; linkEl.setAttribute('download', fileName); linkEl.innerHTML = 'downloading...'; linkEl.style.display = 'none'; document.body.appendChild(linkEl); setTimeout(function () { linkEl.click(); document.body.removeChild(linkEl); }, 1); }, 'image/png'); }
javascript
function () { this.canvas.toBlob(function (blob) { var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png'; var linkEl = document.createElement('a'); var url = URL.createObjectURL(blob); linkEl.href = url; linkEl.setAttribute('download', fileName); linkEl.innerHTML = 'downloading...'; linkEl.style.display = 'none'; document.body.appendChild(linkEl); setTimeout(function () { linkEl.click(); document.body.removeChild(linkEl); }, 1); }, 'image/png'); }
[ "function", "(", ")", "{", "this", ".", "canvas", ".", "toBlob", "(", "function", "(", "blob", ")", "{", "var", "fileName", "=", "'screenshot-'", "+", "document", ".", "title", ".", "toLowerCase", "(", ")", "+", "'-'", "+", "Date", ".", "now", "(", ")", "+", "'.png'", ";", "var", "linkEl", "=", "document", ".", "createElement", "(", "'a'", ")", ";", "var", "url", "=", "URL", ".", "createObjectURL", "(", "blob", ")", ";", "linkEl", ".", "href", "=", "url", ";", "linkEl", ".", "setAttribute", "(", "'download'", ",", "fileName", ")", ";", "linkEl", ".", "innerHTML", "=", "'downloading...'", ";", "linkEl", ".", "style", ".", "display", "=", "'none'", ";", "document", ".", "body", ".", "appendChild", "(", "linkEl", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "linkEl", ".", "click", "(", ")", ";", "document", ".", "body", ".", "removeChild", "(", "linkEl", ")", ";", "}", ",", "1", ")", ";", "}", ",", "'image/png'", ")", ";", "}" ]
Download capture to file.
[ "Download", "capture", "to", "file", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/screenshot.js#L238-L253
train
aframevr/aframe
src/utils/styleParser.js
styleParse
function styleParse (str, obj) { var chunks; var i; var item; var pos; var key; var val; obj = obj || {}; chunks = getKeyValueChunks(str); for (i = 0; i < chunks.length; i++) { item = chunks[i]; if (!item) { continue; } // Split with `.indexOf` rather than `.split` because the value may also contain colons. pos = item.indexOf(':'); key = item.substr(0, pos).trim(); val = item.substr(pos + 1).trim(); obj[key] = val; } return obj; }
javascript
function styleParse (str, obj) { var chunks; var i; var item; var pos; var key; var val; obj = obj || {}; chunks = getKeyValueChunks(str); for (i = 0; i < chunks.length; i++) { item = chunks[i]; if (!item) { continue; } // Split with `.indexOf` rather than `.split` because the value may also contain colons. pos = item.indexOf(':'); key = item.substr(0, pos).trim(); val = item.substr(pos + 1).trim(); obj[key] = val; } return obj; }
[ "function", "styleParse", "(", "str", ",", "obj", ")", "{", "var", "chunks", ";", "var", "i", ";", "var", "item", ";", "var", "pos", ";", "var", "key", ";", "var", "val", ";", "obj", "=", "obj", "||", "{", "}", ";", "chunks", "=", "getKeyValueChunks", "(", "str", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "chunks", ".", "length", ";", "i", "++", ")", "{", "item", "=", "chunks", "[", "i", "]", ";", "if", "(", "!", "item", ")", "{", "continue", ";", "}", "pos", "=", "item", ".", "indexOf", "(", "':'", ")", ";", "key", "=", "item", ".", "substr", "(", "0", ",", "pos", ")", ".", "trim", "(", ")", ";", "val", "=", "item", ".", "substr", "(", "pos", "+", "1", ")", ".", "trim", "(", ")", ";", "obj", "[", "key", "]", "=", "val", ";", "}", "return", "obj", ";", "}" ]
Convert a style attribute string to an object. @param {object} str - Attribute string. @param {object} obj - Object to reuse as a base, else a new one will be allocated.
[ "Convert", "a", "style", "attribute", "string", "to", "an", "object", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/styleParser.js#L109-L130
train
aframevr/aframe
src/utils/styleParser.js
styleStringify
function styleStringify (obj) { var key; var keyCount = 0; var i = 0; var str = ''; for (key in obj) { keyCount++; } for (key in obj) { str += (key + ': ' + obj[key]); if (i < keyCount - 1) { str += '; '; } i++; } return str; }
javascript
function styleStringify (obj) { var key; var keyCount = 0; var i = 0; var str = ''; for (key in obj) { keyCount++; } for (key in obj) { str += (key + ': ' + obj[key]); if (i < keyCount - 1) { str += '; '; } i++; } return str; }
[ "function", "styleStringify", "(", "obj", ")", "{", "var", "key", ";", "var", "keyCount", "=", "0", ";", "var", "i", "=", "0", ";", "var", "str", "=", "''", ";", "for", "(", "key", "in", "obj", ")", "{", "keyCount", "++", ";", "}", "for", "(", "key", "in", "obj", ")", "{", "str", "+=", "(", "key", "+", "': '", "+", "obj", "[", "key", "]", ")", ";", "if", "(", "i", "<", "keyCount", "-", "1", ")", "{", "str", "+=", "'; '", ";", "}", "i", "++", ";", "}", "return", "str", ";", "}" ]
Convert an object into an attribute string
[ "Convert", "an", "object", "into", "an", "attribute", "string" ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/styleParser.js#L135-L149
train
naptha/tesseract.js
src/common/dump.js
deindent
function deindent(html){ var lines = html.split('\n') if(lines[0].substring(0, 2) === " "){ for (var i = 0; i < lines.length; i++) { if (lines[i].substring(0,2) === " ") { lines[i] = lines[i].slice(2) } }; } return lines.join('\n') }
javascript
function deindent(html){ var lines = html.split('\n') if(lines[0].substring(0, 2) === " "){ for (var i = 0; i < lines.length; i++) { if (lines[i].substring(0,2) === " ") { lines[i] = lines[i].slice(2) } }; } return lines.join('\n') }
[ "function", "deindent", "(", "html", ")", "{", "var", "lines", "=", "html", ".", "split", "(", "'\\n'", ")", "\\n", "if", "(", "lines", "[", "0", "]", ".", "substring", "(", "0", ",", "2", ")", "===", "\" \"", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "if", "(", "lines", "[", "i", "]", ".", "substring", "(", "0", ",", "2", ")", "===", "\" \"", ")", "{", "lines", "[", "i", "]", "=", "lines", "[", "i", "]", ".", "slice", "(", "2", ")", "}", "}", ";", "}", "}" ]
the generated HOCR is excessively indented, so we get rid of that indentation
[ "the", "generated", "HOCR", "is", "excessively", "indented", "so", "we", "get", "rid", "of", "that", "indentation" ]
613a19c7e1b61f26014dd3310fca5391423dd65d
https://github.com/naptha/tesseract.js/blob/613a19c7e1b61f26014dd3310fca5391423dd65d/src/common/dump.js#L154-L164
train
nozzle/react-static
packages/react-static/src/browser/index.js
init
function init() { // In development, we need to open a socket to listen for changes to data if (process.env.REACT_STATIC_ENV === 'development') { const io = require('socket.io-client') const run = async () => { try { const { data: { port }, } = await axios.get('/__react-static__/getMessagePort') const socket = io(`http://localhost:${port}`) socket.on('connect', () => { // Do nothing }) socket.on('message', ({ type }) => { if (type === 'reloadClientData') { reloadClientData() } }) } catch (err) { console.log( 'React-Static data hot-loader websocket encountered the following error:' ) console.error(err) } } run() } if (process.env.REACT_STATIC_DISABLE_PRELOAD === 'false') { startPreloader() } }
javascript
function init() { // In development, we need to open a socket to listen for changes to data if (process.env.REACT_STATIC_ENV === 'development') { const io = require('socket.io-client') const run = async () => { try { const { data: { port }, } = await axios.get('/__react-static__/getMessagePort') const socket = io(`http://localhost:${port}`) socket.on('connect', () => { // Do nothing }) socket.on('message', ({ type }) => { if (type === 'reloadClientData') { reloadClientData() } }) } catch (err) { console.log( 'React-Static data hot-loader websocket encountered the following error:' ) console.error(err) } } run() } if (process.env.REACT_STATIC_DISABLE_PRELOAD === 'false') { startPreloader() } }
[ "function", "init", "(", ")", "{", "if", "(", "process", ".", "env", ".", "REACT_STATIC_ENV", "===", "'development'", ")", "{", "const", "io", "=", "require", "(", "'socket.io-client'", ")", "const", "run", "=", "async", "(", ")", "=>", "{", "try", "{", "const", "{", "data", ":", "{", "port", "}", ",", "}", "=", "await", "axios", ".", "get", "(", "'/__react-static__/getMessagePort'", ")", "const", "socket", "=", "io", "(", "`", "${", "port", "}", "`", ")", "socket", ".", "on", "(", "'connect'", ",", "(", ")", "=>", "{", "}", ")", "socket", ".", "on", "(", "'message'", ",", "(", "{", "type", "}", ")", "=>", "{", "if", "(", "type", "===", "'reloadClientData'", ")", "{", "reloadClientData", "(", ")", "}", "}", ")", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "'React-Static data hot-loader websocket encountered the following error:'", ")", "console", ".", "error", "(", "err", ")", "}", "}", "run", "(", ")", "}", "if", "(", "process", ".", "env", ".", "REACT_STATIC_DISABLE_PRELOAD", "===", "'false'", ")", "{", "startPreloader", "(", ")", "}", "}" ]
When in development, init a socket to listen for data changes When the data changes, we invalidate and reload all of the route data
[ "When", "in", "development", "init", "a", "socket", "to", "listen", "for", "data", "changes", "When", "the", "data", "changes", "we", "invalidate", "and", "reload", "all", "of", "the", "route", "data" ]
045a0e119974f46f68c633ff65116f9d74807caf
https://github.com/nozzle/react-static/blob/045a0e119974f46f68c633ff65116f9d74807caf/packages/react-static/src/browser/index.js#L106-L137
train
verdaccio/verdaccio
src/lib/logger.js
pad
function pad(str) { if (str.length < max) { return str + ' '.repeat(max - str.length); } return str; }
javascript
function pad(str) { if (str.length < max) { return str + ' '.repeat(max - str.length); } return str; }
[ "function", "pad", "(", "str", ")", "{", "if", "(", "str", ".", "length", "<", "max", ")", "{", "return", "str", "+", "' '", ".", "repeat", "(", "max", "-", "str", ".", "length", ")", ";", "}", "return", "str", ";", "}" ]
Apply whitespaces based on the length @param {*} str the log message @return {String}
[ "Apply", "whitespaces", "based", "on", "the", "length" ]
daa7e897b6d093bf8282ff12df3f450bcd73476c
https://github.com/verdaccio/verdaccio/blob/daa7e897b6d093bf8282ff12df3f450bcd73476c/src/lib/logger.js#L179-L184
train
verdaccio/verdaccio
src/lib/logger.js
print
function print(type, msg, obj, colors) { if (typeof type === 'number') { type = calculateLevel(type); } const finalMessage = fillInMsgTemplate(msg, obj, colors); const subsystems = [ { in: green('<--'), out: yellow('-->'), fs: black('-=-'), default: blue('---'), }, { in: '<--', out: '-->', fs: '-=-', default: '---', }, ]; const sub = subsystems[colors ? 0 : 1][obj.sub] || subsystems[+!colors].default; if (colors) { return ` ${levels[type](pad(type))}${white(`${sub} ${finalMessage}`)}`; } else { return ` ${pad(type)}${sub} ${finalMessage}`; } }
javascript
function print(type, msg, obj, colors) { if (typeof type === 'number') { type = calculateLevel(type); } const finalMessage = fillInMsgTemplate(msg, obj, colors); const subsystems = [ { in: green('<--'), out: yellow('-->'), fs: black('-=-'), default: blue('---'), }, { in: '<--', out: '-->', fs: '-=-', default: '---', }, ]; const sub = subsystems[colors ? 0 : 1][obj.sub] || subsystems[+!colors].default; if (colors) { return ` ${levels[type](pad(type))}${white(`${sub} ${finalMessage}`)}`; } else { return ` ${pad(type)}${sub} ${finalMessage}`; } }
[ "function", "print", "(", "type", ",", "msg", ",", "obj", ",", "colors", ")", "{", "if", "(", "typeof", "type", "===", "'number'", ")", "{", "type", "=", "calculateLevel", "(", "type", ")", ";", "}", "const", "finalMessage", "=", "fillInMsgTemplate", "(", "msg", ",", "obj", ",", "colors", ")", ";", "const", "subsystems", "=", "[", "{", "in", ":", "green", "(", "'<--'", ")", ",", "out", ":", "yellow", "(", "'", ")", ",", "fs", ":", "black", "(", "'-=-'", ")", ",", "default", ":", "blue", "(", "'---'", ")", ",", "}", ",", "{", "in", ":", "'<--'", ",", "out", ":", "'", ",", "fs", ":", "'-=-'", ",", "default", ":", "'---'", ",", "}", ",", "]", ";", "const", "sub", "=", "subsystems", "[", "colors", "?", "0", ":", "1", "]", "[", "obj", ".", "sub", "]", "||", "subsystems", "[", "+", "!", "colors", "]", ".", "default", ";", "if", "(", "colors", ")", "{", "return", "`", "${", "levels", "[", "type", "]", "(", "pad", "(", "type", ")", ")", "}", "${", "white", "(", "`", "${", "sub", "}", "${", "finalMessage", "}", "`", ")", "}", "`", ";", "}", "else", "{", "return", "`", "${", "pad", "(", "type", ")", "}", "${", "sub", "}", "${", "finalMessage", "}", "`", ";", "}", "}" ]
Apply colors to a string based on level parameters. @param {*} type @param {*} msg @param {*} obj @param {*} colors @return {String}
[ "Apply", "colors", "to", "a", "string", "based", "on", "level", "parameters", "." ]
daa7e897b6d093bf8282ff12df3f450bcd73476c
https://github.com/verdaccio/verdaccio/blob/daa7e897b6d093bf8282ff12df3f450bcd73476c/src/lib/logger.js#L227-L254
train
Shopify/draggable
src/Plugins/SwapAnimation/SwapAnimation.js
animate
function animate(from, to, {duration, easingFunction, horizontal}) { for (const element of [from, to]) { element.style.pointerEvents = 'none'; } if (horizontal) { const width = from.offsetWidth; from.style.transform = `translate3d(${width}px, 0, 0)`; to.style.transform = `translate3d(-${width}px, 0, 0)`; } else { const height = from.offsetHeight; from.style.transform = `translate3d(0, ${height}px, 0)`; to.style.transform = `translate3d(0, -${height}px, 0)`; } requestAnimationFrame(() => { for (const element of [from, to]) { element.addEventListener('transitionend', resetElementOnTransitionEnd); element.style.transition = `transform ${duration}ms ${easingFunction}`; element.style.transform = ''; } }); }
javascript
function animate(from, to, {duration, easingFunction, horizontal}) { for (const element of [from, to]) { element.style.pointerEvents = 'none'; } if (horizontal) { const width = from.offsetWidth; from.style.transform = `translate3d(${width}px, 0, 0)`; to.style.transform = `translate3d(-${width}px, 0, 0)`; } else { const height = from.offsetHeight; from.style.transform = `translate3d(0, ${height}px, 0)`; to.style.transform = `translate3d(0, -${height}px, 0)`; } requestAnimationFrame(() => { for (const element of [from, to]) { element.addEventListener('transitionend', resetElementOnTransitionEnd); element.style.transition = `transform ${duration}ms ${easingFunction}`; element.style.transform = ''; } }); }
[ "function", "animate", "(", "from", ",", "to", ",", "{", "duration", ",", "easingFunction", ",", "horizontal", "}", ")", "{", "for", "(", "const", "element", "of", "[", "from", ",", "to", "]", ")", "{", "element", ".", "style", ".", "pointerEvents", "=", "'none'", ";", "}", "if", "(", "horizontal", ")", "{", "const", "width", "=", "from", ".", "offsetWidth", ";", "from", ".", "style", ".", "transform", "=", "`", "${", "width", "}", "`", ";", "to", ".", "style", ".", "transform", "=", "`", "${", "width", "}", "`", ";", "}", "else", "{", "const", "height", "=", "from", ".", "offsetHeight", ";", "from", ".", "style", ".", "transform", "=", "`", "${", "height", "}", "`", ";", "to", ".", "style", ".", "transform", "=", "`", "${", "height", "}", "`", ";", "}", "requestAnimationFrame", "(", "(", ")", "=>", "{", "for", "(", "const", "element", "of", "[", "from", ",", "to", "]", ")", "{", "element", ".", "addEventListener", "(", "'transitionend'", ",", "resetElementOnTransitionEnd", ")", ";", "element", ".", "style", ".", "transition", "=", "`", "${", "duration", "}", "${", "easingFunction", "}", "`", ";", "element", ".", "style", ".", "transform", "=", "''", ";", "}", "}", ")", ";", "}" ]
Animates two elements @param {HTMLElement} from @param {HTMLElement} to @param {Object} options @param {Number} options.duration @param {String} options.easingFunction @param {String} options.horizontal @private
[ "Animates", "two", "elements" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Plugins/SwapAnimation/SwapAnimation.js#L109-L131
train
Shopify/draggable
src/Plugins/SwapAnimation/SwapAnimation.js
resetElementOnTransitionEnd
function resetElementOnTransitionEnd(event) { event.target.style.transition = ''; event.target.style.pointerEvents = ''; event.target.removeEventListener('transitionend', resetElementOnTransitionEnd); }
javascript
function resetElementOnTransitionEnd(event) { event.target.style.transition = ''; event.target.style.pointerEvents = ''; event.target.removeEventListener('transitionend', resetElementOnTransitionEnd); }
[ "function", "resetElementOnTransitionEnd", "(", "event", ")", "{", "event", ".", "target", ".", "style", ".", "transition", "=", "''", ";", "event", ".", "target", ".", "style", ".", "pointerEvents", "=", "''", ";", "event", ".", "target", ".", "removeEventListener", "(", "'transitionend'", ",", "resetElementOnTransitionEnd", ")", ";", "}" ]
Resets animation style properties after animation has completed @param {Event} event @private
[ "Resets", "animation", "style", "properties", "after", "animation", "has", "completed" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Plugins/SwapAnimation/SwapAnimation.js#L138-L142
train
Shopify/draggable
src/Droppable/Droppable.js
onDroppableReturnedDefaultAnnouncement
function onDroppableReturnedDefaultAnnouncement({dragEvent, dropzone}) { const sourceText = dragEvent.source.textContent.trim() || dragEvent.source.id || 'draggable element'; const dropzoneText = dropzone.textContent.trim() || dropzone.id || 'droppable element'; return `Returned ${sourceText} from ${dropzoneText}`; }
javascript
function onDroppableReturnedDefaultAnnouncement({dragEvent, dropzone}) { const sourceText = dragEvent.source.textContent.trim() || dragEvent.source.id || 'draggable element'; const dropzoneText = dropzone.textContent.trim() || dropzone.id || 'droppable element'; return `Returned ${sourceText} from ${dropzoneText}`; }
[ "function", "onDroppableReturnedDefaultAnnouncement", "(", "{", "dragEvent", ",", "dropzone", "}", ")", "{", "const", "sourceText", "=", "dragEvent", ".", "source", ".", "textContent", ".", "trim", "(", ")", "||", "dragEvent", ".", "source", ".", "id", "||", "'draggable element'", ";", "const", "dropzoneText", "=", "dropzone", ".", "textContent", ".", "trim", "(", ")", "||", "dropzone", ".", "id", "||", "'droppable element'", ";", "return", "`", "${", "sourceText", "}", "${", "dropzoneText", "}", "`", ";", "}" ]
Returns an announcement message when the Draggable element has returned to its original dropzone element @param {DroppableReturnedEvent} droppableEvent @return {String}
[ "Returns", "an", "announcement", "message", "when", "the", "Draggable", "element", "has", "returned", "to", "its", "original", "dropzone", "element" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Droppable/Droppable.js#L31-L36
train
Shopify/draggable
src/Sortable/Sortable.js
onSortableSortedDefaultAnnouncement
function onSortableSortedDefaultAnnouncement({dragEvent}) { const sourceText = dragEvent.source.textContent.trim() || dragEvent.source.id || 'sortable element'; if (dragEvent.over) { const overText = dragEvent.over.textContent.trim() || dragEvent.over.id || 'sortable element'; const isFollowing = dragEvent.source.compareDocumentPosition(dragEvent.over) & Node.DOCUMENT_POSITION_FOLLOWING; if (isFollowing) { return `Placed ${sourceText} after ${overText}`; } else { return `Placed ${sourceText} before ${overText}`; } } else { // need to figure out how to compute container name return `Placed ${sourceText} into a different container`; } }
javascript
function onSortableSortedDefaultAnnouncement({dragEvent}) { const sourceText = dragEvent.source.textContent.trim() || dragEvent.source.id || 'sortable element'; if (dragEvent.over) { const overText = dragEvent.over.textContent.trim() || dragEvent.over.id || 'sortable element'; const isFollowing = dragEvent.source.compareDocumentPosition(dragEvent.over) & Node.DOCUMENT_POSITION_FOLLOWING; if (isFollowing) { return `Placed ${sourceText} after ${overText}`; } else { return `Placed ${sourceText} before ${overText}`; } } else { // need to figure out how to compute container name return `Placed ${sourceText} into a different container`; } }
[ "function", "onSortableSortedDefaultAnnouncement", "(", "{", "dragEvent", "}", ")", "{", "const", "sourceText", "=", "dragEvent", ".", "source", ".", "textContent", ".", "trim", "(", ")", "||", "dragEvent", ".", "source", ".", "id", "||", "'sortable element'", ";", "if", "(", "dragEvent", ".", "over", ")", "{", "const", "overText", "=", "dragEvent", ".", "over", ".", "textContent", ".", "trim", "(", ")", "||", "dragEvent", ".", "over", ".", "id", "||", "'sortable element'", ";", "const", "isFollowing", "=", "dragEvent", ".", "source", ".", "compareDocumentPosition", "(", "dragEvent", ".", "over", ")", "&", "Node", ".", "DOCUMENT_POSITION_FOLLOWING", ";", "if", "(", "isFollowing", ")", "{", "return", "`", "${", "sourceText", "}", "${", "overText", "}", "`", ";", "}", "else", "{", "return", "`", "${", "sourceText", "}", "${", "overText", "}", "`", ";", "}", "}", "else", "{", "return", "`", "${", "sourceText", "}", "`", ";", "}", "}" ]
Returns announcement message when a Draggable element has been sorted with another Draggable element or moved into a new container @param {SortableSortedEvent} sortableEvent @return {String}
[ "Returns", "announcement", "message", "when", "a", "Draggable", "element", "has", "been", "sorted", "with", "another", "Draggable", "element", "or", "moved", "into", "a", "new", "container" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Sortable/Sortable.js#L15-L31
train
Shopify/draggable
src/Draggable/Plugins/Scrollable/Scrollable.js
hasOverflow
function hasOverflow(element) { const overflowRegex = /(auto|scroll)/; const computedStyles = getComputedStyle(element, null); const overflow = computedStyles.getPropertyValue('overflow') + computedStyles.getPropertyValue('overflow-y') + computedStyles.getPropertyValue('overflow-x'); return overflowRegex.test(overflow); }
javascript
function hasOverflow(element) { const overflowRegex = /(auto|scroll)/; const computedStyles = getComputedStyle(element, null); const overflow = computedStyles.getPropertyValue('overflow') + computedStyles.getPropertyValue('overflow-y') + computedStyles.getPropertyValue('overflow-x'); return overflowRegex.test(overflow); }
[ "function", "hasOverflow", "(", "element", ")", "{", "const", "overflowRegex", "=", "/", "(auto|scroll)", "/", ";", "const", "computedStyles", "=", "getComputedStyle", "(", "element", ",", "null", ")", ";", "const", "overflow", "=", "computedStyles", ".", "getPropertyValue", "(", "'overflow'", ")", "+", "computedStyles", ".", "getPropertyValue", "(", "'overflow-y'", ")", "+", "computedStyles", ".", "getPropertyValue", "(", "'overflow-x'", ")", ";", "return", "overflowRegex", ".", "test", "(", "overflow", ")", ";", "}" ]
Returns true if the passed element has overflow @param {HTMLElement} element @return {Boolean} @private
[ "Returns", "true", "if", "the", "passed", "element", "has", "overflow" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Scrollable/Scrollable.js#L255-L265
train
Shopify/draggable
src/Draggable/Plugins/Scrollable/Scrollable.js
closestScrollableElement
function closestScrollableElement(element) { if (!element) { return getDocumentScrollingElement(); } const position = getComputedStyle(element).getPropertyValue('position'); const excludeStaticParents = position === 'absolute'; const scrollableElement = closest(element, (parent) => { if (excludeStaticParents && isStaticallyPositioned(parent)) { return false; } return hasOverflow(parent); }); if (position === 'fixed' || !scrollableElement) { return getDocumentScrollingElement(); } else { return scrollableElement; } }
javascript
function closestScrollableElement(element) { if (!element) { return getDocumentScrollingElement(); } const position = getComputedStyle(element).getPropertyValue('position'); const excludeStaticParents = position === 'absolute'; const scrollableElement = closest(element, (parent) => { if (excludeStaticParents && isStaticallyPositioned(parent)) { return false; } return hasOverflow(parent); }); if (position === 'fixed' || !scrollableElement) { return getDocumentScrollingElement(); } else { return scrollableElement; } }
[ "function", "closestScrollableElement", "(", "element", ")", "{", "if", "(", "!", "element", ")", "{", "return", "getDocumentScrollingElement", "(", ")", ";", "}", "const", "position", "=", "getComputedStyle", "(", "element", ")", ".", "getPropertyValue", "(", "'position'", ")", ";", "const", "excludeStaticParents", "=", "position", "===", "'absolute'", ";", "const", "scrollableElement", "=", "closest", "(", "element", ",", "(", "parent", ")", "=>", "{", "if", "(", "excludeStaticParents", "&&", "isStaticallyPositioned", "(", "parent", ")", ")", "{", "return", "false", ";", "}", "return", "hasOverflow", "(", "parent", ")", ";", "}", ")", ";", "if", "(", "position", "===", "'fixed'", "||", "!", "scrollableElement", ")", "{", "return", "getDocumentScrollingElement", "(", ")", ";", "}", "else", "{", "return", "scrollableElement", ";", "}", "}" ]
Finds closest scrollable element @param {HTMLElement} element @return {HTMLElement} @private
[ "Finds", "closest", "scrollable", "element" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Scrollable/Scrollable.js#L284-L304
train
Shopify/draggable
src/Draggable/Plugins/Focusable/Focusable.js
decorateElement
function decorateElement(element) { const hasMissingTabIndex = Boolean(!element.getAttribute('tabindex') && element.tabIndex === -1); if (hasMissingTabIndex) { elementsWithMissingTabIndex.push(element); element.tabIndex = 0; } }
javascript
function decorateElement(element) { const hasMissingTabIndex = Boolean(!element.getAttribute('tabindex') && element.tabIndex === -1); if (hasMissingTabIndex) { elementsWithMissingTabIndex.push(element); element.tabIndex = 0; } }
[ "function", "decorateElement", "(", "element", ")", "{", "const", "hasMissingTabIndex", "=", "Boolean", "(", "!", "element", ".", "getAttribute", "(", "'tabindex'", ")", "&&", "element", ".", "tabIndex", "===", "-", "1", ")", ";", "if", "(", "hasMissingTabIndex", ")", "{", "elementsWithMissingTabIndex", ".", "push", "(", "element", ")", ";", "element", ".", "tabIndex", "=", "0", ";", "}", "}" ]
Decorates element with tabindex attributes @param {HTMLElement} element @return {Object} @private
[ "Decorates", "element", "with", "tabindex", "attributes" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Focusable/Focusable.js#L108-L115
train
Shopify/draggable
src/Draggable/Plugins/Focusable/Focusable.js
stripElement
function stripElement(element) { const tabIndexElementPosition = elementsWithMissingTabIndex.indexOf(element); if (tabIndexElementPosition !== -1) { element.tabIndex = -1; elementsWithMissingTabIndex.splice(tabIndexElementPosition, 1); } }
javascript
function stripElement(element) { const tabIndexElementPosition = elementsWithMissingTabIndex.indexOf(element); if (tabIndexElementPosition !== -1) { element.tabIndex = -1; elementsWithMissingTabIndex.splice(tabIndexElementPosition, 1); } }
[ "function", "stripElement", "(", "element", ")", "{", "const", "tabIndexElementPosition", "=", "elementsWithMissingTabIndex", ".", "indexOf", "(", "element", ")", ";", "if", "(", "tabIndexElementPosition", "!==", "-", "1", ")", "{", "element", ".", "tabIndex", "=", "-", "1", ";", "elementsWithMissingTabIndex", ".", "splice", "(", "tabIndexElementPosition", ",", "1", ")", ";", "}", "}" ]
Removes elements tabindex attributes @param {HTMLElement} element @private
[ "Removes", "elements", "tabindex", "attributes" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Focusable/Focusable.js#L122-L129
train
Shopify/draggable
src/Swappable/Swappable.js
onSwappableSwappedDefaultAnnouncement
function onSwappableSwappedDefaultAnnouncement({dragEvent, swappedElement}) { const sourceText = dragEvent.source.textContent.trim() || dragEvent.source.id || 'swappable element'; const overText = swappedElement.textContent.trim() || swappedElement.id || 'swappable element'; return `Swapped ${sourceText} with ${overText}`; }
javascript
function onSwappableSwappedDefaultAnnouncement({dragEvent, swappedElement}) { const sourceText = dragEvent.source.textContent.trim() || dragEvent.source.id || 'swappable element'; const overText = swappedElement.textContent.trim() || swappedElement.id || 'swappable element'; return `Swapped ${sourceText} with ${overText}`; }
[ "function", "onSwappableSwappedDefaultAnnouncement", "(", "{", "dragEvent", ",", "swappedElement", "}", ")", "{", "const", "sourceText", "=", "dragEvent", ".", "source", ".", "textContent", ".", "trim", "(", ")", "||", "dragEvent", ".", "source", ".", "id", "||", "'swappable element'", ";", "const", "overText", "=", "swappedElement", ".", "textContent", ".", "trim", "(", ")", "||", "swappedElement", ".", "id", "||", "'swappable element'", ";", "return", "`", "${", "sourceText", "}", "${", "overText", "}", "`", ";", "}" ]
Returns an announcement message when the Draggable element is swapped with another draggable element @param {SwappableSwappedEvent} swappableEvent @return {String}
[ "Returns", "an", "announcement", "message", "when", "the", "Draggable", "element", "is", "swapped", "with", "another", "draggable", "element" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Swappable/Swappable.js#L13-L18
train
Shopify/draggable
src/Draggable/Plugins/Mirror/Mirror.js
computeMirrorDimensions
function computeMirrorDimensions({source, ...args}) { return withPromise((resolve) => { const sourceRect = source.getBoundingClientRect(); resolve({source, sourceRect, ...args}); }); }
javascript
function computeMirrorDimensions({source, ...args}) { return withPromise((resolve) => { const sourceRect = source.getBoundingClientRect(); resolve({source, sourceRect, ...args}); }); }
[ "function", "computeMirrorDimensions", "(", "{", "source", ",", "...", "args", "}", ")", "{", "return", "withPromise", "(", "(", "resolve", ")", "=>", "{", "const", "sourceRect", "=", "source", ".", "getBoundingClientRect", "(", ")", ";", "resolve", "(", "{", "source", ",", "sourceRect", ",", "...", "args", "}", ")", ";", "}", ")", ";", "}" ]
Computes mirror dimensions based on the source element Adds sourceRect to state @param {Object} state @param {HTMLElement} state.source @return {Promise} @private
[ "Computes", "mirror", "dimensions", "based", "on", "the", "source", "element", "Adds", "sourceRect", "to", "state" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Mirror/Mirror.js#L330-L335
train
Shopify/draggable
src/Draggable/Plugins/Mirror/Mirror.js
calculateMirrorOffset
function calculateMirrorOffset({sensorEvent, sourceRect, options, ...args}) { return withPromise((resolve) => { const top = options.cursorOffsetY === null ? sensorEvent.clientY - sourceRect.top : options.cursorOffsetY; const left = options.cursorOffsetX === null ? sensorEvent.clientX - sourceRect.left : options.cursorOffsetX; const mirrorOffset = {top, left}; resolve({sensorEvent, sourceRect, mirrorOffset, options, ...args}); }); }
javascript
function calculateMirrorOffset({sensorEvent, sourceRect, options, ...args}) { return withPromise((resolve) => { const top = options.cursorOffsetY === null ? sensorEvent.clientY - sourceRect.top : options.cursorOffsetY; const left = options.cursorOffsetX === null ? sensorEvent.clientX - sourceRect.left : options.cursorOffsetX; const mirrorOffset = {top, left}; resolve({sensorEvent, sourceRect, mirrorOffset, options, ...args}); }); }
[ "function", "calculateMirrorOffset", "(", "{", "sensorEvent", ",", "sourceRect", ",", "options", ",", "...", "args", "}", ")", "{", "return", "withPromise", "(", "(", "resolve", ")", "=>", "{", "const", "top", "=", "options", ".", "cursorOffsetY", "===", "null", "?", "sensorEvent", ".", "clientY", "-", "sourceRect", ".", "top", ":", "options", ".", "cursorOffsetY", ";", "const", "left", "=", "options", ".", "cursorOffsetX", "===", "null", "?", "sensorEvent", ".", "clientX", "-", "sourceRect", ".", "left", ":", "options", ".", "cursorOffsetX", ";", "const", "mirrorOffset", "=", "{", "top", ",", "left", "}", ";", "resolve", "(", "{", "sensorEvent", ",", "sourceRect", ",", "mirrorOffset", ",", "options", ",", "...", "args", "}", ")", ";", "}", ")", ";", "}" ]
Calculates mirror offset Adds mirrorOffset to state @param {Object} state @param {SensorEvent} state.sensorEvent @param {DOMRect} state.sourceRect @return {Promise} @private
[ "Calculates", "mirror", "offset", "Adds", "mirrorOffset", "to", "state" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Mirror/Mirror.js#L346-L355
train
Shopify/draggable
src/Draggable/Plugins/Mirror/Mirror.js
resetMirror
function resetMirror({mirror, source, options, ...args}) { return withPromise((resolve) => { let offsetHeight; let offsetWidth; if (options.constrainDimensions) { const computedSourceStyles = getComputedStyle(source); offsetHeight = computedSourceStyles.getPropertyValue('height'); offsetWidth = computedSourceStyles.getPropertyValue('width'); } mirror.style.position = 'fixed'; mirror.style.pointerEvents = 'none'; mirror.style.top = 0; mirror.style.left = 0; mirror.style.margin = 0; if (options.constrainDimensions) { mirror.style.height = offsetHeight; mirror.style.width = offsetWidth; } resolve({mirror, source, options, ...args}); }); }
javascript
function resetMirror({mirror, source, options, ...args}) { return withPromise((resolve) => { let offsetHeight; let offsetWidth; if (options.constrainDimensions) { const computedSourceStyles = getComputedStyle(source); offsetHeight = computedSourceStyles.getPropertyValue('height'); offsetWidth = computedSourceStyles.getPropertyValue('width'); } mirror.style.position = 'fixed'; mirror.style.pointerEvents = 'none'; mirror.style.top = 0; mirror.style.left = 0; mirror.style.margin = 0; if (options.constrainDimensions) { mirror.style.height = offsetHeight; mirror.style.width = offsetWidth; } resolve({mirror, source, options, ...args}); }); }
[ "function", "resetMirror", "(", "{", "mirror", ",", "source", ",", "options", ",", "...", "args", "}", ")", "{", "return", "withPromise", "(", "(", "resolve", ")", "=>", "{", "let", "offsetHeight", ";", "let", "offsetWidth", ";", "if", "(", "options", ".", "constrainDimensions", ")", "{", "const", "computedSourceStyles", "=", "getComputedStyle", "(", "source", ")", ";", "offsetHeight", "=", "computedSourceStyles", ".", "getPropertyValue", "(", "'height'", ")", ";", "offsetWidth", "=", "computedSourceStyles", ".", "getPropertyValue", "(", "'width'", ")", ";", "}", "mirror", ".", "style", ".", "position", "=", "'fixed'", ";", "mirror", ".", "style", ".", "pointerEvents", "=", "'none'", ";", "mirror", ".", "style", ".", "top", "=", "0", ";", "mirror", ".", "style", ".", "left", "=", "0", ";", "mirror", ".", "style", ".", "margin", "=", "0", ";", "if", "(", "options", ".", "constrainDimensions", ")", "{", "mirror", ".", "style", ".", "height", "=", "offsetHeight", ";", "mirror", ".", "style", ".", "width", "=", "offsetWidth", ";", "}", "resolve", "(", "{", "mirror", ",", "source", ",", "options", ",", "...", "args", "}", ")", ";", "}", ")", ";", "}" ]
Applys mirror styles @param {Object} state @param {HTMLElement} state.mirror @param {HTMLElement} state.source @param {Object} state.options @return {Promise} @private
[ "Applys", "mirror", "styles" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Mirror/Mirror.js#L366-L390
train
Shopify/draggable
src/Draggable/Plugins/Mirror/Mirror.js
addMirrorClasses
function addMirrorClasses({mirror, mirrorClass, ...args}) { return withPromise((resolve) => { mirror.classList.add(mirrorClass); resolve({mirror, mirrorClass, ...args}); }); }
javascript
function addMirrorClasses({mirror, mirrorClass, ...args}) { return withPromise((resolve) => { mirror.classList.add(mirrorClass); resolve({mirror, mirrorClass, ...args}); }); }
[ "function", "addMirrorClasses", "(", "{", "mirror", ",", "mirrorClass", ",", "...", "args", "}", ")", "{", "return", "withPromise", "(", "(", "resolve", ")", "=>", "{", "mirror", ".", "classList", ".", "add", "(", "mirrorClass", ")", ";", "resolve", "(", "{", "mirror", ",", "mirrorClass", ",", "...", "args", "}", ")", ";", "}", ")", ";", "}" ]
Applys mirror class on mirror element @param {Object} state @param {HTMLElement} state.mirror @param {String} state.mirrorClass @return {Promise} @private
[ "Applys", "mirror", "class", "on", "mirror", "element" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Mirror/Mirror.js#L400-L405
train
Shopify/draggable
src/Draggable/Plugins/Mirror/Mirror.js
removeMirrorID
function removeMirrorID({mirror, ...args}) { return withPromise((resolve) => { mirror.removeAttribute('id'); delete mirror.id; resolve({mirror, ...args}); }); }
javascript
function removeMirrorID({mirror, ...args}) { return withPromise((resolve) => { mirror.removeAttribute('id'); delete mirror.id; resolve({mirror, ...args}); }); }
[ "function", "removeMirrorID", "(", "{", "mirror", ",", "...", "args", "}", ")", "{", "return", "withPromise", "(", "(", "resolve", ")", "=>", "{", "mirror", ".", "removeAttribute", "(", "'id'", ")", ";", "delete", "mirror", ".", "id", ";", "resolve", "(", "{", "mirror", ",", "...", "args", "}", ")", ";", "}", ")", ";", "}" ]
Removes source ID from cloned mirror element @param {Object} state @param {HTMLElement} state.mirror @return {Promise} @private
[ "Removes", "source", "ID", "from", "cloned", "mirror", "element" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Mirror/Mirror.js#L414-L420
train
Shopify/draggable
src/Draggable/Plugins/Mirror/Mirror.js
positionMirror
function positionMirror({withFrame = false, initial = false} = {}) { return ({mirror, sensorEvent, mirrorOffset, initialY, initialX, scrollOffset, options, ...args}) => { return withPromise( (resolve) => { const result = { mirror, sensorEvent, mirrorOffset, options, ...args, }; if (mirrorOffset) { const x = sensorEvent.clientX - mirrorOffset.left - scrollOffset.x; const y = sensorEvent.clientY - mirrorOffset.top - scrollOffset.y; if ((options.xAxis && options.yAxis) || initial) { mirror.style.transform = `translate3d(${x}px, ${y}px, 0)`; } else if (options.xAxis && !options.yAxis) { mirror.style.transform = `translate3d(${x}px, ${initialY}px, 0)`; } else if (options.yAxis && !options.xAxis) { mirror.style.transform = `translate3d(${initialX}px, ${y}px, 0)`; } if (initial) { result.initialX = x; result.initialY = y; } } resolve(result); }, {frame: withFrame}, ); }; }
javascript
function positionMirror({withFrame = false, initial = false} = {}) { return ({mirror, sensorEvent, mirrorOffset, initialY, initialX, scrollOffset, options, ...args}) => { return withPromise( (resolve) => { const result = { mirror, sensorEvent, mirrorOffset, options, ...args, }; if (mirrorOffset) { const x = sensorEvent.clientX - mirrorOffset.left - scrollOffset.x; const y = sensorEvent.clientY - mirrorOffset.top - scrollOffset.y; if ((options.xAxis && options.yAxis) || initial) { mirror.style.transform = `translate3d(${x}px, ${y}px, 0)`; } else if (options.xAxis && !options.yAxis) { mirror.style.transform = `translate3d(${x}px, ${initialY}px, 0)`; } else if (options.yAxis && !options.xAxis) { mirror.style.transform = `translate3d(${initialX}px, ${y}px, 0)`; } if (initial) { result.initialX = x; result.initialY = y; } } resolve(result); }, {frame: withFrame}, ); }; }
[ "function", "positionMirror", "(", "{", "withFrame", "=", "false", ",", "initial", "=", "false", "}", "=", "{", "}", ")", "{", "return", "(", "{", "mirror", ",", "sensorEvent", ",", "mirrorOffset", ",", "initialY", ",", "initialX", ",", "scrollOffset", ",", "options", ",", "...", "args", "}", ")", "=>", "{", "return", "withPromise", "(", "(", "resolve", ")", "=>", "{", "const", "result", "=", "{", "mirror", ",", "sensorEvent", ",", "mirrorOffset", ",", "options", ",", "...", "args", ",", "}", ";", "if", "(", "mirrorOffset", ")", "{", "const", "x", "=", "sensorEvent", ".", "clientX", "-", "mirrorOffset", ".", "left", "-", "scrollOffset", ".", "x", ";", "const", "y", "=", "sensorEvent", ".", "clientY", "-", "mirrorOffset", ".", "top", "-", "scrollOffset", ".", "y", ";", "if", "(", "(", "options", ".", "xAxis", "&&", "options", ".", "yAxis", ")", "||", "initial", ")", "{", "mirror", ".", "style", ".", "transform", "=", "`", "${", "x", "}", "${", "y", "}", "`", ";", "}", "else", "if", "(", "options", ".", "xAxis", "&&", "!", "options", ".", "yAxis", ")", "{", "mirror", ".", "style", ".", "transform", "=", "`", "${", "x", "}", "${", "initialY", "}", "`", ";", "}", "else", "if", "(", "options", ".", "yAxis", "&&", "!", "options", ".", "xAxis", ")", "{", "mirror", ".", "style", ".", "transform", "=", "`", "${", "initialX", "}", "${", "y", "}", "`", ";", "}", "if", "(", "initial", ")", "{", "result", ".", "initialX", "=", "x", ";", "result", ".", "initialY", "=", "y", ";", "}", "}", "resolve", "(", "result", ")", ";", "}", ",", "{", "frame", ":", "withFrame", "}", ",", ")", ";", "}", ";", "}" ]
Positions mirror with translate3d @param {Object} state @param {HTMLElement} state.mirror @param {SensorEvent} state.sensorEvent @param {Object} state.mirrorOffset @param {Number} state.initialY @param {Number} state.initialX @param {Object} state.options @return {Promise} @private
[ "Positions", "mirror", "with", "translate3d" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Mirror/Mirror.js#L434-L469
train
Shopify/draggable
src/Draggable/Plugins/Mirror/Mirror.js
withPromise
function withPromise(callback, {raf = false} = {}) { return new Promise((resolve, reject) => { if (raf) { requestAnimationFrame(() => { callback(resolve, reject); }); } else { callback(resolve, reject); } }); }
javascript
function withPromise(callback, {raf = false} = {}) { return new Promise((resolve, reject) => { if (raf) { requestAnimationFrame(() => { callback(resolve, reject); }); } else { callback(resolve, reject); } }); }
[ "function", "withPromise", "(", "callback", ",", "{", "raf", "=", "false", "}", "=", "{", "}", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "raf", ")", "{", "requestAnimationFrame", "(", "(", ")", "=>", "{", "callback", "(", "resolve", ",", "reject", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "resolve", ",", "reject", ")", ";", "}", "}", ")", ";", "}" ]
Wraps functions in promise with potential animation frame option @param {Function} callback @param {Object} options @param {Boolean} options.raf @return {Promise} @private
[ "Wraps", "functions", "in", "promise", "with", "potential", "animation", "frame", "option" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Mirror/Mirror.js#L479-L489
train
Shopify/draggable
src/Draggable/Plugins/Announcement/Announcement.js
announce
function announce(message, {expire}) { const element = document.createElement('div'); element.textContent = message; liveRegion.appendChild(element); return setTimeout(() => { liveRegion.removeChild(element); }, expire); }
javascript
function announce(message, {expire}) { const element = document.createElement('div'); element.textContent = message; liveRegion.appendChild(element); return setTimeout(() => { liveRegion.removeChild(element); }, expire); }
[ "function", "announce", "(", "message", ",", "{", "expire", "}", ")", "{", "const", "element", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "element", ".", "textContent", "=", "message", ";", "liveRegion", ".", "appendChild", "(", "element", ")", ";", "return", "setTimeout", "(", "(", ")", "=>", "{", "liveRegion", ".", "removeChild", "(", "element", ")", ";", "}", ",", "expire", ")", ";", "}" ]
Announces message via live region @param {String} message @param {Object} options @param {Number} options.expire
[ "Announces", "message", "via", "live", "region" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Announcement/Announcement.js#L142-L151
train
Shopify/draggable
src/Draggable/Plugins/Announcement/Announcement.js
createRegion
function createRegion() { const element = document.createElement('div'); element.setAttribute('id', 'draggable-live-region'); element.setAttribute(ARIA_RELEVANT, 'additions'); element.setAttribute(ARIA_ATOMIC, 'true'); element.setAttribute(ARIA_LIVE, 'assertive'); element.setAttribute(ROLE, 'log'); element.style.position = 'fixed'; element.style.width = '1px'; element.style.height = '1px'; element.style.top = '-1px'; element.style.overflow = 'hidden'; return element; }
javascript
function createRegion() { const element = document.createElement('div'); element.setAttribute('id', 'draggable-live-region'); element.setAttribute(ARIA_RELEVANT, 'additions'); element.setAttribute(ARIA_ATOMIC, 'true'); element.setAttribute(ARIA_LIVE, 'assertive'); element.setAttribute(ROLE, 'log'); element.style.position = 'fixed'; element.style.width = '1px'; element.style.height = '1px'; element.style.top = '-1px'; element.style.overflow = 'hidden'; return element; }
[ "function", "createRegion", "(", ")", "{", "const", "element", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "element", ".", "setAttribute", "(", "'id'", ",", "'draggable-live-region'", ")", ";", "element", ".", "setAttribute", "(", "ARIA_RELEVANT", ",", "'additions'", ")", ";", "element", ".", "setAttribute", "(", "ARIA_ATOMIC", ",", "'true'", ")", ";", "element", ".", "setAttribute", "(", "ARIA_LIVE", ",", "'assertive'", ")", ";", "element", ".", "setAttribute", "(", "ROLE", ",", "'log'", ")", ";", "element", ".", "style", ".", "position", "=", "'fixed'", ";", "element", ".", "style", ".", "width", "=", "'1px'", ";", "element", ".", "style", ".", "height", "=", "'1px'", ";", "element", ".", "style", ".", "top", "=", "'-1px'", ";", "element", ".", "style", ".", "overflow", "=", "'hidden'", ";", "return", "element", ";", "}" ]
Creates region element @return {HTMLElement}
[ "Creates", "region", "element" ]
ecc04b2cdb8b5009664862472ff8cb237c38cfeb
https://github.com/Shopify/draggable/blob/ecc04b2cdb8b5009664862472ff8cb237c38cfeb/src/Draggable/Plugins/Announcement/Announcement.js#L157-L173
train
adobe/brackets
src/preferences/PreferencesBase.js
function () { var result = new $.Deferred(); var path = this.path; var createIfMissing = this.createIfMissing; var recreateIfInvalid = this.recreateIfInvalid; var self = this; if (path) { var prefFile = FileSystem.getFileForPath(path); prefFile.read({}, function (err, text) { if (err) { if (createIfMissing) { // Unreadable file is also unwritable -- delete so get recreated if (recreateIfInvalid && (err === FileSystemError.NOT_READABLE || err === FileSystemError.UNSUPPORTED_ENCODING)) { appshell.fs.moveToTrash(path, function (err) { if (err) { console.log("Cannot move unreadable preferences file " + path + " to trash!!"); } else { console.log("Brackets has recreated the unreadable preferences file " + path + ". You may refer to the deleted file in trash in case you need it!!"); } }.bind(this)); } result.resolve({}); } else { result.reject(new Error("Unable to load preferences at " + path + " " + err)); } return; } self._lineEndings = FileUtils.sniffLineEndings(text); // If the file is empty, turn it into an empty object if (/^\s*$/.test(text)) { result.resolve({}); } else { try { result.resolve(JSON.parse(text)); } catch (e) { if (recreateIfInvalid) { // JSON parsing error -- recreate the preferences file appshell.fs.moveToTrash(path, function (err) { if (err) { console.log("Cannot move unparseable preferences file " + path + " to trash!!"); } else { console.log("Brackets has recreated the Invalid JSON preferences file " + path + ". You may refer to the deleted file in trash in case you need it!!"); } }.bind(this)); result.resolve({}); } else { result.reject(new ParsingError("Invalid JSON settings at " + path + "(" + e.toString() + ")")); } } } }); } else { result.resolve({}); } return result.promise(); }
javascript
function () { var result = new $.Deferred(); var path = this.path; var createIfMissing = this.createIfMissing; var recreateIfInvalid = this.recreateIfInvalid; var self = this; if (path) { var prefFile = FileSystem.getFileForPath(path); prefFile.read({}, function (err, text) { if (err) { if (createIfMissing) { // Unreadable file is also unwritable -- delete so get recreated if (recreateIfInvalid && (err === FileSystemError.NOT_READABLE || err === FileSystemError.UNSUPPORTED_ENCODING)) { appshell.fs.moveToTrash(path, function (err) { if (err) { console.log("Cannot move unreadable preferences file " + path + " to trash!!"); } else { console.log("Brackets has recreated the unreadable preferences file " + path + ". You may refer to the deleted file in trash in case you need it!!"); } }.bind(this)); } result.resolve({}); } else { result.reject(new Error("Unable to load preferences at " + path + " " + err)); } return; } self._lineEndings = FileUtils.sniffLineEndings(text); // If the file is empty, turn it into an empty object if (/^\s*$/.test(text)) { result.resolve({}); } else { try { result.resolve(JSON.parse(text)); } catch (e) { if (recreateIfInvalid) { // JSON parsing error -- recreate the preferences file appshell.fs.moveToTrash(path, function (err) { if (err) { console.log("Cannot move unparseable preferences file " + path + " to trash!!"); } else { console.log("Brackets has recreated the Invalid JSON preferences file " + path + ". You may refer to the deleted file in trash in case you need it!!"); } }.bind(this)); result.resolve({}); } else { result.reject(new ParsingError("Invalid JSON settings at " + path + "(" + e.toString() + ")")); } } } }); } else { result.resolve({}); } return result.promise(); }
[ "function", "(", ")", "{", "var", "result", "=", "new", "$", ".", "Deferred", "(", ")", ";", "var", "path", "=", "this", ".", "path", ";", "var", "createIfMissing", "=", "this", ".", "createIfMissing", ";", "var", "recreateIfInvalid", "=", "this", ".", "recreateIfInvalid", ";", "var", "self", "=", "this", ";", "if", "(", "path", ")", "{", "var", "prefFile", "=", "FileSystem", ".", "getFileForPath", "(", "path", ")", ";", "prefFile", ".", "read", "(", "{", "}", ",", "function", "(", "err", ",", "text", ")", "{", "if", "(", "err", ")", "{", "if", "(", "createIfMissing", ")", "{", "if", "(", "recreateIfInvalid", "&&", "(", "err", "===", "FileSystemError", ".", "NOT_READABLE", "||", "err", "===", "FileSystemError", ".", "UNSUPPORTED_ENCODING", ")", ")", "{", "appshell", ".", "fs", ".", "moveToTrash", "(", "path", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"Cannot move unreadable preferences file \"", "+", "path", "+", "\" to trash!!\"", ")", ";", "}", "else", "{", "console", ".", "log", "(", "\"Brackets has recreated the unreadable preferences file \"", "+", "path", "+", "\". You may refer to the deleted file in trash in case you need it!!\"", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "result", ".", "resolve", "(", "{", "}", ")", ";", "}", "else", "{", "result", ".", "reject", "(", "new", "Error", "(", "\"Unable to load preferences at \"", "+", "path", "+", "\" \"", "+", "err", ")", ")", ";", "}", "return", ";", "}", "self", ".", "_lineEndings", "=", "FileUtils", ".", "sniffLineEndings", "(", "text", ")", ";", "if", "(", "/", "^\\s*$", "/", ".", "test", "(", "text", ")", ")", "{", "result", ".", "resolve", "(", "{", "}", ")", ";", "}", "else", "{", "try", "{", "result", ".", "resolve", "(", "JSON", ".", "parse", "(", "text", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "recreateIfInvalid", ")", "{", "appshell", ".", "fs", ".", "moveToTrash", "(", "path", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"Cannot move unparseable preferences file \"", "+", "path", "+", "\" to trash!!\"", ")", ";", "}", "else", "{", "console", ".", "log", "(", "\"Brackets has recreated the Invalid JSON preferences file \"", "+", "path", "+", "\". You may refer to the deleted file in trash in case you need it!!\"", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "result", ".", "resolve", "(", "{", "}", ")", ";", "}", "else", "{", "result", ".", "reject", "(", "new", "ParsingError", "(", "\"Invalid JSON settings at \"", "+", "path", "+", "\"(\"", "+", "e", ".", "toString", "(", ")", "+", "\")\"", ")", ")", ";", "}", "}", "}", "}", ")", ";", "}", "else", "{", "result", ".", "resolve", "(", "{", "}", ")", ";", "}", "return", "result", ".", "promise", "(", ")", ";", "}" ]
Loads the preferences from disk. Can throw an exception if the file is not readable or parseable. @return {Promise} Resolved with the data once it has been parsed.
[ "Loads", "the", "preferences", "from", "disk", ".", "Can", "throw", "an", "exception", "if", "the", "file", "is", "not", "readable", "or", "parseable", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/preferences/PreferencesBase.js#L170-L229
train
adobe/brackets
src/preferences/PreferencesBase.js
function (newData) { var result = new $.Deferred(); var path = this.path; var prefFile = FileSystem.getFileForPath(path); if (path) { try { var text = JSON.stringify(newData, null, 4); // maintain the original line endings text = FileUtils.translateLineEndings(text, this._lineEndings); prefFile.write(text, {}, function (err) { if (err) { result.reject("Unable to save prefs at " + path + " " + err); } else { result.resolve(); } }); } catch (e) { result.reject("Unable to convert prefs to JSON" + e.toString()); } } else { result.resolve(); } return result.promise(); }
javascript
function (newData) { var result = new $.Deferred(); var path = this.path; var prefFile = FileSystem.getFileForPath(path); if (path) { try { var text = JSON.stringify(newData, null, 4); // maintain the original line endings text = FileUtils.translateLineEndings(text, this._lineEndings); prefFile.write(text, {}, function (err) { if (err) { result.reject("Unable to save prefs at " + path + " " + err); } else { result.resolve(); } }); } catch (e) { result.reject("Unable to convert prefs to JSON" + e.toString()); } } else { result.resolve(); } return result.promise(); }
[ "function", "(", "newData", ")", "{", "var", "result", "=", "new", "$", ".", "Deferred", "(", ")", ";", "var", "path", "=", "this", ".", "path", ";", "var", "prefFile", "=", "FileSystem", ".", "getFileForPath", "(", "path", ")", ";", "if", "(", "path", ")", "{", "try", "{", "var", "text", "=", "JSON", ".", "stringify", "(", "newData", ",", "null", ",", "4", ")", ";", "text", "=", "FileUtils", ".", "translateLineEndings", "(", "text", ",", "this", ".", "_lineEndings", ")", ";", "prefFile", ".", "write", "(", "text", ",", "{", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "result", ".", "reject", "(", "\"Unable to save prefs at \"", "+", "path", "+", "\" \"", "+", "err", ")", ";", "}", "else", "{", "result", ".", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "result", ".", "reject", "(", "\"Unable to convert prefs to JSON\"", "+", "e", ".", "toString", "(", ")", ")", ";", "}", "}", "else", "{", "result", ".", "resolve", "(", ")", ";", "}", "return", "result", ".", "promise", "(", ")", ";", "}" ]
Saves the new data to disk. @param {Object} newData data to save @return {Promise} Promise resolved (with no arguments) once the data has been saved
[ "Saves", "the", "new", "data", "to", "disk", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/preferences/PreferencesBase.js#L237-L262
train
adobe/brackets
src/preferences/PreferencesBase.js
Scope
function Scope(storage) { this.storage = storage; storage.on("changed", this.load.bind(this)); this.data = {}; this._dirty = false; this._layers = []; this._layerMap = {}; this._exclusions = []; }
javascript
function Scope(storage) { this.storage = storage; storage.on("changed", this.load.bind(this)); this.data = {}; this._dirty = false; this._layers = []; this._layerMap = {}; this._exclusions = []; }
[ "function", "Scope", "(", "storage", ")", "{", "this", ".", "storage", "=", "storage", ";", "storage", ".", "on", "(", "\"changed\"", ",", "this", ".", "load", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "data", "=", "{", "}", ";", "this", ".", "_dirty", "=", "false", ";", "this", ".", "_layers", "=", "[", "]", ";", "this", ".", "_layerMap", "=", "{", "}", ";", "this", ".", "_exclusions", "=", "[", "]", ";", "}" ]
A `Scope` is a data container that is tied to a `Storage`. Additionally, `Scope`s support "layers" which are additional levels of preferences that are stored within a single preferences file. @constructor @param {Storage} storage Storage object from which prefs are loaded/saved
[ "A", "Scope", "is", "a", "data", "container", "that", "is", "tied", "to", "a", "Storage", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/preferences/PreferencesBase.js#L300-L308
train
adobe/brackets
src/preferences/PreferencesBase.js
function () { var result = new $.Deferred(); this.storage.load() .then(function (data) { var oldKeys = this.getKeys(); this.data = data; result.resolve(); this.trigger(PREFERENCE_CHANGE, { ids: _.union(this.getKeys(), oldKeys) }); }.bind(this)) .fail(function (error) { result.reject(error); }); return result.promise(); }
javascript
function () { var result = new $.Deferred(); this.storage.load() .then(function (data) { var oldKeys = this.getKeys(); this.data = data; result.resolve(); this.trigger(PREFERENCE_CHANGE, { ids: _.union(this.getKeys(), oldKeys) }); }.bind(this)) .fail(function (error) { result.reject(error); }); return result.promise(); }
[ "function", "(", ")", "{", "var", "result", "=", "new", "$", ".", "Deferred", "(", ")", ";", "this", ".", "storage", ".", "load", "(", ")", ".", "then", "(", "function", "(", "data", ")", "{", "var", "oldKeys", "=", "this", ".", "getKeys", "(", ")", ";", "this", ".", "data", "=", "data", ";", "result", ".", "resolve", "(", ")", ";", "this", ".", "trigger", "(", "PREFERENCE_CHANGE", ",", "{", "ids", ":", "_", ".", "union", "(", "this", ".", "getKeys", "(", ")", ",", "oldKeys", ")", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ".", "fail", "(", "function", "(", "error", ")", "{", "result", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "return", "result", ".", "promise", "(", ")", ";", "}" ]
Loads the prefs for this `Scope` from the `Storage`. @return {Promise} Promise that is resolved once loading is complete
[ "Loads", "the", "prefs", "for", "this", "Scope", "from", "the", "Storage", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/preferences/PreferencesBase.js#L316-L331
train
adobe/brackets
src/preferences/PreferencesBase.js
function () { var self = this; if (this._dirty) { self._dirty = false; return this.storage.save(this.data); } else { return (new $.Deferred()).resolve().promise(); } }
javascript
function () { var self = this; if (this._dirty) { self._dirty = false; return this.storage.save(this.data); } else { return (new $.Deferred()).resolve().promise(); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "this", ".", "_dirty", ")", "{", "self", ".", "_dirty", "=", "false", ";", "return", "this", ".", "storage", ".", "save", "(", "this", ".", "data", ")", ";", "}", "else", "{", "return", "(", "new", "$", ".", "Deferred", "(", ")", ")", ".", "resolve", "(", ")", ".", "promise", "(", ")", ";", "}", "}" ]
Saves the prefs for this `Scope`. @return {Promise} promise resolved once the data is saved.
[ "Saves", "the", "prefs", "for", "this", "Scope", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/preferences/PreferencesBase.js#L338-L346
train
adobe/brackets
src/preferences/PreferencesBase.js
function (id, value, context, location) { if (!location) { location = this.getPreferenceLocation(id, context); } if (location && location.layer) { var layer = this._layerMap[location.layer]; if (layer) { if (this.data[layer.key] === undefined) { this.data[layer.key] = {}; } var wasSet = layer.set(this.data[layer.key], id, value, context, location.layerID); this._dirty = this._dirty || wasSet; return wasSet; } else { return false; } } else { return this._performSet(id, value); } }
javascript
function (id, value, context, location) { if (!location) { location = this.getPreferenceLocation(id, context); } if (location && location.layer) { var layer = this._layerMap[location.layer]; if (layer) { if (this.data[layer.key] === undefined) { this.data[layer.key] = {}; } var wasSet = layer.set(this.data[layer.key], id, value, context, location.layerID); this._dirty = this._dirty || wasSet; return wasSet; } else { return false; } } else { return this._performSet(id, value); } }
[ "function", "(", "id", ",", "value", ",", "context", ",", "location", ")", "{", "if", "(", "!", "location", ")", "{", "location", "=", "this", ".", "getPreferenceLocation", "(", "id", ",", "context", ")", ";", "}", "if", "(", "location", "&&", "location", ".", "layer", ")", "{", "var", "layer", "=", "this", ".", "_layerMap", "[", "location", ".", "layer", "]", ";", "if", "(", "layer", ")", "{", "if", "(", "this", ".", "data", "[", "layer", ".", "key", "]", "===", "undefined", ")", "{", "this", ".", "data", "[", "layer", ".", "key", "]", "=", "{", "}", ";", "}", "var", "wasSet", "=", "layer", ".", "set", "(", "this", ".", "data", "[", "layer", ".", "key", "]", ",", "id", ",", "value", ",", "context", ",", "location", ".", "layerID", ")", ";", "this", ".", "_dirty", "=", "this", ".", "_dirty", "||", "wasSet", ";", "return", "wasSet", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "{", "return", "this", ".", "_performSet", "(", "id", ",", "value", ")", ";", "}", "}" ]
Sets the value for `id`. The value is set at the location given, or at the current location for the preference if no location is specified. If an invalid location is given, nothing will be set and no exception is thrown. @param {string} id Key to set @param {*} value Value for this key @param {Object=} context Optional additional information about the request (typically used for layers) @param {{layer: ?string, layerID: ?Object}=} location Optional location in which to set the value. If the object is empty, the value will be set at the Scope's base level. @return {boolean} true if the value was set
[ "Sets", "the", "value", "for", "id", ".", "The", "value", "is", "set", "at", "the", "location", "given", "or", "at", "the", "current", "location", "for", "the", "preference", "if", "no", "location", "is", "specified", ".", "If", "an", "invalid", "location", "is", "given", "nothing", "will", "be", "set", "and", "no", "exception", "is", "thrown", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/preferences/PreferencesBase.js#L361-L381
train
adobe/brackets
src/preferences/PreferencesBase.js
function (id, context) { var layerCounter, layers = this._layers, layer, data = this.data, result; context = context || {}; for (layerCounter = 0; layerCounter < layers.length; layerCounter++) { layer = layers[layerCounter]; result = layer.get(data[layer.key], id, context); if (result !== undefined) { return result; } } if (this._exclusions.indexOf(id) === -1) { return data[id]; } }
javascript
function (id, context) { var layerCounter, layers = this._layers, layer, data = this.data, result; context = context || {}; for (layerCounter = 0; layerCounter < layers.length; layerCounter++) { layer = layers[layerCounter]; result = layer.get(data[layer.key], id, context); if (result !== undefined) { return result; } } if (this._exclusions.indexOf(id) === -1) { return data[id]; } }
[ "function", "(", "id", ",", "context", ")", "{", "var", "layerCounter", ",", "layers", "=", "this", ".", "_layers", ",", "layer", ",", "data", "=", "this", ".", "data", ",", "result", ";", "context", "=", "context", "||", "{", "}", ";", "for", "(", "layerCounter", "=", "0", ";", "layerCounter", "<", "layers", ".", "length", ";", "layerCounter", "++", ")", "{", "layer", "=", "layers", "[", "layerCounter", "]", ";", "result", "=", "layer", ".", "get", "(", "data", "[", "layer", ".", "key", "]", ",", "id", ",", "context", ")", ";", "if", "(", "result", "!==", "undefined", ")", "{", "return", "result", ";", "}", "}", "if", "(", "this", ".", "_exclusions", ".", "indexOf", "(", "id", ")", "===", "-", "1", ")", "{", "return", "data", "[", "id", "]", ";", "}", "}" ]
Get the value for id, given the context. The context is provided to layers which may override the value from the main data of the Scope. Note that layers will often exclude values from consideration. @param {string} id Preference to retrieve @param {?Object} context Optional additional information about the request @return {*} Current value of the Preference
[ "Get", "the", "value", "for", "id", "given", "the", "context", ".", "The", "context", "is", "provided", "to", "layers", "which", "may", "override", "the", "value", "from", "the", "main", "data", "of", "the", "Scope", ".", "Note", "that", "layers", "will", "often", "exclude", "values", "from", "consideration", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/preferences/PreferencesBase.js#L415-L435
train