_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q16600
|
train
|
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
|
{
"resource": ""
}
|
|
q16601
|
processPropertyDefinition
|
train
|
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
|
{
"resource": ""
}
|
q16602
|
parseProperty
|
train
|
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
|
{
"resource": ""
}
|
q16603
|
stringifyProperty
|
train
|
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
|
{
"resource": ""
}
|
q16604
|
mediaElementLoaded
|
train
|
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
|
{
"resource": ""
}
|
q16605
|
fixUpMediaElement
|
train
|
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
|
{
"resource": ""
}
|
q16606
|
extractDomain
|
train
|
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
|
{
"resource": ""
}
|
q16607
|
train
|
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
|
{
"resource": ""
}
|
|
q16608
|
train
|
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
|
{
"resource": ""
}
|
|
q16609
|
train
|
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
|
{
"resource": ""
}
|
|
q16610
|
extend
|
train
|
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
|
{
"resource": ""
}
|
q16611
|
addComponentMapping
|
train
|
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
|
{
"resource": ""
}
|
q16612
|
definePrimitive
|
train
|
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
|
{
"resource": ""
}
|
q16613
|
registerPropertyType
|
train
|
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
|
{
"resource": ""
}
|
q16614
|
assetParse
|
train
|
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
|
{
"resource": ""
}
|
q16615
|
isValidDefaultValue
|
train
|
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
|
{
"resource": ""
}
|
q16616
|
isValidDefaultCoordinate
|
train
|
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
|
{
"resource": ""
}
|
q16617
|
train
|
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
|
{
"resource": ""
}
|
|
q16618
|
validateSrc
|
train
|
function validateSrc (src, isImageCb, isVideoCb) {
checkIsImage(src, function isAnImageUrl (isImage) {
if (isImage) {
isImageCb(src);
return;
}
isVideoCb(src);
});
}
|
javascript
|
{
"resource": ""
}
|
q16619
|
validateCubemapSrc
|
train
|
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
|
{
"resource": ""
}
|
q16620
|
checkIsImage
|
train
|
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
|
{
"resource": ""
}
|
q16621
|
validateAndGetQuerySelector
|
train
|
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
|
{
"resource": ""
}
|
q16622
|
train
|
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
|
{
"resource": ""
}
|
|
q16623
|
train
|
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
|
{
"resource": ""
}
|
|
q16624
|
train
|
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
|
{
"resource": ""
}
|
|
q16625
|
train
|
function (material) {
var materials = this.materials;
Object.keys(materials).forEach(function (uuid) {
materials[uuid].needsUpdate = true;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q16626
|
loadImageTexture
|
train
|
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
|
{
"resource": ""
}
|
q16627
|
setTextureProperties
|
train
|
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
|
{
"resource": ""
}
|
q16628
|
createVideoEl
|
train
|
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
|
{
"resource": ""
}
|
q16629
|
fixVideoAttributes
|
train
|
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
|
{
"resource": ""
}
|
q16630
|
train
|
function (oldEvt) {
var el = this.el;
if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
el.addEventListener(this.data.on, this.playSoundBound);
}
|
javascript
|
{
"resource": ""
}
|
|
q16631
|
train
|
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
|
{
"resource": ""
}
|
|
q16632
|
train
|
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
|
{
"resource": ""
}
|
|
q16633
|
train
|
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
|
{
"resource": ""
}
|
|
q16634
|
train
|
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
|
{
"resource": ""
}
|
|
q16635
|
train
|
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
|
{
"resource": ""
}
|
|
q16636
|
wrapANodeMethods
|
train
|
function wrapANodeMethods (obj) {
var newObj = {};
var ANodeMethods = [
'attachedCallback',
'attributeChangedCallback',
'createdCallback',
'detachedCallback'
];
wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
copyProperties(obj, newObj);
return newObj;
}
|
javascript
|
{
"resource": ""
}
|
q16637
|
wrapAEntityMethods
|
train
|
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
|
{
"resource": ""
}
|
q16638
|
wrapMethods
|
train
|
function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
methodList.forEach(function (methodName) {
wrapMethod(targetObj, methodName, derivedObj, baseObj);
});
}
|
javascript
|
{
"resource": ""
}
|
q16639
|
wrapMethod
|
train
|
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
|
{
"resource": ""
}
|
q16640
|
copyProperties
|
train
|
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
|
{
"resource": ""
}
|
q16641
|
train
|
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
|
{
"resource": ""
}
|
|
q16642
|
train
|
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
|
{
"resource": ""
}
|
|
q16643
|
removeDefaultCamera
|
train
|
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
|
{
"resource": ""
}
|
q16644
|
train
|
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
|
{
"resource": ""
}
|
|
q16645
|
train
|
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
|
{
"resource": ""
}
|
|
q16646
|
train
|
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
|
{
"resource": ""
}
|
|
q16647
|
train
|
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
|
{
"resource": ""
}
|
|
q16648
|
train
|
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
|
{
"resource": ""
}
|
|
q16649
|
train
|
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
|
{
"resource": ""
}
|
|
q16650
|
train
|
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
|
{
"resource": ""
}
|
|
q16651
|
train
|
function () {
if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
this.saveCameraPose();
this.el.object3D.position.set(0, 0, 0);
this.el.object3D.updateMatrix();
}
|
javascript
|
{
"resource": ""
}
|
|
q16652
|
train
|
function () {
var el = this.el;
this.savedPose.position.copy(el.object3D.position);
this.savedPose.rotation.copy(el.object3D.rotation);
this.hasSavedPose = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q16653
|
train
|
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
|
{
"resource": ""
}
|
|
q16654
|
createEnterVRButton
|
train
|
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
|
{
"resource": ""
}
|
q16655
|
createOrientationModal
|
train
|
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
|
{
"resource": ""
}
|
q16656
|
train
|
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
|
{
"resource": ""
}
|
|
q16657
|
train
|
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
|
{
"resource": ""
}
|
|
q16658
|
train
|
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
|
{
"resource": ""
}
|
|
q16659
|
train
|
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
|
{
"resource": ""
}
|
|
q16660
|
computeFontWidthFactor
|
train
|
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
|
{
"resource": ""
}
|
q16661
|
PromiseCache
|
train
|
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
|
{
"resource": ""
}
|
q16662
|
findMatchingControllerWebVR
|
train
|
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
|
{
"resource": ""
}
|
q16663
|
train
|
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
|
{
"resource": ""
}
|
|
q16664
|
train
|
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
|
{
"resource": ""
}
|
|
q16665
|
train
|
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
|
{
"resource": ""
}
|
|
q16666
|
train
|
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
|
{
"resource": ""
}
|
|
q16667
|
train
|
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
|
{
"resource": ""
}
|
|
q16668
|
train
|
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
|
{
"resource": ""
}
|
|
q16669
|
styleParse
|
train
|
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
|
{
"resource": ""
}
|
q16670
|
styleStringify
|
train
|
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
|
{
"resource": ""
}
|
q16671
|
deindent
|
train
|
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
|
{
"resource": ""
}
|
q16672
|
init
|
train
|
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
|
{
"resource": ""
}
|
q16673
|
pad
|
train
|
function pad(str) {
if (str.length < max) {
return str + ' '.repeat(max - str.length);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q16674
|
print
|
train
|
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
|
{
"resource": ""
}
|
q16675
|
animate
|
train
|
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
|
{
"resource": ""
}
|
q16676
|
resetElementOnTransitionEnd
|
train
|
function resetElementOnTransitionEnd(event) {
event.target.style.transition = '';
event.target.style.pointerEvents = '';
event.target.removeEventListener('transitionend', resetElementOnTransitionEnd);
}
|
javascript
|
{
"resource": ""
}
|
q16677
|
onDroppableReturnedDefaultAnnouncement
|
train
|
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
|
{
"resource": ""
}
|
q16678
|
onSortableSortedDefaultAnnouncement
|
train
|
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
|
{
"resource": ""
}
|
q16679
|
hasOverflow
|
train
|
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
|
{
"resource": ""
}
|
q16680
|
closestScrollableElement
|
train
|
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
|
{
"resource": ""
}
|
q16681
|
decorateElement
|
train
|
function decorateElement(element) {
const hasMissingTabIndex = Boolean(!element.getAttribute('tabindex') && element.tabIndex === -1);
if (hasMissingTabIndex) {
elementsWithMissingTabIndex.push(element);
element.tabIndex = 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q16682
|
stripElement
|
train
|
function stripElement(element) {
const tabIndexElementPosition = elementsWithMissingTabIndex.indexOf(element);
if (tabIndexElementPosition !== -1) {
element.tabIndex = -1;
elementsWithMissingTabIndex.splice(tabIndexElementPosition, 1);
}
}
|
javascript
|
{
"resource": ""
}
|
q16683
|
onSwappableSwappedDefaultAnnouncement
|
train
|
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
|
{
"resource": ""
}
|
q16684
|
computeMirrorDimensions
|
train
|
function computeMirrorDimensions({source, ...args}) {
return withPromise((resolve) => {
const sourceRect = source.getBoundingClientRect();
resolve({source, sourceRect, ...args});
});
}
|
javascript
|
{
"resource": ""
}
|
q16685
|
calculateMirrorOffset
|
train
|
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
|
{
"resource": ""
}
|
q16686
|
resetMirror
|
train
|
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
|
{
"resource": ""
}
|
q16687
|
addMirrorClasses
|
train
|
function addMirrorClasses({mirror, mirrorClass, ...args}) {
return withPromise((resolve) => {
mirror.classList.add(mirrorClass);
resolve({mirror, mirrorClass, ...args});
});
}
|
javascript
|
{
"resource": ""
}
|
q16688
|
removeMirrorID
|
train
|
function removeMirrorID({mirror, ...args}) {
return withPromise((resolve) => {
mirror.removeAttribute('id');
delete mirror.id;
resolve({mirror, ...args});
});
}
|
javascript
|
{
"resource": ""
}
|
q16689
|
positionMirror
|
train
|
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
|
{
"resource": ""
}
|
q16690
|
withPromise
|
train
|
function withPromise(callback, {raf = false} = {}) {
return new Promise((resolve, reject) => {
if (raf) {
requestAnimationFrame(() => {
callback(resolve, reject);
});
} else {
callback(resolve, reject);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16691
|
announce
|
train
|
function announce(message, {expire}) {
const element = document.createElement('div');
element.textContent = message;
liveRegion.appendChild(element);
return setTimeout(() => {
liveRegion.removeChild(element);
}, expire);
}
|
javascript
|
{
"resource": ""
}
|
q16692
|
createRegion
|
train
|
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
|
{
"resource": ""
}
|
q16693
|
train
|
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
|
{
"resource": ""
}
|
|
q16694
|
train
|
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
|
{
"resource": ""
}
|
|
q16695
|
Scope
|
train
|
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
|
{
"resource": ""
}
|
q16696
|
train
|
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
|
{
"resource": ""
}
|
|
q16697
|
train
|
function () {
var self = this;
if (this._dirty) {
self._dirty = false;
return this.storage.save(this.data);
} else {
return (new $.Deferred()).resolve().promise();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q16698
|
train
|
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
|
{
"resource": ""
}
|
|
q16699
|
train
|
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
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.