id
int32
0
58k
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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
1,500
goldfire/howler.js
examples/3d/js/game.js
function() { this.lastTime = 0; // Setup our different game components. this.audio = new Sound(); this.player = new Player(10, 26, Math.PI * 1.9, 2.5); this.controls = new Controls(); this.map = new Map(25); this.camera = new Camera(isMobile ? 256 : 512); requestAnimationFrame(this.tick.bind(this)); }
javascript
function() { this.lastTime = 0; // Setup our different game components. this.audio = new Sound(); this.player = new Player(10, 26, Math.PI * 1.9, 2.5); this.controls = new Controls(); this.map = new Map(25); this.camera = new Camera(isMobile ? 256 : 512); requestAnimationFrame(this.tick.bind(this)); }
[ "function", "(", ")", "{", "this", ".", "lastTime", "=", "0", ";", "// Setup our different game components.", "this", ".", "audio", "=", "new", "Sound", "(", ")", ";", "this", ".", "player", "=", "new", "Player", "(", "10", ",", "26", ",", "Math", ".", "PI", "*", "1.9", ",", "2.5", ")", ";", "this", ".", "controls", "=", "new", "Controls", "(", ")", ";", "this", ".", "map", "=", "new", "Map", "(", "25", ")", ";", "this", ".", "camera", "=", "new", "Camera", "(", "isMobile", "?", "256", ":", "512", ")", ";", "requestAnimationFrame", "(", "this", ".", "tick", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Main game class that runs the tick and sets up all other components.
[ "Main", "game", "class", "that", "runs", "the", "tick", "and", "sets", "up", "all", "other", "components", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/game.js#L22-L33
1,501
goldfire/howler.js
examples/3d/js/game.js
function(time) { var ms = time - this.lastTime; this.lastTime = time; // Update the different components of the scene. this.map.update(ms / 1000); this.player.update(ms / 1000); this.camera.render(this.player, this.map); // Continue the game loop. requestAnimationFrame(this.tick.bind(this)); }
javascript
function(time) { var ms = time - this.lastTime; this.lastTime = time; // Update the different components of the scene. this.map.update(ms / 1000); this.player.update(ms / 1000); this.camera.render(this.player, this.map); // Continue the game loop. requestAnimationFrame(this.tick.bind(this)); }
[ "function", "(", "time", ")", "{", "var", "ms", "=", "time", "-", "this", ".", "lastTime", ";", "this", ".", "lastTime", "=", "time", ";", "// Update the different components of the scene.", "this", ".", "map", ".", "update", "(", "ms", "/", "1000", ")", ";", "this", ".", "player", ".", "update", "(", "ms", "/", "1000", ")", ";", "this", ".", "camera", ".", "render", "(", "this", ".", "player", ",", "this", ".", "map", ")", ";", "// Continue the game loop.", "requestAnimationFrame", "(", "this", ".", "tick", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Main game loop that renders the full scene on each screen refresh. @param {Number} time
[ "Main", "game", "loop", "that", "renders", "the", "full", "scene", "on", "each", "screen", "refresh", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/game.js#L39-L50
1,502
goldfire/howler.js
examples/radio/radio.js
function(stations) { var self = this; self.stations = stations; self.index = 0; // Setup the display for each station. for (var i=0; i<self.stations.length; i++) { window['title' + i].innerHTML = '<b>' + self.stations[i].freq + '</b> ' + self.stations[i].title; window['station' + i].addEventListener('click', function(index) { var isNotPlaying = (self.stations[index].howl && !self.stations[index].howl.playing()); // Stop other sounds or the current one. radio.stop(); // If the station isn't already playing or it doesn't exist, play it. if (isNotPlaying || !self.stations[index].howl) { radio.play(index); } }.bind(self, i)); } }
javascript
function(stations) { var self = this; self.stations = stations; self.index = 0; // Setup the display for each station. for (var i=0; i<self.stations.length; i++) { window['title' + i].innerHTML = '<b>' + self.stations[i].freq + '</b> ' + self.stations[i].title; window['station' + i].addEventListener('click', function(index) { var isNotPlaying = (self.stations[index].howl && !self.stations[index].howl.playing()); // Stop other sounds or the current one. radio.stop(); // If the station isn't already playing or it doesn't exist, play it. if (isNotPlaying || !self.stations[index].howl) { radio.play(index); } }.bind(self, i)); } }
[ "function", "(", "stations", ")", "{", "var", "self", "=", "this", ";", "self", ".", "stations", "=", "stations", ";", "self", ".", "index", "=", "0", ";", "// Setup the display for each station.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "stations", ".", "length", ";", "i", "++", ")", "{", "window", "[", "'title'", "+", "i", "]", ".", "innerHTML", "=", "'<b>'", "+", "self", ".", "stations", "[", "i", "]", ".", "freq", "+", "'</b> '", "+", "self", ".", "stations", "[", "i", "]", ".", "title", ";", "window", "[", "'station'", "+", "i", "]", ".", "addEventListener", "(", "'click'", ",", "function", "(", "index", ")", "{", "var", "isNotPlaying", "=", "(", "self", ".", "stations", "[", "index", "]", ".", "howl", "&&", "!", "self", ".", "stations", "[", "index", "]", ".", "howl", ".", "playing", "(", ")", ")", ";", "// Stop other sounds or the current one.", "radio", ".", "stop", "(", ")", ";", "// If the station isn't already playing or it doesn't exist, play it.", "if", "(", "isNotPlaying", "||", "!", "self", ".", "stations", "[", "index", "]", ".", "howl", ")", "{", "radio", ".", "play", "(", "index", ")", ";", "}", "}", ".", "bind", "(", "self", ",", "i", ")", ")", ";", "}", "}" ]
Radio class containing the state of our stations. Includes all methods for playing, stopping, etc. @param {Array} stations Array of objects with station details ({title, src, howl, ...}).
[ "Radio", "class", "containing", "the", "state", "of", "our", "stations", ".", "Includes", "all", "methods", "for", "playing", "stopping", "etc", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/radio/radio.js#L22-L43
1,503
goldfire/howler.js
examples/radio/radio.js
function(index) { var self = this; var sound; index = typeof index === 'number' ? index : self.index; var data = self.stations[index]; // If we already loaded this track, use the current one. // Otherwise, setup and load a new Howl. if (data.howl) { sound = data.howl; } else { sound = data.howl = new Howl({ src: data.src, html5: true, // A live stream can only be played through HTML5 Audio. format: ['mp3', 'aac'] }); } // Begin playing the sound. sound.play(); // Toggle the display. self.toggleStationDisplay(index, true); // Keep track of the index we are currently playing. self.index = index; }
javascript
function(index) { var self = this; var sound; index = typeof index === 'number' ? index : self.index; var data = self.stations[index]; // If we already loaded this track, use the current one. // Otherwise, setup and load a new Howl. if (data.howl) { sound = data.howl; } else { sound = data.howl = new Howl({ src: data.src, html5: true, // A live stream can only be played through HTML5 Audio. format: ['mp3', 'aac'] }); } // Begin playing the sound. sound.play(); // Toggle the display. self.toggleStationDisplay(index, true); // Keep track of the index we are currently playing. self.index = index; }
[ "function", "(", "index", ")", "{", "var", "self", "=", "this", ";", "var", "sound", ";", "index", "=", "typeof", "index", "===", "'number'", "?", "index", ":", "self", ".", "index", ";", "var", "data", "=", "self", ".", "stations", "[", "index", "]", ";", "// If we already loaded this track, use the current one.", "// Otherwise, setup and load a new Howl.", "if", "(", "data", ".", "howl", ")", "{", "sound", "=", "data", ".", "howl", ";", "}", "else", "{", "sound", "=", "data", ".", "howl", "=", "new", "Howl", "(", "{", "src", ":", "data", ".", "src", ",", "html5", ":", "true", ",", "// A live stream can only be played through HTML5 Audio.", "format", ":", "[", "'mp3'", ",", "'aac'", "]", "}", ")", ";", "}", "// Begin playing the sound.", "sound", ".", "play", "(", ")", ";", "// Toggle the display.", "self", ".", "toggleStationDisplay", "(", "index", ",", "true", ")", ";", "// Keep track of the index we are currently playing.", "self", ".", "index", "=", "index", ";", "}" ]
Play a station with a specific index. @param {Number} index Index in the array of stations.
[ "Play", "a", "station", "with", "a", "specific", "index", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/radio/radio.js#L49-L76
1,504
goldfire/howler.js
examples/radio/radio.js
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.stations[self.index].howl; // Toggle the display. self.toggleStationDisplay(self.index, false); // Stop the sound. if (sound) { sound.unload(); } }
javascript
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.stations[self.index].howl; // Toggle the display. self.toggleStationDisplay(self.index, false); // Stop the sound. if (sound) { sound.unload(); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Get the Howl we want to manipulate.", "var", "sound", "=", "self", ".", "stations", "[", "self", ".", "index", "]", ".", "howl", ";", "// Toggle the display.", "self", ".", "toggleStationDisplay", "(", "self", ".", "index", ",", "false", ")", ";", "// Stop the sound.", "if", "(", "sound", ")", "{", "sound", ".", "unload", "(", ")", ";", "}", "}" ]
Stop a station's live stream.
[ "Stop", "a", "station", "s", "live", "stream", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/radio/radio.js#L81-L94
1,505
goldfire/howler.js
examples/player/player.js
function(playlist) { this.playlist = playlist; this.index = 0; // Display the title of the first track. track.innerHTML = '1. ' + playlist[0].title; // Setup the playlist display. playlist.forEach(function(song) { var div = document.createElement('div'); div.className = 'list-song'; div.innerHTML = song.title; div.onclick = function() { player.skipTo(playlist.indexOf(song)); }; list.appendChild(div); }); }
javascript
function(playlist) { this.playlist = playlist; this.index = 0; // Display the title of the first track. track.innerHTML = '1. ' + playlist[0].title; // Setup the playlist display. playlist.forEach(function(song) { var div = document.createElement('div'); div.className = 'list-song'; div.innerHTML = song.title; div.onclick = function() { player.skipTo(playlist.indexOf(song)); }; list.appendChild(div); }); }
[ "function", "(", "playlist", ")", "{", "this", ".", "playlist", "=", "playlist", ";", "this", ".", "index", "=", "0", ";", "// Display the title of the first track.", "track", ".", "innerHTML", "=", "'1. '", "+", "playlist", "[", "0", "]", ".", "title", ";", "// Setup the playlist display.", "playlist", ".", "forEach", "(", "function", "(", "song", ")", "{", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "className", "=", "'list-song'", ";", "div", ".", "innerHTML", "=", "song", ".", "title", ";", "div", ".", "onclick", "=", "function", "(", ")", "{", "player", ".", "skipTo", "(", "playlist", ".", "indexOf", "(", "song", ")", ")", ";", "}", ";", "list", ".", "appendChild", "(", "div", ")", ";", "}", ")", ";", "}" ]
Player class containing the state of our playlist and where we are in it. Includes all methods for playing, skipping, updating the display, etc. @param {Array} playlist Array of objects with playlist song details ({title, file, howl}).
[ "Player", "class", "containing", "the", "state", "of", "our", "playlist", "and", "where", "we", "are", "in", "it", ".", "Includes", "all", "methods", "for", "playing", "skipping", "updating", "the", "display", "etc", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L22-L39
1,506
goldfire/howler.js
examples/player/player.js
function(index) { var self = this; var sound; index = typeof index === 'number' ? index : self.index; var data = self.playlist[index]; // If we already loaded this track, use the current one. // Otherwise, setup and load a new Howl. if (data.howl) { sound = data.howl; } else { sound = data.howl = new Howl({ src: ['./audio/' + data.file + '.webm', './audio/' + data.file + '.mp3'], html5: true, // Force to HTML5 so that the audio can stream in (best for large files). onplay: function() { // Display the duration. duration.innerHTML = self.formatTime(Math.round(sound.duration())); // Start upating the progress of the track. requestAnimationFrame(self.step.bind(self)); // Start the wave animation if we have already loaded wave.container.style.display = 'block'; bar.style.display = 'none'; pauseBtn.style.display = 'block'; }, onload: function() { // Start the wave animation. wave.container.style.display = 'block'; bar.style.display = 'none'; loading.style.display = 'none'; }, onend: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; self.skip('next'); }, onpause: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; }, onstop: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; }, onseek: function() { // Start upating the progress of the track. requestAnimationFrame(self.step.bind(self)); } }); } // Begin playing the sound. sound.play(); // Update the track display. track.innerHTML = (index + 1) + '. ' + data.title; // Show the pause button. if (sound.state() === 'loaded') { playBtn.style.display = 'none'; pauseBtn.style.display = 'block'; } else { loading.style.display = 'block'; playBtn.style.display = 'none'; pauseBtn.style.display = 'none'; } // Keep track of the index we are currently playing. self.index = index; }
javascript
function(index) { var self = this; var sound; index = typeof index === 'number' ? index : self.index; var data = self.playlist[index]; // If we already loaded this track, use the current one. // Otherwise, setup and load a new Howl. if (data.howl) { sound = data.howl; } else { sound = data.howl = new Howl({ src: ['./audio/' + data.file + '.webm', './audio/' + data.file + '.mp3'], html5: true, // Force to HTML5 so that the audio can stream in (best for large files). onplay: function() { // Display the duration. duration.innerHTML = self.formatTime(Math.round(sound.duration())); // Start upating the progress of the track. requestAnimationFrame(self.step.bind(self)); // Start the wave animation if we have already loaded wave.container.style.display = 'block'; bar.style.display = 'none'; pauseBtn.style.display = 'block'; }, onload: function() { // Start the wave animation. wave.container.style.display = 'block'; bar.style.display = 'none'; loading.style.display = 'none'; }, onend: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; self.skip('next'); }, onpause: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; }, onstop: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; }, onseek: function() { // Start upating the progress of the track. requestAnimationFrame(self.step.bind(self)); } }); } // Begin playing the sound. sound.play(); // Update the track display. track.innerHTML = (index + 1) + '. ' + data.title; // Show the pause button. if (sound.state() === 'loaded') { playBtn.style.display = 'none'; pauseBtn.style.display = 'block'; } else { loading.style.display = 'block'; playBtn.style.display = 'none'; pauseBtn.style.display = 'none'; } // Keep track of the index we are currently playing. self.index = index; }
[ "function", "(", "index", ")", "{", "var", "self", "=", "this", ";", "var", "sound", ";", "index", "=", "typeof", "index", "===", "'number'", "?", "index", ":", "self", ".", "index", ";", "var", "data", "=", "self", ".", "playlist", "[", "index", "]", ";", "// If we already loaded this track, use the current one.", "// Otherwise, setup and load a new Howl.", "if", "(", "data", ".", "howl", ")", "{", "sound", "=", "data", ".", "howl", ";", "}", "else", "{", "sound", "=", "data", ".", "howl", "=", "new", "Howl", "(", "{", "src", ":", "[", "'./audio/'", "+", "data", ".", "file", "+", "'.webm'", ",", "'./audio/'", "+", "data", ".", "file", "+", "'.mp3'", "]", ",", "html5", ":", "true", ",", "// Force to HTML5 so that the audio can stream in (best for large files).", "onplay", ":", "function", "(", ")", "{", "// Display the duration.", "duration", ".", "innerHTML", "=", "self", ".", "formatTime", "(", "Math", ".", "round", "(", "sound", ".", "duration", "(", ")", ")", ")", ";", "// Start upating the progress of the track.", "requestAnimationFrame", "(", "self", ".", "step", ".", "bind", "(", "self", ")", ")", ";", "// Start the wave animation if we have already loaded", "wave", ".", "container", ".", "style", ".", "display", "=", "'block'", ";", "bar", ".", "style", ".", "display", "=", "'none'", ";", "pauseBtn", ".", "style", ".", "display", "=", "'block'", ";", "}", ",", "onload", ":", "function", "(", ")", "{", "// Start the wave animation.", "wave", ".", "container", ".", "style", ".", "display", "=", "'block'", ";", "bar", ".", "style", ".", "display", "=", "'none'", ";", "loading", ".", "style", ".", "display", "=", "'none'", ";", "}", ",", "onend", ":", "function", "(", ")", "{", "// Stop the wave animation.", "wave", ".", "container", ".", "style", ".", "display", "=", "'none'", ";", "bar", ".", "style", ".", "display", "=", "'block'", ";", "self", ".", "skip", "(", "'next'", ")", ";", "}", ",", "onpause", ":", "function", "(", ")", "{", "// Stop the wave animation.", "wave", ".", "container", ".", "style", ".", "display", "=", "'none'", ";", "bar", ".", "style", ".", "display", "=", "'block'", ";", "}", ",", "onstop", ":", "function", "(", ")", "{", "// Stop the wave animation.", "wave", ".", "container", ".", "style", ".", "display", "=", "'none'", ";", "bar", ".", "style", ".", "display", "=", "'block'", ";", "}", ",", "onseek", ":", "function", "(", ")", "{", "// Start upating the progress of the track.", "requestAnimationFrame", "(", "self", ".", "step", ".", "bind", "(", "self", ")", ")", ";", "}", "}", ")", ";", "}", "// Begin playing the sound.", "sound", ".", "play", "(", ")", ";", "// Update the track display.", "track", ".", "innerHTML", "=", "(", "index", "+", "1", ")", "+", "'. '", "+", "data", ".", "title", ";", "// Show the pause button.", "if", "(", "sound", ".", "state", "(", ")", "===", "'loaded'", ")", "{", "playBtn", ".", "style", ".", "display", "=", "'none'", ";", "pauseBtn", ".", "style", ".", "display", "=", "'block'", ";", "}", "else", "{", "loading", ".", "style", ".", "display", "=", "'block'", ";", "playBtn", ".", "style", ".", "display", "=", "'none'", ";", "pauseBtn", ".", "style", ".", "display", "=", "'none'", ";", "}", "// Keep track of the index we are currently playing.", "self", ".", "index", "=", "index", ";", "}" ]
Play a song in the playlist. @param {Number} index Index of the song in the playlist (leave empty to play the first or current).
[ "Play", "a", "song", "in", "the", "playlist", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L45-L119
1,507
goldfire/howler.js
examples/player/player.js
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Puase the sound. sound.pause(); // Show the play button. playBtn.style.display = 'block'; pauseBtn.style.display = 'none'; }
javascript
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Puase the sound. sound.pause(); // Show the play button. playBtn.style.display = 'block'; pauseBtn.style.display = 'none'; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Get the Howl we want to manipulate.", "var", "sound", "=", "self", ".", "playlist", "[", "self", ".", "index", "]", ".", "howl", ";", "// Puase the sound.", "sound", ".", "pause", "(", ")", ";", "// Show the play button.", "playBtn", ".", "style", ".", "display", "=", "'block'", ";", "pauseBtn", ".", "style", ".", "display", "=", "'none'", ";", "}" ]
Pause the currently playing track.
[ "Pause", "the", "currently", "playing", "track", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L124-L136
1,508
goldfire/howler.js
examples/player/player.js
function(direction) { var self = this; // Get the next track based on the direction of the track. var index = 0; if (direction === 'prev') { index = self.index - 1; if (index < 0) { index = self.playlist.length - 1; } } else { index = self.index + 1; if (index >= self.playlist.length) { index = 0; } } self.skipTo(index); }
javascript
function(direction) { var self = this; // Get the next track based on the direction of the track. var index = 0; if (direction === 'prev') { index = self.index - 1; if (index < 0) { index = self.playlist.length - 1; } } else { index = self.index + 1; if (index >= self.playlist.length) { index = 0; } } self.skipTo(index); }
[ "function", "(", "direction", ")", "{", "var", "self", "=", "this", ";", "// Get the next track based on the direction of the track.", "var", "index", "=", "0", ";", "if", "(", "direction", "===", "'prev'", ")", "{", "index", "=", "self", ".", "index", "-", "1", ";", "if", "(", "index", "<", "0", ")", "{", "index", "=", "self", ".", "playlist", ".", "length", "-", "1", ";", "}", "}", "else", "{", "index", "=", "self", ".", "index", "+", "1", ";", "if", "(", "index", ">=", "self", ".", "playlist", ".", "length", ")", "{", "index", "=", "0", ";", "}", "}", "self", ".", "skipTo", "(", "index", ")", ";", "}" ]
Skip to the next or previous track. @param {String} direction 'next' or 'prev'.
[ "Skip", "to", "the", "next", "or", "previous", "track", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L142-L160
1,509
goldfire/howler.js
examples/player/player.js
function(index) { var self = this; // Stop the current track. if (self.playlist[self.index].howl) { self.playlist[self.index].howl.stop(); } // Reset progress. progress.style.width = '0%'; // Play the new track. self.play(index); }
javascript
function(index) { var self = this; // Stop the current track. if (self.playlist[self.index].howl) { self.playlist[self.index].howl.stop(); } // Reset progress. progress.style.width = '0%'; // Play the new track. self.play(index); }
[ "function", "(", "index", ")", "{", "var", "self", "=", "this", ";", "// Stop the current track.", "if", "(", "self", ".", "playlist", "[", "self", ".", "index", "]", ".", "howl", ")", "{", "self", ".", "playlist", "[", "self", ".", "index", "]", ".", "howl", ".", "stop", "(", ")", ";", "}", "// Reset progress.", "progress", ".", "style", ".", "width", "=", "'0%'", ";", "// Play the new track.", "self", ".", "play", "(", "index", ")", ";", "}" ]
Skip to a specific track based on its playlist index. @param {Number} index Index in the playlist.
[ "Skip", "to", "a", "specific", "track", "based", "on", "its", "playlist", "index", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L166-L179
1,510
goldfire/howler.js
examples/player/player.js
function(val) { var self = this; // Update the global volume (affecting all Howls). Howler.volume(val); // Update the display on the slider. var barWidth = (val * 90) / 100; barFull.style.width = (barWidth * 100) + '%'; sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px'; }
javascript
function(val) { var self = this; // Update the global volume (affecting all Howls). Howler.volume(val); // Update the display on the slider. var barWidth = (val * 90) / 100; barFull.style.width = (barWidth * 100) + '%'; sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px'; }
[ "function", "(", "val", ")", "{", "var", "self", "=", "this", ";", "// Update the global volume (affecting all Howls).", "Howler", ".", "volume", "(", "val", ")", ";", "// Update the display on the slider.", "var", "barWidth", "=", "(", "val", "*", "90", ")", "/", "100", ";", "barFull", ".", "style", ".", "width", "=", "(", "barWidth", "*", "100", ")", "+", "'%'", ";", "sliderBtn", ".", "style", ".", "left", "=", "(", "window", ".", "innerWidth", "*", "barWidth", "+", "window", ".", "innerWidth", "*", "0.05", "-", "25", ")", "+", "'px'", ";", "}" ]
Set the volume and update the volume slider display. @param {Number} val Volume between 0 and 1.
[ "Set", "the", "volume", "and", "update", "the", "volume", "slider", "display", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L185-L195
1,511
goldfire/howler.js
examples/player/player.js
function(per) { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Convert the percent into a seek position. if (sound.playing()) { sound.seek(sound.duration() * per); } }
javascript
function(per) { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Convert the percent into a seek position. if (sound.playing()) { sound.seek(sound.duration() * per); } }
[ "function", "(", "per", ")", "{", "var", "self", "=", "this", ";", "// Get the Howl we want to manipulate.", "var", "sound", "=", "self", ".", "playlist", "[", "self", ".", "index", "]", ".", "howl", ";", "// Convert the percent into a seek position.", "if", "(", "sound", ".", "playing", "(", ")", ")", "{", "sound", ".", "seek", "(", "sound", ".", "duration", "(", ")", "*", "per", ")", ";", "}", "}" ]
Seek to a new position in the currently playing track. @param {Number} per Percentage through the song to skip.
[ "Seek", "to", "a", "new", "position", "in", "the", "currently", "playing", "track", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L201-L211
1,512
goldfire/howler.js
examples/player/player.js
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Determine our current seek position. var seek = sound.seek() || 0; timer.innerHTML = self.formatTime(Math.round(seek)); progress.style.width = (((seek / sound.duration()) * 100) || 0) + '%'; // If the sound is still playing, continue stepping. if (sound.playing()) { requestAnimationFrame(self.step.bind(self)); } }
javascript
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Determine our current seek position. var seek = sound.seek() || 0; timer.innerHTML = self.formatTime(Math.round(seek)); progress.style.width = (((seek / sound.duration()) * 100) || 0) + '%'; // If the sound is still playing, continue stepping. if (sound.playing()) { requestAnimationFrame(self.step.bind(self)); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Get the Howl we want to manipulate.", "var", "sound", "=", "self", ".", "playlist", "[", "self", ".", "index", "]", ".", "howl", ";", "// Determine our current seek position.", "var", "seek", "=", "sound", ".", "seek", "(", ")", "||", "0", ";", "timer", ".", "innerHTML", "=", "self", ".", "formatTime", "(", "Math", ".", "round", "(", "seek", ")", ")", ";", "progress", ".", "style", ".", "width", "=", "(", "(", "(", "seek", "/", "sound", ".", "duration", "(", ")", ")", "*", "100", ")", "||", "0", ")", "+", "'%'", ";", "// If the sound is still playing, continue stepping.", "if", "(", "sound", ".", "playing", "(", ")", ")", "{", "requestAnimationFrame", "(", "self", ".", "step", ".", "bind", "(", "self", ")", ")", ";", "}", "}" ]
The step called within requestAnimationFrame to update the playback position.
[ "The", "step", "called", "within", "requestAnimationFrame", "to", "update", "the", "playback", "position", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L216-L231
1,513
goldfire/howler.js
examples/player/player.js
function() { var height = window.innerHeight * 0.3; var width = window.innerWidth; wave.height = height; wave.height_2 = height / 2; wave.MAX = wave.height_2 - 4; wave.width = width; wave.width_2 = width / 2; wave.width_4 = width / 4; wave.canvas.height = height; wave.canvas.width = width; wave.container.style.margin = -(height / 2) + 'px auto'; // Update the position of the slider. var sound = player.playlist[player.index].howl; if (sound) { var vol = sound.volume(); var barWidth = (vol * 0.9); sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px'; } }
javascript
function() { var height = window.innerHeight * 0.3; var width = window.innerWidth; wave.height = height; wave.height_2 = height / 2; wave.MAX = wave.height_2 - 4; wave.width = width; wave.width_2 = width / 2; wave.width_4 = width / 4; wave.canvas.height = height; wave.canvas.width = width; wave.container.style.margin = -(height / 2) + 'px auto'; // Update the position of the slider. var sound = player.playlist[player.index].howl; if (sound) { var vol = sound.volume(); var barWidth = (vol * 0.9); sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px'; } }
[ "function", "(", ")", "{", "var", "height", "=", "window", ".", "innerHeight", "*", "0.3", ";", "var", "width", "=", "window", ".", "innerWidth", ";", "wave", ".", "height", "=", "height", ";", "wave", ".", "height_2", "=", "height", "/", "2", ";", "wave", ".", "MAX", "=", "wave", ".", "height_2", "-", "4", ";", "wave", ".", "width", "=", "width", ";", "wave", ".", "width_2", "=", "width", "/", "2", ";", "wave", ".", "width_4", "=", "width", "/", "4", ";", "wave", ".", "canvas", ".", "height", "=", "height", ";", "wave", ".", "canvas", ".", "width", "=", "width", ";", "wave", ".", "container", ".", "style", ".", "margin", "=", "-", "(", "height", "/", "2", ")", "+", "'px auto'", ";", "// Update the position of the slider.", "var", "sound", "=", "player", ".", "playlist", "[", "player", ".", "index", "]", ".", "howl", ";", "if", "(", "sound", ")", "{", "var", "vol", "=", "sound", ".", "volume", "(", ")", ";", "var", "barWidth", "=", "(", "vol", "*", "0.9", ")", ";", "sliderBtn", ".", "style", ".", "left", "=", "(", "window", ".", "innerWidth", "*", "barWidth", "+", "window", ".", "innerWidth", "*", "0.05", "-", "25", ")", "+", "'px'", ";", "}", "}" ]
Update the height of the wave animation. These are basically some hacks to get SiriWave.js to do what we want.
[ "Update", "the", "height", "of", "the", "wave", "animation", ".", "These", "are", "basically", "some", "hacks", "to", "get", "SiriWave", ".", "js", "to", "do", "what", "we", "want", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/player/player.js#L365-L385
1,514
jgraph/mxgraph
docs/js/toc.js
maketoc
function maketoc(element, enableSections) { enableSections = (enableSections != null) ? enableSections : true; var tmp = crawlDom(document.body, 2, 4, [], 30, enableSections); if (tmp.childNodes.length > 0) { element.appendChild(tmp); } }
javascript
function maketoc(element, enableSections) { enableSections = (enableSections != null) ? enableSections : true; var tmp = crawlDom(document.body, 2, 4, [], 30, enableSections); if (tmp.childNodes.length > 0) { element.appendChild(tmp); } }
[ "function", "maketoc", "(", "element", ",", "enableSections", ")", "{", "enableSections", "=", "(", "enableSections", "!=", "null", ")", "?", "enableSections", ":", "true", ";", "var", "tmp", "=", "crawlDom", "(", "document", ".", "body", ",", "2", ",", "4", ",", "[", "]", ",", "30", ",", "enableSections", ")", ";", "if", "(", "tmp", ".", "childNodes", ".", "length", ">", "0", ")", "{", "element", ".", "appendChild", "(", "tmp", ")", ";", "}", "}" ]
Creates a table of contents inside the given element.
[ "Creates", "a", "table", "of", "contents", "inside", "the", "given", "element", "." ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/docs/js/toc.js#L4-L13
1,515
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Graph.js
addPoint
function addPoint(type, x, y) { var rpt = new mxPoint(x, y); rpt.type = type; actual.push(rpt); var curr = (state.routedPoints != null) ? state.routedPoints[actual.length - 1] : null; return curr == null || curr.type != type || curr.x != x || curr.y != y; }
javascript
function addPoint(type, x, y) { var rpt = new mxPoint(x, y); rpt.type = type; actual.push(rpt); var curr = (state.routedPoints != null) ? state.routedPoints[actual.length - 1] : null; return curr == null || curr.type != type || curr.x != x || curr.y != y; }
[ "function", "addPoint", "(", "type", ",", "x", ",", "y", ")", "{", "var", "rpt", "=", "new", "mxPoint", "(", "x", ",", "y", ")", ";", "rpt", ".", "type", "=", "type", ";", "actual", ".", "push", "(", "rpt", ")", ";", "var", "curr", "=", "(", "state", ".", "routedPoints", "!=", "null", ")", "?", "state", ".", "routedPoints", "[", "actual", ".", "length", "-", "1", "]", ":", "null", ";", "return", "curr", "==", "null", "||", "curr", ".", "type", "!=", "type", "||", "curr", ".", "x", "!=", "x", "||", "curr", ".", "y", "!=", "y", ";", "}" ]
Type 0 means normal waypoint, 1 means jump
[ "Type", "0", "means", "normal", "waypoint", "1", "means", "jump" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Graph.js#L4089-L4098
1,516
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Graph.js
short
function short(str, max) { if (str.length > max) { str = str.substring(0, Math.round(max / 2)) + '...' + str.substring(str.length - Math.round(max / 4)); } return str; }
javascript
function short(str, max) { if (str.length > max) { str = str.substring(0, Math.round(max / 2)) + '...' + str.substring(str.length - Math.round(max / 4)); } return str; }
[ "function", "short", "(", "str", ",", "max", ")", "{", "if", "(", "str", ".", "length", ">", "max", ")", "{", "str", "=", "str", ".", "substring", "(", "0", ",", "Math", ".", "round", "(", "max", "/", "2", ")", ")", "+", "'...'", "+", "str", ".", "substring", "(", "str", ".", "length", "-", "Math", ".", "round", "(", "max", "/", "4", ")", ")", ";", "}", "return", "str", ";", "}" ]
Helper function to shorten strings
[ "Helper", "function", "to", "shorten", "strings" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Graph.js#L6835-L6844
1,517
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Graph.js
reference
function reference(node, clone) { clone.originalNode = node; node = node.firstChild; var child = clone.firstChild; while (node != null && child != null) { reference(node, child); node = node.nextSibling; child = child.nextSibling; } return clone; }
javascript
function reference(node, clone) { clone.originalNode = node; node = node.firstChild; var child = clone.firstChild; while (node != null && child != null) { reference(node, child); node = node.nextSibling; child = child.nextSibling; } return clone; }
[ "function", "reference", "(", "node", ",", "clone", ")", "{", "clone", ".", "originalNode", "=", "node", ";", "node", "=", "node", ".", "firstChild", ";", "var", "child", "=", "clone", ".", "firstChild", ";", "while", "(", "node", "!=", "null", "&&", "child", "!=", "null", ")", "{", "reference", "(", "node", ",", "child", ")", ";", "node", "=", "node", ".", "nextSibling", ";", "child", "=", "child", ".", "nextSibling", ";", "}", "return", "clone", ";", "}" ]
Adds a reference from the clone to the original node, recursively
[ "Adds", "a", "reference", "from", "the", "clone", "to", "the", "original", "node", "recursively" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Graph.js#L7139-L7154
1,518
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Graph.js
checkNode
function checkNode(node, clone) { if (node != null) { if (clone.originalNode != node) { cleanNode(node); } else { node = node.firstChild; clone = clone.firstChild; while (node != null) { var nextNode = node.nextSibling; if (clone == null) { cleanNode(node); } else { checkNode(node, clone); clone = clone.nextSibling; } node = nextNode; } } } }
javascript
function checkNode(node, clone) { if (node != null) { if (clone.originalNode != node) { cleanNode(node); } else { node = node.firstChild; clone = clone.firstChild; while (node != null) { var nextNode = node.nextSibling; if (clone == null) { cleanNode(node); } else { checkNode(node, clone); clone = clone.nextSibling; } node = nextNode; } } } }
[ "function", "checkNode", "(", "node", ",", "clone", ")", "{", "if", "(", "node", "!=", "null", ")", "{", "if", "(", "clone", ".", "originalNode", "!=", "node", ")", "{", "cleanNode", "(", "node", ")", ";", "}", "else", "{", "node", "=", "node", ".", "firstChild", ";", "clone", "=", "clone", ".", "firstChild", ";", "while", "(", "node", "!=", "null", ")", "{", "var", "nextNode", "=", "node", ".", "nextSibling", ";", "if", "(", "clone", "==", "null", ")", "{", "cleanNode", "(", "node", ")", ";", "}", "else", "{", "checkNode", "(", "node", ",", "clone", ")", ";", "clone", "=", "clone", ".", "nextSibling", ";", "}", "node", "=", "nextNode", ";", "}", "}", "}", "}" ]
Checks the given node for new nodes, recursively
[ "Checks", "the", "given", "node", "for", "new", "nodes", "recursively" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Graph.js#L7157-L7188
1,519
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Graph.js
cleanNode
function cleanNode(node) { var child = node.firstChild; while (child != null) { var next = child.nextSibling; cleanNode(child); child = next; } if ((node.nodeType != 1 || (node.nodeName !== 'BR' && node.firstChild == null)) && (node.nodeType != 3 || mxUtils.trim(mxUtils.getTextContent(node)).length == 0)) { node.parentNode.removeChild(node); } else { // Removes linefeeds if (node.nodeType == 3) { mxUtils.setTextContent(node, mxUtils.getTextContent(node).replace(/\n|\r/g, '')); } // Removes CSS classes and styles (for Word and Excel) if (node.nodeType == 1) { node.removeAttribute('style'); node.removeAttribute('class'); node.removeAttribute('width'); node.removeAttribute('cellpadding'); node.removeAttribute('cellspacing'); node.removeAttribute('border'); } } }
javascript
function cleanNode(node) { var child = node.firstChild; while (child != null) { var next = child.nextSibling; cleanNode(child); child = next; } if ((node.nodeType != 1 || (node.nodeName !== 'BR' && node.firstChild == null)) && (node.nodeType != 3 || mxUtils.trim(mxUtils.getTextContent(node)).length == 0)) { node.parentNode.removeChild(node); } else { // Removes linefeeds if (node.nodeType == 3) { mxUtils.setTextContent(node, mxUtils.getTextContent(node).replace(/\n|\r/g, '')); } // Removes CSS classes and styles (for Word and Excel) if (node.nodeType == 1) { node.removeAttribute('style'); node.removeAttribute('class'); node.removeAttribute('width'); node.removeAttribute('cellpadding'); node.removeAttribute('cellspacing'); node.removeAttribute('border'); } } }
[ "function", "cleanNode", "(", "node", ")", "{", "var", "child", "=", "node", ".", "firstChild", ";", "while", "(", "child", "!=", "null", ")", "{", "var", "next", "=", "child", ".", "nextSibling", ";", "cleanNode", "(", "child", ")", ";", "child", "=", "next", ";", "}", "if", "(", "(", "node", ".", "nodeType", "!=", "1", "||", "(", "node", ".", "nodeName", "!==", "'BR'", "&&", "node", ".", "firstChild", "==", "null", ")", ")", "&&", "(", "node", ".", "nodeType", "!=", "3", "||", "mxUtils", ".", "trim", "(", "mxUtils", ".", "getTextContent", "(", "node", ")", ")", ".", "length", "==", "0", ")", ")", "{", "node", ".", "parentNode", ".", "removeChild", "(", "node", ")", ";", "}", "else", "{", "// Removes linefeeds", "if", "(", "node", ".", "nodeType", "==", "3", ")", "{", "mxUtils", ".", "setTextContent", "(", "node", ",", "mxUtils", ".", "getTextContent", "(", "node", ")", ".", "replace", "(", "/", "\\n|\\r", "/", "g", ",", "''", ")", ")", ";", "}", "// Removes CSS classes and styles (for Word and Excel)", "if", "(", "node", ".", "nodeType", "==", "1", ")", "{", "node", ".", "removeAttribute", "(", "'style'", ")", ";", "node", ".", "removeAttribute", "(", "'class'", ")", ";", "node", ".", "removeAttribute", "(", "'width'", ")", ";", "node", ".", "removeAttribute", "(", "'cellpadding'", ")", ";", "node", ".", "removeAttribute", "(", "'cellspacing'", ")", ";", "node", ".", "removeAttribute", "(", "'border'", ")", ";", "}", "}", "}" ]
Removes unused DOM nodes and attributes, recursively
[ "Removes", "unused", "DOM", "nodes", "and", "attributes", "recursively" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Graph.js#L7191-L7226
1,520
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Graph.js
createHint
function createHint() { var hint = document.createElement('div'); hint.className = 'geHint'; hint.style.whiteSpace = 'nowrap'; hint.style.position = 'absolute'; return hint; }
javascript
function createHint() { var hint = document.createElement('div'); hint.className = 'geHint'; hint.style.whiteSpace = 'nowrap'; hint.style.position = 'absolute'; return hint; }
[ "function", "createHint", "(", ")", "{", "var", "hint", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "hint", ".", "className", "=", "'geHint'", ";", "hint", ".", "style", ".", "whiteSpace", "=", "'nowrap'", ";", "hint", ".", "style", ".", "position", "=", "'absolute'", ";", "return", "hint", ";", "}" ]
Hints on handlers
[ "Hints", "on", "handlers" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Graph.js#L7566-L7574
1,521
jgraph/mxgraph
javascript/examples/grapheditor/www/js/EditorUi.js
function(evt) { if (evt != null) { var source = mxEvent.getSource(evt); if (source.nodeName == 'A') { while (source != null) { if (source.className == 'geHint') { return true; } source = source.parentNode; } } } return textEditing(evt); }
javascript
function(evt) { if (evt != null) { var source = mxEvent.getSource(evt); if (source.nodeName == 'A') { while (source != null) { if (source.className == 'geHint') { return true; } source = source.parentNode; } } } return textEditing(evt); }
[ "function", "(", "evt", ")", "{", "if", "(", "evt", "!=", "null", ")", "{", "var", "source", "=", "mxEvent", ".", "getSource", "(", "evt", ")", ";", "if", "(", "source", ".", "nodeName", "==", "'A'", ")", "{", "while", "(", "source", "!=", "null", ")", "{", "if", "(", "source", ".", "className", "==", "'geHint'", ")", "{", "return", "true", ";", "}", "source", "=", "source", ".", "parentNode", ";", "}", "}", "}", "return", "textEditing", "(", "evt", ")", ";", "}" ]
Allows context menu for links in hints
[ "Allows", "context", "menu", "for", "links", "in", "hints" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/EditorUi.js#L96-L117
1,522
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Format.js
isOrContains
function isOrContains(container, node) { while (node != null) { if (node === container) { return true; } node = node.parentNode; } return false; }
javascript
function isOrContains(container, node) { while (node != null) { if (node === container) { return true; } node = node.parentNode; } return false; }
[ "function", "isOrContains", "(", "container", ",", "node", ")", "{", "while", "(", "node", "!=", "null", ")", "{", "if", "(", "node", "===", "container", ")", "{", "return", "true", ";", "}", "node", "=", "node", ".", "parentNode", ";", "}", "return", "false", ";", "}" ]
Node.contains does not work for text nodes in IE11
[ "Node", ".", "contains", "does", "not", "work", "for", "text", "nodes", "in", "IE11" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Format.js#L2893-L2906
1,523
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Menus.js
Menu
function Menu(funct, enabled) { mxEventSource.call(this); this.funct = funct; this.enabled = (enabled != null) ? enabled : true; }
javascript
function Menu(funct, enabled) { mxEventSource.call(this); this.funct = funct; this.enabled = (enabled != null) ? enabled : true; }
[ "function", "Menu", "(", "funct", ",", "enabled", ")", "{", "mxEventSource", ".", "call", "(", "this", ")", ";", "this", ".", "funct", "=", "funct", ";", "this", ".", "enabled", "=", "(", "enabled", "!=", "null", ")", "?", "enabled", ":", "true", ";", "}" ]
Constructs a new action for the given parameters.
[ "Constructs", "a", "new", "action", "for", "the", "given", "parameters", "." ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Menus.js#L1280-L1285
1,524
jgraph/mxgraph
javascript/examples/grapheditor/www/js/Editor.js
preview
function preview(print) { var autoOrigin = onePageCheckBox.checked || pageCountCheckBox.checked; var printScale = parseInt(pageScaleInput.value) / 100; if (isNaN(printScale)) { printScale = 1; pageScaleInput.value = '100%'; } // Workaround to match available paper size in actual print output printScale *= 0.75; var pf = graph.pageFormat || mxConstants.PAGE_FORMAT_A4_PORTRAIT; var scale = 1 / graph.pageScale; if (autoOrigin) { var pageCount = (onePageCheckBox.checked) ? 1 : parseInt(pageCountInput.value); if (!isNaN(pageCount)) { scale = mxUtils.getScaleForPageCount(pageCount, graph, pf); } } // Negative coordinates are cropped or shifted if page visible var gb = graph.getGraphBounds(); var border = 0; var x0 = 0; var y0 = 0; // Applies print scale pf = mxRectangle.fromRectangle(pf); pf.width = Math.ceil(pf.width * printScale); pf.height = Math.ceil(pf.height * printScale); scale *= printScale; // Starts at first visible page if (!autoOrigin && graph.pageVisible) { var layout = graph.getPageLayout(); x0 -= layout.x * pf.width; y0 -= layout.y * pf.height; } else { autoOrigin = true; } var preview = PrintDialog.createPrintPreview(graph, scale, pf, border, x0, y0, autoOrigin); preview.open(); if (print) { PrintDialog.printPreview(preview); } }
javascript
function preview(print) { var autoOrigin = onePageCheckBox.checked || pageCountCheckBox.checked; var printScale = parseInt(pageScaleInput.value) / 100; if (isNaN(printScale)) { printScale = 1; pageScaleInput.value = '100%'; } // Workaround to match available paper size in actual print output printScale *= 0.75; var pf = graph.pageFormat || mxConstants.PAGE_FORMAT_A4_PORTRAIT; var scale = 1 / graph.pageScale; if (autoOrigin) { var pageCount = (onePageCheckBox.checked) ? 1 : parseInt(pageCountInput.value); if (!isNaN(pageCount)) { scale = mxUtils.getScaleForPageCount(pageCount, graph, pf); } } // Negative coordinates are cropped or shifted if page visible var gb = graph.getGraphBounds(); var border = 0; var x0 = 0; var y0 = 0; // Applies print scale pf = mxRectangle.fromRectangle(pf); pf.width = Math.ceil(pf.width * printScale); pf.height = Math.ceil(pf.height * printScale); scale *= printScale; // Starts at first visible page if (!autoOrigin && graph.pageVisible) { var layout = graph.getPageLayout(); x0 -= layout.x * pf.width; y0 -= layout.y * pf.height; } else { autoOrigin = true; } var preview = PrintDialog.createPrintPreview(graph, scale, pf, border, x0, y0, autoOrigin); preview.open(); if (print) { PrintDialog.printPreview(preview); } }
[ "function", "preview", "(", "print", ")", "{", "var", "autoOrigin", "=", "onePageCheckBox", ".", "checked", "||", "pageCountCheckBox", ".", "checked", ";", "var", "printScale", "=", "parseInt", "(", "pageScaleInput", ".", "value", ")", "/", "100", ";", "if", "(", "isNaN", "(", "printScale", ")", ")", "{", "printScale", "=", "1", ";", "pageScaleInput", ".", "value", "=", "'100%'", ";", "}", "// Workaround to match available paper size in actual print output", "printScale", "*=", "0.75", ";", "var", "pf", "=", "graph", ".", "pageFormat", "||", "mxConstants", ".", "PAGE_FORMAT_A4_PORTRAIT", ";", "var", "scale", "=", "1", "/", "graph", ".", "pageScale", ";", "if", "(", "autoOrigin", ")", "{", "var", "pageCount", "=", "(", "onePageCheckBox", ".", "checked", ")", "?", "1", ":", "parseInt", "(", "pageCountInput", ".", "value", ")", ";", "if", "(", "!", "isNaN", "(", "pageCount", ")", ")", "{", "scale", "=", "mxUtils", ".", "getScaleForPageCount", "(", "pageCount", ",", "graph", ",", "pf", ")", ";", "}", "}", "// Negative coordinates are cropped or shifted if page visible", "var", "gb", "=", "graph", ".", "getGraphBounds", "(", ")", ";", "var", "border", "=", "0", ";", "var", "x0", "=", "0", ";", "var", "y0", "=", "0", ";", "// Applies print scale", "pf", "=", "mxRectangle", ".", "fromRectangle", "(", "pf", ")", ";", "pf", ".", "width", "=", "Math", ".", "ceil", "(", "pf", ".", "width", "*", "printScale", ")", ";", "pf", ".", "height", "=", "Math", ".", "ceil", "(", "pf", ".", "height", "*", "printScale", ")", ";", "scale", "*=", "printScale", ";", "// Starts at first visible page", "if", "(", "!", "autoOrigin", "&&", "graph", ".", "pageVisible", ")", "{", "var", "layout", "=", "graph", ".", "getPageLayout", "(", ")", ";", "x0", "-=", "layout", ".", "x", "*", "pf", ".", "width", ";", "y0", "-=", "layout", ".", "y", "*", "pf", ".", "height", ";", "}", "else", "{", "autoOrigin", "=", "true", ";", "}", "var", "preview", "=", "PrintDialog", ".", "createPrintPreview", "(", "graph", ",", "scale", ",", "pf", ",", "border", ",", "x0", ",", "y0", ",", "autoOrigin", ")", ";", "preview", ".", "open", "(", ")", ";", "if", "(", "print", ")", "{", "PrintDialog", ".", "printPreview", "(", "preview", ")", ";", "}", "}" ]
Overall scale for print-out to account for print borders in dialogs etc
[ "Overall", "scale", "for", "print", "-", "out", "to", "account", "for", "print", "borders", "in", "dialogs", "etc" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/examples/grapheditor/www/js/Editor.js#L1111-L1169
1,525
jgraph/mxgraph
javascript/mxClient.js
snapX
function snapX(x, state) { x += this.graph.panDx; var override = false; if (Math.abs(x - center) < ttX) { dx = x - bounds.getCenterX(); ttX = Math.abs(x - center); override = true; } else if (Math.abs(x - left) < ttX) { dx = x - bounds.x; ttX = Math.abs(x - left); override = true; } else if (Math.abs(x - right) < ttX) { dx = x - bounds.x - bounds.width; ttX = Math.abs(x - right); override = true; } if (override) { stateX = state; valueX = Math.round(x - this.graph.panDx); if (this.guideX == null) { this.guideX = this.createGuideShape(true); // Makes sure to use either VML or SVG shapes in order to implement // event-transparency on the background area of the rectangle since // HTML shapes do not let mouseevents through even when transparent this.guideX.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_VML : mxConstants.DIALECT_SVG; this.guideX.pointerEvents = false; this.guideX.init(this.graph.getView().getOverlayPane()); } } overrideX = overrideX || override; }
javascript
function snapX(x, state) { x += this.graph.panDx; var override = false; if (Math.abs(x - center) < ttX) { dx = x - bounds.getCenterX(); ttX = Math.abs(x - center); override = true; } else if (Math.abs(x - left) < ttX) { dx = x - bounds.x; ttX = Math.abs(x - left); override = true; } else if (Math.abs(x - right) < ttX) { dx = x - bounds.x - bounds.width; ttX = Math.abs(x - right); override = true; } if (override) { stateX = state; valueX = Math.round(x - this.graph.panDx); if (this.guideX == null) { this.guideX = this.createGuideShape(true); // Makes sure to use either VML or SVG shapes in order to implement // event-transparency on the background area of the rectangle since // HTML shapes do not let mouseevents through even when transparent this.guideX.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_VML : mxConstants.DIALECT_SVG; this.guideX.pointerEvents = false; this.guideX.init(this.graph.getView().getOverlayPane()); } } overrideX = overrideX || override; }
[ "function", "snapX", "(", "x", ",", "state", ")", "{", "x", "+=", "this", ".", "graph", ".", "panDx", ";", "var", "override", "=", "false", ";", "if", "(", "Math", ".", "abs", "(", "x", "-", "center", ")", "<", "ttX", ")", "{", "dx", "=", "x", "-", "bounds", ".", "getCenterX", "(", ")", ";", "ttX", "=", "Math", ".", "abs", "(", "x", "-", "center", ")", ";", "override", "=", "true", ";", "}", "else", "if", "(", "Math", ".", "abs", "(", "x", "-", "left", ")", "<", "ttX", ")", "{", "dx", "=", "x", "-", "bounds", ".", "x", ";", "ttX", "=", "Math", ".", "abs", "(", "x", "-", "left", ")", ";", "override", "=", "true", ";", "}", "else", "if", "(", "Math", ".", "abs", "(", "x", "-", "right", ")", "<", "ttX", ")", "{", "dx", "=", "x", "-", "bounds", ".", "x", "-", "bounds", ".", "width", ";", "ttX", "=", "Math", ".", "abs", "(", "x", "-", "right", ")", ";", "override", "=", "true", ";", "}", "if", "(", "override", ")", "{", "stateX", "=", "state", ";", "valueX", "=", "Math", ".", "round", "(", "x", "-", "this", ".", "graph", ".", "panDx", ")", ";", "if", "(", "this", ".", "guideX", "==", "null", ")", "{", "this", ".", "guideX", "=", "this", ".", "createGuideShape", "(", "true", ")", ";", "// Makes sure to use either VML or SVG shapes in order to implement", "// event-transparency on the background area of the rectangle since", "// HTML shapes do not let mouseevents through even when transparent", "this", ".", "guideX", ".", "dialect", "=", "(", "this", ".", "graph", ".", "dialect", "!=", "mxConstants", ".", "DIALECT_SVG", ")", "?", "mxConstants", ".", "DIALECT_VML", ":", "mxConstants", ".", "DIALECT_SVG", ";", "this", ".", "guideX", ".", "pointerEvents", "=", "false", ";", "this", ".", "guideX", ".", "init", "(", "this", ".", "graph", ".", "getView", "(", ")", ".", "getOverlayPane", "(", ")", ")", ";", "}", "}", "overrideX", "=", "overrideX", "||", "override", ";", "}" ]
Snaps the left, center and right to the given x-coordinate
[ "Snaps", "the", "left", "center", "and", "right", "to", "the", "given", "x", "-", "coordinate" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/mxClient.js#L21854-L21898
1,526
jgraph/mxgraph
javascript/mxClient.js
snapY
function snapY(y, state) { y += this.graph.panDy; var override = false; if (Math.abs(y - middle) < ttY) { dy = y - bounds.getCenterY(); ttY = Math.abs(y - middle); override = true; } else if (Math.abs(y - top) < ttY) { dy = y - bounds.y; ttY = Math.abs(y - top); override = true; } else if (Math.abs(y - bottom) < ttY) { dy = y - bounds.y - bounds.height; ttY = Math.abs(y - bottom); override = true; } if (override) { stateY = state; valueY = Math.round(y - this.graph.panDy); if (this.guideY == null) { this.guideY = this.createGuideShape(false); // Makes sure to use either VML or SVG shapes in order to implement // event-transparency on the background area of the rectangle since // HTML shapes do not let mouseevents through even when transparent this.guideY.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_VML : mxConstants.DIALECT_SVG; this.guideY.pointerEvents = false; this.guideY.init(this.graph.getView().getOverlayPane()); } } overrideY = overrideY || override; }
javascript
function snapY(y, state) { y += this.graph.panDy; var override = false; if (Math.abs(y - middle) < ttY) { dy = y - bounds.getCenterY(); ttY = Math.abs(y - middle); override = true; } else if (Math.abs(y - top) < ttY) { dy = y - bounds.y; ttY = Math.abs(y - top); override = true; } else if (Math.abs(y - bottom) < ttY) { dy = y - bounds.y - bounds.height; ttY = Math.abs(y - bottom); override = true; } if (override) { stateY = state; valueY = Math.round(y - this.graph.panDy); if (this.guideY == null) { this.guideY = this.createGuideShape(false); // Makes sure to use either VML or SVG shapes in order to implement // event-transparency on the background area of the rectangle since // HTML shapes do not let mouseevents through even when transparent this.guideY.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_VML : mxConstants.DIALECT_SVG; this.guideY.pointerEvents = false; this.guideY.init(this.graph.getView().getOverlayPane()); } } overrideY = overrideY || override; }
[ "function", "snapY", "(", "y", ",", "state", ")", "{", "y", "+=", "this", ".", "graph", ".", "panDy", ";", "var", "override", "=", "false", ";", "if", "(", "Math", ".", "abs", "(", "y", "-", "middle", ")", "<", "ttY", ")", "{", "dy", "=", "y", "-", "bounds", ".", "getCenterY", "(", ")", ";", "ttY", "=", "Math", ".", "abs", "(", "y", "-", "middle", ")", ";", "override", "=", "true", ";", "}", "else", "if", "(", "Math", ".", "abs", "(", "y", "-", "top", ")", "<", "ttY", ")", "{", "dy", "=", "y", "-", "bounds", ".", "y", ";", "ttY", "=", "Math", ".", "abs", "(", "y", "-", "top", ")", ";", "override", "=", "true", ";", "}", "else", "if", "(", "Math", ".", "abs", "(", "y", "-", "bottom", ")", "<", "ttY", ")", "{", "dy", "=", "y", "-", "bounds", ".", "y", "-", "bounds", ".", "height", ";", "ttY", "=", "Math", ".", "abs", "(", "y", "-", "bottom", ")", ";", "override", "=", "true", ";", "}", "if", "(", "override", ")", "{", "stateY", "=", "state", ";", "valueY", "=", "Math", ".", "round", "(", "y", "-", "this", ".", "graph", ".", "panDy", ")", ";", "if", "(", "this", ".", "guideY", "==", "null", ")", "{", "this", ".", "guideY", "=", "this", ".", "createGuideShape", "(", "false", ")", ";", "// Makes sure to use either VML or SVG shapes in order to implement", "// event-transparency on the background area of the rectangle since", "// HTML shapes do not let mouseevents through even when transparent", "this", ".", "guideY", ".", "dialect", "=", "(", "this", ".", "graph", ".", "dialect", "!=", "mxConstants", ".", "DIALECT_SVG", ")", "?", "mxConstants", ".", "DIALECT_VML", ":", "mxConstants", ".", "DIALECT_SVG", ";", "this", ".", "guideY", ".", "pointerEvents", "=", "false", ";", "this", ".", "guideY", ".", "init", "(", "this", ".", "graph", ".", "getView", "(", ")", ".", "getOverlayPane", "(", ")", ")", ";", "}", "}", "overrideY", "=", "overrideY", "||", "override", ";", "}" ]
Snaps the top, middle or bottom to the given y-coordinate
[ "Snaps", "the", "top", "middle", "or", "bottom", "to", "the", "given", "y", "-", "coordinate" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/mxClient.js#L21901-L21945
1,527
jgraph/mxgraph
javascript/mxClient.js
pushPoint
function pushPoint(pt) { if (lastPushed == null || Math.abs(lastPushed.x - pt.x) >= tol || Math.abs(lastPushed.y - pt.y) >= tol) { result.push(pt); lastPushed = pt; } return lastPushed; }
javascript
function pushPoint(pt) { if (lastPushed == null || Math.abs(lastPushed.x - pt.x) >= tol || Math.abs(lastPushed.y - pt.y) >= tol) { result.push(pt); lastPushed = pt; } return lastPushed; }
[ "function", "pushPoint", "(", "pt", ")", "{", "if", "(", "lastPushed", "==", "null", "||", "Math", ".", "abs", "(", "lastPushed", ".", "x", "-", "pt", ".", "x", ")", ">=", "tol", "||", "Math", ".", "abs", "(", "lastPushed", ".", "y", "-", "pt", ".", "y", ")", ">=", "tol", ")", "{", "result", ".", "push", "(", "pt", ")", ";", "lastPushed", "=", "pt", ";", "}", "return", "lastPushed", ";", "}" ]
Adds waypoints only if outside of tolerance
[ "Adds", "waypoints", "only", "if", "outside", "of", "tolerance" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/mxClient.js#L50016-L50025
1,528
jgraph/mxgraph
javascript/mxClient.js
function(state, source, target, points, isSource) { var value = mxUtils.getValue(state.style, (isSource) ? mxConstants.STYLE_SOURCE_JETTY_SIZE : mxConstants.STYLE_TARGET_JETTY_SIZE, mxUtils.getValue(state.style, mxConstants.STYLE_JETTY_SIZE, mxEdgeStyle.orthBuffer)); if (value == 'auto') { // Computes the automatic jetty size var type = mxUtils.getValue(state.style, (isSource) ? mxConstants.STYLE_STARTARROW : mxConstants.STYLE_ENDARROW, mxConstants.NONE); if (type != mxConstants.NONE) { var size = mxUtils.getNumber(state.style, (isSource) ? mxConstants.STYLE_STARTSIZE : mxConstants.STYLE_ENDSIZE, mxConstants.DEFAULT_MARKERSIZE); value = Math.max(2, Math.ceil((size + mxEdgeStyle.orthBuffer) / mxEdgeStyle.orthBuffer)) * mxEdgeStyle.orthBuffer; } else { value = 2 * mxEdgeStyle.orthBuffer; } } return value; }
javascript
function(state, source, target, points, isSource) { var value = mxUtils.getValue(state.style, (isSource) ? mxConstants.STYLE_SOURCE_JETTY_SIZE : mxConstants.STYLE_TARGET_JETTY_SIZE, mxUtils.getValue(state.style, mxConstants.STYLE_JETTY_SIZE, mxEdgeStyle.orthBuffer)); if (value == 'auto') { // Computes the automatic jetty size var type = mxUtils.getValue(state.style, (isSource) ? mxConstants.STYLE_STARTARROW : mxConstants.STYLE_ENDARROW, mxConstants.NONE); if (type != mxConstants.NONE) { var size = mxUtils.getNumber(state.style, (isSource) ? mxConstants.STYLE_STARTSIZE : mxConstants.STYLE_ENDSIZE, mxConstants.DEFAULT_MARKERSIZE); value = Math.max(2, Math.ceil((size + mxEdgeStyle.orthBuffer) / mxEdgeStyle.orthBuffer)) * mxEdgeStyle.orthBuffer; } else { value = 2 * mxEdgeStyle.orthBuffer; } } return value; }
[ "function", "(", "state", ",", "source", ",", "target", ",", "points", ",", "isSource", ")", "{", "var", "value", "=", "mxUtils", ".", "getValue", "(", "state", ".", "style", ",", "(", "isSource", ")", "?", "mxConstants", ".", "STYLE_SOURCE_JETTY_SIZE", ":", "mxConstants", ".", "STYLE_TARGET_JETTY_SIZE", ",", "mxUtils", ".", "getValue", "(", "state", ".", "style", ",", "mxConstants", ".", "STYLE_JETTY_SIZE", ",", "mxEdgeStyle", ".", "orthBuffer", ")", ")", ";", "if", "(", "value", "==", "'auto'", ")", "{", "// Computes the automatic jetty size", "var", "type", "=", "mxUtils", ".", "getValue", "(", "state", ".", "style", ",", "(", "isSource", ")", "?", "mxConstants", ".", "STYLE_STARTARROW", ":", "mxConstants", ".", "STYLE_ENDARROW", ",", "mxConstants", ".", "NONE", ")", ";", "if", "(", "type", "!=", "mxConstants", ".", "NONE", ")", "{", "var", "size", "=", "mxUtils", ".", "getNumber", "(", "state", ".", "style", ",", "(", "isSource", ")", "?", "mxConstants", ".", "STYLE_STARTSIZE", ":", "mxConstants", ".", "STYLE_ENDSIZE", ",", "mxConstants", ".", "DEFAULT_MARKERSIZE", ")", ";", "value", "=", "Math", ".", "max", "(", "2", ",", "Math", ".", "ceil", "(", "(", "size", "+", "mxEdgeStyle", ".", "orthBuffer", ")", "/", "mxEdgeStyle", ".", "orthBuffer", ")", ")", "*", "mxEdgeStyle", ".", "orthBuffer", ";", "}", "else", "{", "value", "=", "2", "*", "mxEdgeStyle", ".", "orthBuffer", ";", "}", "}", "return", "value", ";", "}" ]
mxEdgeStyle.SOURCE_MASK | mxEdgeStyle.TARGET_MASK,
[ "mxEdgeStyle", ".", "SOURCE_MASK", "|", "mxEdgeStyle", ".", "TARGET_MASK" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/mxClient.js#L50364-L50387
1,529
jgraph/mxgraph
javascript/mxClient.js
function(evt) { var state = null; // Workaround for touch events which started on some DOM node // on top of the container, in which case the cells under the // mouse for the move and up events are not detected. if (mxClient.IS_TOUCH) { var x = mxEvent.getClientX(evt); var y = mxEvent.getClientY(evt); // Dispatches the drop event to the graph which // consumes and executes the source function var pt = mxUtils.convertPoint(container, x, y); state = graph.view.getState(graph.getCellAt(pt.x, pt.y)); } return state; }
javascript
function(evt) { var state = null; // Workaround for touch events which started on some DOM node // on top of the container, in which case the cells under the // mouse for the move and up events are not detected. if (mxClient.IS_TOUCH) { var x = mxEvent.getClientX(evt); var y = mxEvent.getClientY(evt); // Dispatches the drop event to the graph which // consumes and executes the source function var pt = mxUtils.convertPoint(container, x, y); state = graph.view.getState(graph.getCellAt(pt.x, pt.y)); } return state; }
[ "function", "(", "evt", ")", "{", "var", "state", "=", "null", ";", "// Workaround for touch events which started on some DOM node", "// on top of the container, in which case the cells under the", "// mouse for the move and up events are not detected.", "if", "(", "mxClient", ".", "IS_TOUCH", ")", "{", "var", "x", "=", "mxEvent", ".", "getClientX", "(", "evt", ")", ";", "var", "y", "=", "mxEvent", ".", "getClientY", "(", "evt", ")", ";", "// Dispatches the drop event to the graph which", "// consumes and executes the source function", "var", "pt", "=", "mxUtils", ".", "convertPoint", "(", "container", ",", "x", ",", "y", ")", ";", "state", "=", "graph", ".", "view", ".", "getState", "(", "graph", ".", "getCellAt", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", ")", ";", "}", "return", "state", ";", "}" ]
Workaround for touch events which started on some DOM node on top of the container, in which case the cells under the mouse for the move and up events are not detected.
[ "Workaround", "for", "touch", "events", "which", "started", "on", "some", "DOM", "node", "on", "top", "of", "the", "container", "in", "which", "case", "the", "cells", "under", "the", "mouse", "for", "the", "move", "and", "up", "events", "are", "not", "detected", "." ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/mxClient.js#L53687-L53706
1,530
jgraph/mxgraph
javascript/mxClient.js
function(sender, evt) { var changes = evt.getProperty('edit').changes; graph.setSelectionCells(graph.getSelectionCellsForChanges(changes)); }
javascript
function(sender, evt) { var changes = evt.getProperty('edit').changes; graph.setSelectionCells(graph.getSelectionCellsForChanges(changes)); }
[ "function", "(", "sender", ",", "evt", ")", "{", "var", "changes", "=", "evt", ".", "getProperty", "(", "'edit'", ")", ".", "changes", ";", "graph", ".", "setSelectionCells", "(", "graph", ".", "getSelectionCellsForChanges", "(", "changes", ")", ")", ";", "}" ]
Keeps the selection state in sync
[ "Keeps", "the", "selection", "state", "in", "sync" ]
33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44
https://github.com/jgraph/mxgraph/blob/33911ed7e055c17b74d0367f5f1f6c9ee4b4fd44/javascript/mxClient.js#L84652-L84656
1,531
discordjs/discord.js
src/errors/DJSError.js
makeDiscordjsError
function makeDiscordjsError(Base) { return class DiscordjsError extends Base { constructor(key, ...args) { super(message(key, args)); this[kCode] = key; if (Error.captureStackTrace) Error.captureStackTrace(this, DiscordjsError); } get name() { return `${super.name} [${this[kCode]}]`; } get code() { return this[kCode]; } }; }
javascript
function makeDiscordjsError(Base) { return class DiscordjsError extends Base { constructor(key, ...args) { super(message(key, args)); this[kCode] = key; if (Error.captureStackTrace) Error.captureStackTrace(this, DiscordjsError); } get name() { return `${super.name} [${this[kCode]}]`; } get code() { return this[kCode]; } }; }
[ "function", "makeDiscordjsError", "(", "Base", ")", "{", "return", "class", "DiscordjsError", "extends", "Base", "{", "constructor", "(", "key", ",", "...", "args", ")", "{", "super", "(", "message", "(", "key", ",", "args", ")", ")", ";", "this", "[", "kCode", "]", "=", "key", ";", "if", "(", "Error", ".", "captureStackTrace", ")", "Error", ".", "captureStackTrace", "(", "this", ",", "DiscordjsError", ")", ";", "}", "get", "name", "(", ")", "{", "return", "`", "${", "super", ".", "name", "}", "${", "this", "[", "kCode", "]", "}", "`", ";", "}", "get", "code", "(", ")", "{", "return", "this", "[", "kCode", "]", ";", "}", "}", ";", "}" ]
Extend an error of some sort into a DiscordjsError. @param {Error} Base Base error to extend @returns {DiscordjsError}
[ "Extend", "an", "error", "of", "some", "sort", "into", "a", "DiscordjsError", "." ]
75d5598fdada9ad1913b533e70d049de0d4ff7af
https://github.com/discordjs/discord.js/blob/75d5598fdada9ad1913b533e70d049de0d4ff7af/src/errors/DJSError.js#L13-L29
1,532
discordjs/discord.js
src/errors/DJSError.js
message
function message(key, args) { if (typeof key !== 'string') throw new Error('Error message key must be a string'); const msg = messages.get(key); if (!msg) throw new Error(`An invalid error message key was used: ${key}.`); if (typeof msg === 'function') return msg(...args); if (args === undefined || args.length === 0) return msg; args.unshift(msg); return String(...args); }
javascript
function message(key, args) { if (typeof key !== 'string') throw new Error('Error message key must be a string'); const msg = messages.get(key); if (!msg) throw new Error(`An invalid error message key was used: ${key}.`); if (typeof msg === 'function') return msg(...args); if (args === undefined || args.length === 0) return msg; args.unshift(msg); return String(...args); }
[ "function", "message", "(", "key", ",", "args", ")", "{", "if", "(", "typeof", "key", "!==", "'string'", ")", "throw", "new", "Error", "(", "'Error message key must be a string'", ")", ";", "const", "msg", "=", "messages", ".", "get", "(", "key", ")", ";", "if", "(", "!", "msg", ")", "throw", "new", "Error", "(", "`", "${", "key", "}", "`", ")", ";", "if", "(", "typeof", "msg", "===", "'function'", ")", "return", "msg", "(", "...", "args", ")", ";", "if", "(", "args", "===", "undefined", "||", "args", ".", "length", "===", "0", ")", "return", "msg", ";", "args", ".", "unshift", "(", "msg", ")", ";", "return", "String", "(", "...", "args", ")", ";", "}" ]
Format the message for an error. @param {string} key Error key @param {Array<*>} args Arguments to pass for util format or as function args @returns {string} Formatted string
[ "Format", "the", "message", "for", "an", "error", "." ]
75d5598fdada9ad1913b533e70d049de0d4ff7af
https://github.com/discordjs/discord.js/blob/75d5598fdada9ad1913b533e70d049de0d4ff7af/src/errors/DJSError.js#L37-L45
1,533
discordjs/discord.js
src/errors/DJSError.js
register
function register(sym, val) { messages.set(sym, typeof val === 'function' ? val : String(val)); }
javascript
function register(sym, val) { messages.set(sym, typeof val === 'function' ? val : String(val)); }
[ "function", "register", "(", "sym", ",", "val", ")", "{", "messages", ".", "set", "(", "sym", ",", "typeof", "val", "===", "'function'", "?", "val", ":", "String", "(", "val", ")", ")", ";", "}" ]
Register an error code and message. @param {string} sym Unique name for the error @param {*} val Value of the error
[ "Register", "an", "error", "code", "and", "message", "." ]
75d5598fdada9ad1913b533e70d049de0d4ff7af
https://github.com/discordjs/discord.js/blob/75d5598fdada9ad1913b533e70d049de0d4ff7af/src/errors/DJSError.js#L52-L54
1,534
webdriverio/webdriverio
packages/wdio-sync/src/index.js
function (fn, repeatTest = 0, args = []) { /** * if a new hook gets executed we can assume that all commands should have finised * with exception of timeouts where `commandIsRunning` will never be reset but here */ // commandIsRunning = false return new Promise((resolve, reject) => { try { const res = fn.apply(this, args) resolve(res) } catch (e) { if (repeatTest) { return resolve(executeSync(fn, --repeatTest, args)) } /** * no need to modify stack if no stack available */ if (!e.stack) { return reject(e) } e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n') reject(e) } }) }
javascript
function (fn, repeatTest = 0, args = []) { /** * if a new hook gets executed we can assume that all commands should have finised * with exception of timeouts where `commandIsRunning` will never be reset but here */ // commandIsRunning = false return new Promise((resolve, reject) => { try { const res = fn.apply(this, args) resolve(res) } catch (e) { if (repeatTest) { return resolve(executeSync(fn, --repeatTest, args)) } /** * no need to modify stack if no stack available */ if (!e.stack) { return reject(e) } e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n') reject(e) } }) }
[ "function", "(", "fn", ",", "repeatTest", "=", "0", ",", "args", "=", "[", "]", ")", "{", "/**\n * if a new hook gets executed we can assume that all commands should have finised\n * with exception of timeouts where `commandIsRunning` will never be reset but here\n */", "// commandIsRunning = false", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "const", "res", "=", "fn", ".", "apply", "(", "this", ",", "args", ")", "resolve", "(", "res", ")", "}", "catch", "(", "e", ")", "{", "if", "(", "repeatTest", ")", "{", "return", "resolve", "(", "executeSync", "(", "fn", ",", "--", "repeatTest", ",", "args", ")", ")", "}", "/**\n * no need to modify stack if no stack available\n */", "if", "(", "!", "e", ".", "stack", ")", "{", "return", "reject", "(", "e", ")", "}", "e", ".", "stack", "=", "e", ".", "stack", ".", "split", "(", "'\\n'", ")", ".", "filter", "(", "STACKTRACE_FILTER_FN", ")", ".", "join", "(", "'\\n'", ")", "reject", "(", "e", ")", "}", "}", ")", "}" ]
execute test or hook synchronously @param {Function} fn spec or hook method @param {Number} repeatTest number of retries @return {Promise} that gets resolved once test/hook is done or was retried enough
[ "execute", "test", "or", "hook", "synchronously" ]
8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1
https://github.com/webdriverio/webdriverio/blob/8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1/packages/wdio-sync/src/index.js#L19-L46
1,535
webdriverio/webdriverio
packages/wdio-sync/src/index.js
function (fn, repeatTest = 0, args = []) { let result, error /** * if a new hook gets executed we can assume that all commands should have finised * with exception of timeouts where `commandIsRunning` will never be reset but here */ // commandIsRunning = false try { result = fn.apply(this, args) } catch (e) { error = e } /** * handle errors that get thrown directly and are not cause by * rejected promises */ if (error) { if (repeatTest) { return executeAsync(fn, --repeatTest, args) } return new Promise((resolve, reject) => reject(error)) } /** * if we don't retry just return result */ if (repeatTest === 0 || !result || typeof result.catch !== 'function') { return new Promise(resolve => resolve(result)) } /** * handle promise response */ return result.catch((e) => { if (repeatTest) { return executeAsync(fn, --repeatTest, args) } e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n') return Promise.reject(e) }) }
javascript
function (fn, repeatTest = 0, args = []) { let result, error /** * if a new hook gets executed we can assume that all commands should have finised * with exception of timeouts where `commandIsRunning` will never be reset but here */ // commandIsRunning = false try { result = fn.apply(this, args) } catch (e) { error = e } /** * handle errors that get thrown directly and are not cause by * rejected promises */ if (error) { if (repeatTest) { return executeAsync(fn, --repeatTest, args) } return new Promise((resolve, reject) => reject(error)) } /** * if we don't retry just return result */ if (repeatTest === 0 || !result || typeof result.catch !== 'function') { return new Promise(resolve => resolve(result)) } /** * handle promise response */ return result.catch((e) => { if (repeatTest) { return executeAsync(fn, --repeatTest, args) } e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n') return Promise.reject(e) }) }
[ "function", "(", "fn", ",", "repeatTest", "=", "0", ",", "args", "=", "[", "]", ")", "{", "let", "result", ",", "error", "/**\n * if a new hook gets executed we can assume that all commands should have finised\n * with exception of timeouts where `commandIsRunning` will never be reset but here\n */", "// commandIsRunning = false", "try", "{", "result", "=", "fn", ".", "apply", "(", "this", ",", "args", ")", "}", "catch", "(", "e", ")", "{", "error", "=", "e", "}", "/**\n * handle errors that get thrown directly and are not cause by\n * rejected promises\n */", "if", "(", "error", ")", "{", "if", "(", "repeatTest", ")", "{", "return", "executeAsync", "(", "fn", ",", "--", "repeatTest", ",", "args", ")", "}", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "reject", "(", "error", ")", ")", "}", "/**\n * if we don't retry just return result\n */", "if", "(", "repeatTest", "===", "0", "||", "!", "result", "||", "typeof", "result", ".", "catch", "!==", "'function'", ")", "{", "return", "new", "Promise", "(", "resolve", "=>", "resolve", "(", "result", ")", ")", "}", "/**\n * handle promise response\n */", "return", "result", ".", "catch", "(", "(", "e", ")", "=>", "{", "if", "(", "repeatTest", ")", "{", "return", "executeAsync", "(", "fn", ",", "--", "repeatTest", ",", "args", ")", "}", "e", ".", "stack", "=", "e", ".", "stack", ".", "split", "(", "'\\n'", ")", ".", "filter", "(", "STACKTRACE_FILTER_FN", ")", ".", "join", "(", "'\\n'", ")", "return", "Promise", ".", "reject", "(", "e", ")", "}", ")", "}" ]
execute test or hook asynchronously @param {Function} fn spec or hook method @param {Number} repeatTest number of retries @return {Promise} that gets resolved once test/hook is done or was retried enough
[ "execute", "test", "or", "hook", "asynchronously" ]
8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1
https://github.com/webdriverio/webdriverio/blob/8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1/packages/wdio-sync/src/index.js#L54-L98
1,536
webdriverio/webdriverio
packages/wdio-sync/src/index.js
runSync
function runSync (fn, repeatTest = 0, args = []) { return (resolve, reject) => Fiber(() => executeSync.call(this, fn, repeatTest, args).then(() => resolve(), reject)).run() }
javascript
function runSync (fn, repeatTest = 0, args = []) { return (resolve, reject) => Fiber(() => executeSync.call(this, fn, repeatTest, args).then(() => resolve(), reject)).run() }
[ "function", "runSync", "(", "fn", ",", "repeatTest", "=", "0", ",", "args", "=", "[", "]", ")", "{", "return", "(", "resolve", ",", "reject", ")", "=>", "Fiber", "(", "(", ")", "=>", "executeSync", ".", "call", "(", "this", ",", "fn", ",", "repeatTest", ",", "args", ")", ".", "then", "(", "(", ")", "=>", "resolve", "(", ")", ",", "reject", ")", ")", ".", "run", "(", ")", "}" ]
run hook or spec via executeSync
[ "run", "hook", "or", "spec", "via", "executeSync" ]
8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1
https://github.com/webdriverio/webdriverio/blob/8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1/packages/wdio-sync/src/index.js#L159-L162
1,537
webdriverio/webdriverio
packages/wdio-sync/src/index.js
function (testInterfaceFnNames, before, after, fnName, scope = global) { const origFn = scope[fnName] scope[fnName] = wrapTestFunction(fnName, origFn, testInterfaceFnNames, before, after) /** * support it.skip for the Mocha framework */ if (typeof origFn.skip === 'function') { scope[fnName].skip = origFn.skip } /** * wrap it.only for the Mocha framework */ if (typeof origFn.only === 'function') { const origOnlyFn = origFn.only scope[fnName].only = wrapTestFunction(fnName + '.only', origOnlyFn, testInterfaceFnNames, before, after) } }
javascript
function (testInterfaceFnNames, before, after, fnName, scope = global) { const origFn = scope[fnName] scope[fnName] = wrapTestFunction(fnName, origFn, testInterfaceFnNames, before, after) /** * support it.skip for the Mocha framework */ if (typeof origFn.skip === 'function') { scope[fnName].skip = origFn.skip } /** * wrap it.only for the Mocha framework */ if (typeof origFn.only === 'function') { const origOnlyFn = origFn.only scope[fnName].only = wrapTestFunction(fnName + '.only', origOnlyFn, testInterfaceFnNames, before, after) } }
[ "function", "(", "testInterfaceFnNames", ",", "before", ",", "after", ",", "fnName", ",", "scope", "=", "global", ")", "{", "const", "origFn", "=", "scope", "[", "fnName", "]", "scope", "[", "fnName", "]", "=", "wrapTestFunction", "(", "fnName", ",", "origFn", ",", "testInterfaceFnNames", ",", "before", ",", "after", ")", "/**\n * support it.skip for the Mocha framework\n */", "if", "(", "typeof", "origFn", ".", "skip", "===", "'function'", ")", "{", "scope", "[", "fnName", "]", ".", "skip", "=", "origFn", ".", "skip", "}", "/**\n * wrap it.only for the Mocha framework\n */", "if", "(", "typeof", "origFn", ".", "only", "===", "'function'", ")", "{", "const", "origOnlyFn", "=", "origFn", ".", "only", "scope", "[", "fnName", "]", ".", "only", "=", "wrapTestFunction", "(", "fnName", "+", "'.only'", ",", "origOnlyFn", ",", "testInterfaceFnNames", ",", "before", ",", "after", ")", "}", "}" ]
Wraps global test function like `it` so that commands can run synchronouse The scope parameter is used in the qunit framework since all functions are bound to global.QUnit instead of global @param {String[]} testInterfaceFnNames command that runs specs, e.g. `it`, `it.only` or `fit` @param {Function} before before hook hook @param {Function} after after hook hook @param {String} fnName test interface command to wrap, e.g. `beforeEach` @param {Object} scope the scope to run command from, defaults to global
[ "Wraps", "global", "test", "function", "like", "it", "so", "that", "commands", "can", "run", "synchronouse" ]
8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1
https://github.com/webdriverio/webdriverio/blob/8de7f1a3b12d97282ed4ee2e25e4c3c9a8940ac1/packages/wdio-sync/src/index.js#L209-L227
1,538
heyui/heyui
src/plugins/popper/index.js
getStyleComputedProperty
function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var css = getComputedStyle(element, null); return property ? css[property] : css; }
javascript
function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var css = getComputedStyle(element, null); return property ? css[property] : css; }
[ "function", "getStyleComputedProperty", "(", "element", ",", "property", ")", "{", "if", "(", "element", ".", "nodeType", "!==", "1", ")", "{", "return", "[", "]", ";", "}", "// NOTE: 1 DOM access here", "var", "css", "=", "getComputedStyle", "(", "element", ",", "null", ")", ";", "return", "property", "?", "css", "[", "property", "]", ":", "css", ";", "}" ]
Get CSS computed property of the given element @method @memberof Popper.Utils @argument {Eement} element @argument {String} property
[ "Get", "CSS", "computed", "property", "of", "the", "given", "element" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L95-L102
1,539
heyui/heyui
src/plugins/popper/index.js
getClientRect
function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); }
javascript
function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); }
[ "function", "getClientRect", "(", "offsets", ")", "{", "return", "_extends", "(", "{", "}", ",", "offsets", ",", "{", "right", ":", "offsets", ".", "left", "+", "offsets", ".", "width", ",", "bottom", ":", "offsets", ".", "top", "+", "offsets", ".", "height", "}", ")", ";", "}" ]
Given element offsets, generate an output similar to getBoundingClientRect @method @memberof Popper.Utils @argument {Object} offsets @returns {Object} ClientRect like output
[ "Given", "element", "offsets", "generate", "an", "output", "similar", "to", "getBoundingClientRect" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L432-L437
1,540
heyui/heyui
src/plugins/popper/index.js
getFixedPositionOffsetParent
function getFixedPositionOffsetParent(element) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element || !element.parentElement || isIE()) { return document.documentElement; } var el = element.parentElement; while (el && getStyleComputedProperty(el, 'transform') === 'none') { el = el.parentElement; } return el || document.documentElement; }
javascript
function getFixedPositionOffsetParent(element) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element || !element.parentElement || isIE()) { return document.documentElement; } var el = element.parentElement; while (el && getStyleComputedProperty(el, 'transform') === 'none') { el = el.parentElement; } return el || document.documentElement; }
[ "function", "getFixedPositionOffsetParent", "(", "element", ")", "{", "// This check is needed to avoid errors in case one of the elements isn't defined for any reason", "if", "(", "!", "element", "||", "!", "element", ".", "parentElement", "||", "isIE", "(", ")", ")", "{", "return", "document", ".", "documentElement", ";", "}", "var", "el", "=", "element", ".", "parentElement", ";", "while", "(", "el", "&&", "getStyleComputedProperty", "(", "el", ",", "'transform'", ")", "===", "'none'", ")", "{", "el", "=", "el", ".", "parentElement", ";", "}", "return", "el", "||", "document", ".", "documentElement", ";", "}" ]
Finds the first parent of an element that has a transformed property defined @method @memberof Popper.Utils @argument {Element} element @returns {Element} first transformed parent or documentElement
[ "Finds", "the", "first", "parent", "of", "an", "element", "that", "has", "a", "transformed", "property", "defined" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L595-L605
1,541
heyui/heyui
src/plugins/popper/index.js
find
function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; }
javascript
function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; }
[ "function", "find", "(", "arr", ",", "check", ")", "{", "// use native find if supported", "if", "(", "Array", ".", "prototype", ".", "find", ")", "{", "return", "arr", ".", "find", "(", "check", ")", ";", "}", "// use `filter` to obtain the same behavior of `find`", "return", "arr", ".", "filter", "(", "check", ")", "[", "0", "]", ";", "}" ]
Mimics the `find` method of Array @method @memberof Popper.Utils @argument {Array} arr @argument prop @argument value @returns index or -1
[ "Mimics", "the", "find", "method", "of", "Array" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L838-L846
1,542
heyui/heyui
src/plugins/popper/index.js
findIndex
function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); }
javascript
function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); }
[ "function", "findIndex", "(", "arr", ",", "prop", ",", "value", ")", "{", "// use native findIndex if supported", "if", "(", "Array", ".", "prototype", ".", "findIndex", ")", "{", "return", "arr", ".", "findIndex", "(", "function", "(", "cur", ")", "{", "return", "cur", "[", "prop", "]", "===", "value", ";", "}", ")", ";", "}", "// use `find` + `indexOf` if `findIndex` isn't supported", "var", "match", "=", "find", "(", "arr", ",", "function", "(", "obj", ")", "{", "return", "obj", "[", "prop", "]", "===", "value", ";", "}", ")", ";", "return", "arr", ".", "indexOf", "(", "match", ")", ";", "}" ]
Return the index of the matching object @method @memberof Popper.Utils @argument {Array} arr @argument prop @argument value @returns index or -1
[ "Return", "the", "index", "of", "the", "matching", "object" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L857-L870
1,543
heyui/heyui
src/plugins/popper/index.js
runModifiers
function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier['function']) { // eslint-disable-line dot-notation console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation if (modifier.enabled && isFunction(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; }
javascript
function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier['function']) { // eslint-disable-line dot-notation console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation if (modifier.enabled && isFunction(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; }
[ "function", "runModifiers", "(", "modifiers", ",", "data", ",", "ends", ")", "{", "var", "modifiersToRun", "=", "ends", "===", "undefined", "?", "modifiers", ":", "modifiers", ".", "slice", "(", "0", ",", "findIndex", "(", "modifiers", ",", "'name'", ",", "ends", ")", ")", ";", "modifiersToRun", ".", "forEach", "(", "function", "(", "modifier", ")", "{", "if", "(", "modifier", "[", "'function'", "]", ")", "{", "// eslint-disable-line dot-notation", "console", ".", "warn", "(", "'`modifier.function` is deprecated, use `modifier.fn`!'", ")", ";", "}", "var", "fn", "=", "modifier", "[", "'function'", "]", "||", "modifier", ".", "fn", ";", "// eslint-disable-line dot-notation", "if", "(", "modifier", ".", "enabled", "&&", "isFunction", "(", "fn", ")", ")", "{", "// Add properties to offsets to make them a complete clientRect object", "// we do this before each modifier to make sure the previous one doesn't", "// mess with these values", "data", ".", "offsets", ".", "popper", "=", "getClientRect", "(", "data", ".", "offsets", ".", "popper", ")", ";", "data", ".", "offsets", ".", "reference", "=", "getClientRect", "(", "data", ".", "offsets", ".", "reference", ")", ";", "data", "=", "fn", "(", "data", ",", "modifier", ")", ";", "}", "}", ")", ";", "return", "data", ";", "}" ]
Loop trough the list of modifiers and run them in order, each of them will then edit the data object. @method @memberof Popper.Utils @param {dataObject} data @param {Array} modifiers @param {String} ends - Optional modifier name used as stopper @returns {dataObject}
[ "Loop", "trough", "the", "list", "of", "modifiers", "and", "run", "them", "in", "order", "each", "of", "them", "will", "then", "edit", "the", "data", "object", "." ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L882-L903
1,544
heyui/heyui
src/plugins/popper/index.js
updateModifiers
function updateModifiers() { if (this.state.isDestroyed) { return; } // Deep merge modifiers options let options = this.defaultOptions; this.options.modifiers = {}; const _this = this; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); }
javascript
function updateModifiers() { if (this.state.isDestroyed) { return; } // Deep merge modifiers options let options = this.defaultOptions; this.options.modifiers = {}; const _this = this; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); }
[ "function", "updateModifiers", "(", ")", "{", "if", "(", "this", ".", "state", ".", "isDestroyed", ")", "{", "return", ";", "}", "// Deep merge modifiers options", "let", "options", "=", "this", ".", "defaultOptions", ";", "this", ".", "options", ".", "modifiers", "=", "{", "}", ";", "const", "_this", "=", "this", ";", "Object", ".", "keys", "(", "_extends", "(", "{", "}", ",", "Popper", ".", "Defaults", ".", "modifiers", ",", "options", ".", "modifiers", ")", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "_this", ".", "options", ".", "modifiers", "[", "name", "]", "=", "_extends", "(", "{", "}", ",", "Popper", ".", "Defaults", ".", "modifiers", "[", "name", "]", "||", "{", "}", ",", "options", ".", "modifiers", "?", "options", ".", "modifiers", "[", "name", "]", ":", "{", "}", ")", ";", "}", ")", ";", "// Refactoring modifiers' list (Object => Array)", "this", ".", "modifiers", "=", "Object", ".", "keys", "(", "this", ".", "options", ".", "modifiers", ")", ".", "map", "(", "function", "(", "name", ")", "{", "return", "_extends", "(", "{", "name", ":", "name", "}", ",", "_this", ".", "options", ".", "modifiers", "[", "name", "]", ")", ";", "}", ")", "// sort the modifiers by order", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "order", "-", "b", ".", "order", ";", "}", ")", ";", "// modifiers have the ability to execute arbitrary code when Popper.js get inited", "// such code is executed in the same order of its modifier", "// they could add new properties to their options configuration", "// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!", "this", ".", "modifiers", ".", "forEach", "(", "function", "(", "modifierOptions", ")", "{", "if", "(", "modifierOptions", ".", "enabled", "&&", "isFunction", "(", "modifierOptions", ".", "onLoad", ")", ")", "{", "modifierOptions", ".", "onLoad", "(", "_this", ".", "reference", ",", "_this", ".", "popper", ",", "_this", ".", "options", ",", "modifierOptions", ",", "_this", ".", "state", ")", ";", "}", "}", ")", ";", "}" ]
Updates the options of Popper @method @memberof Popper
[ "Updates", "the", "options", "of", "Popper" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L910-L942
1,545
heyui/heyui
src/plugins/popper/index.js
setupEventListeners
function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; getWindow(reference).addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; }
javascript
function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; getWindow(reference).addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; }
[ "function", "setupEventListeners", "(", "reference", ",", "options", ",", "state", ",", "updateBound", ")", "{", "// Resize event listener on window", "state", ".", "updateBound", "=", "updateBound", ";", "getWindow", "(", "reference", ")", ".", "addEventListener", "(", "'resize'", ",", "state", ".", "updateBound", ",", "{", "passive", ":", "true", "}", ")", ";", "// Scroll event listener on scroll parents", "var", "scrollElement", "=", "getScrollParent", "(", "reference", ")", ";", "attachToScrollParents", "(", "scrollElement", ",", "'scroll'", ",", "state", ".", "updateBound", ",", "state", ".", "scrollParents", ")", ";", "state", ".", "scrollElement", "=", "scrollElement", ";", "state", ".", "eventsEnabled", "=", "true", ";", "return", "state", ";", "}" ]
Setup needed event listeners used to update the popper position @method @memberof Popper.Utils @private
[ "Setup", "needed", "event", "listeners", "used", "to", "update", "the", "popper", "position" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L1089-L1101
1,546
heyui/heyui
src/plugins/popper/index.js
removeEventListeners
function removeEventListeners(reference, state) { // Remove resize event listener on window getWindow(reference).removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; }
javascript
function removeEventListeners(reference, state) { // Remove resize event listener on window getWindow(reference).removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; }
[ "function", "removeEventListeners", "(", "reference", ",", "state", ")", "{", "// Remove resize event listener on window", "getWindow", "(", "reference", ")", ".", "removeEventListener", "(", "'resize'", ",", "state", ".", "updateBound", ")", ";", "// Remove scroll event listener on scroll parents", "state", ".", "scrollParents", ".", "forEach", "(", "function", "(", "target", ")", "{", "target", ".", "removeEventListener", "(", "'scroll'", ",", "state", ".", "updateBound", ")", ";", "}", ")", ";", "// Reset state", "state", ".", "updateBound", "=", "null", ";", "state", ".", "scrollParents", "=", "[", "]", ";", "state", ".", "scrollElement", "=", "null", ";", "state", ".", "eventsEnabled", "=", "false", ";", "return", "state", ";", "}" ]
Remove event listeners used to update the popper position @method @memberof Popper.Utils @private
[ "Remove", "event", "listeners", "used", "to", "update", "the", "popper", "position" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L1121-L1136
1,547
heyui/heyui
src/plugins/popper/index.js
setStyles
function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); }
javascript
function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); }
[ "function", "setStyles", "(", "element", ",", "styles", ")", "{", "Object", ".", "keys", "(", "styles", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "unit", "=", "''", ";", "// add unit if the value is numeric and is one of the following", "if", "(", "[", "'width'", ",", "'height'", ",", "'top'", ",", "'right'", ",", "'bottom'", ",", "'left'", "]", ".", "indexOf", "(", "prop", ")", "!==", "-", "1", "&&", "isNumeric", "(", "styles", "[", "prop", "]", ")", ")", "{", "unit", "=", "'px'", ";", "}", "element", ".", "style", "[", "prop", "]", "=", "styles", "[", "prop", "]", "+", "unit", ";", "}", ")", ";", "}" ]
Set the style to the given popper @method @memberof Popper.Utils @argument {Element} element - Element to apply the style to @argument {Object} styles Object with a list of properties and values which will be applied to the element
[ "Set", "the", "style", "to", "the", "given", "popper" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L1173-L1182
1,548
heyui/heyui
src/plugins/popper/index.js
setAttributes
function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); }
javascript
function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); }
[ "function", "setAttributes", "(", "element", ",", "attributes", ")", "{", "Object", ".", "keys", "(", "attributes", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "value", "=", "attributes", "[", "prop", "]", ";", "if", "(", "value", "!==", "false", ")", "{", "element", ".", "setAttribute", "(", "prop", ",", "attributes", "[", "prop", "]", ")", ";", "}", "else", "{", "element", ".", "removeAttribute", "(", "prop", ")", ";", "}", "}", ")", ";", "}" ]
Set the attributes to the given popper @method @memberof Popper.Utils @argument {Element} element - Element to apply the attributes to @argument {Object} styles Object with a list of properties and values which will be applied to the element
[ "Set", "the", "attributes", "to", "the", "given", "popper" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L1192-L1201
1,549
heyui/heyui
src/plugins/popper/index.js
toValue
function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } }
javascript
function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } }
[ "function", "toValue", "(", "str", ",", "measurement", ",", "popperOffsets", ",", "referenceOffsets", ")", "{", "// separate value from unit", "var", "split", "=", "str", ".", "match", "(", "/", "((?:\\-|\\+)?\\d*\\.?\\d*)(.*)", "/", ")", ";", "var", "value", "=", "+", "split", "[", "1", "]", ";", "var", "unit", "=", "split", "[", "2", "]", ";", "// If it's not a number it's an operator, I guess", "if", "(", "!", "value", ")", "{", "return", "str", ";", "}", "if", "(", "unit", ".", "indexOf", "(", "'%'", ")", "===", "0", ")", "{", "var", "element", "=", "void", "0", ";", "switch", "(", "unit", ")", "{", "case", "'%p'", ":", "element", "=", "popperOffsets", ";", "break", ";", "case", "'%'", ":", "case", "'%r'", ":", "default", ":", "element", "=", "referenceOffsets", ";", "}", "var", "rect", "=", "getClientRect", "(", "element", ")", ";", "return", "rect", "[", "measurement", "]", "/", "100", "*", "value", ";", "}", "else", "if", "(", "unit", "===", "'vh'", "||", "unit", "===", "'vw'", ")", "{", "// if is a vh or vw, we calculate the size based on the viewport", "var", "size", "=", "void", "0", ";", "if", "(", "unit", "===", "'vh'", ")", "{", "size", "=", "Math", ".", "max", "(", "document", ".", "documentElement", ".", "clientHeight", ",", "window", ".", "innerHeight", "||", "0", ")", ";", "}", "else", "{", "size", "=", "Math", ".", "max", "(", "document", ".", "documentElement", ".", "clientWidth", ",", "window", ".", "innerWidth", "||", "0", ")", ";", "}", "return", "size", "/", "100", "*", "value", ";", "}", "else", "{", "// if is an explicit pixel unit, we get rid of the unit and keep the value", "// if is an implicit unit, it's px, and we return just the value", "return", "value", ";", "}", "}" ]
Converts a string containing value + unit into a px value number @function @memberof {modifiers~offset} @private @argument {String} str - Value + unit string @argument {String} measurement - `height` or `width` @argument {Object} popperOffsets @argument {Object} referenceOffsets @returns {Number|String} Value in pixels, or original string if no values were extracted
[ "Converts", "a", "string", "containing", "value", "+", "unit", "into", "a", "px", "value", "number" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L1676-L1715
1,550
heyui/heyui
src/plugins/popper/index.js
Popper
function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimation(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.defaultOptions = options; this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference && reference.jquery ? reference[0] : reference; this.popper = popper && popper.jquery ? popper[0] : popper; this.updateModifiers(); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; }
javascript
function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimation(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.defaultOptions = options; this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference && reference.jquery ? reference[0] : reference; this.popper = popper && popper.jquery ? popper[0] : popper; this.updateModifiers(); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; }
[ "function", "Popper", "(", "reference", ",", "popper", ")", "{", "var", "_this", "=", "this", ";", "var", "options", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "{", "}", ";", "classCallCheck", "(", "this", ",", "Popper", ")", ";", "this", ".", "scheduleUpdate", "=", "function", "(", ")", "{", "return", "requestAnimation", "(", "_this", ".", "update", ")", ";", "}", ";", "// make update() debounced, so that it only runs at most once-per-tick", "this", ".", "update", "=", "debounce", "(", "this", ".", "update", ".", "bind", "(", "this", ")", ")", ";", "// with {} we create a new object with the options inside it", "this", ".", "defaultOptions", "=", "options", ";", "this", ".", "options", "=", "_extends", "(", "{", "}", ",", "Popper", ".", "Defaults", ",", "options", ")", ";", "// init state", "this", ".", "state", "=", "{", "isDestroyed", ":", "false", ",", "isCreated", ":", "false", ",", "scrollParents", ":", "[", "]", "}", ";", "// get reference and popper elements (allow jQuery wrappers)", "this", ".", "reference", "=", "reference", "&&", "reference", ".", "jquery", "?", "reference", "[", "0", "]", ":", "reference", ";", "this", ".", "popper", "=", "popper", "&&", "popper", ".", "jquery", "?", "popper", "[", "0", "]", ":", "popper", ";", "this", ".", "updateModifiers", "(", ")", ";", "// fire the first update to position the popper in the right place", "this", ".", "update", "(", ")", ";", "var", "eventsEnabled", "=", "this", ".", "options", ".", "eventsEnabled", ";", "if", "(", "eventsEnabled", ")", "{", "// setup event listeners, they will take care of update the position in specific situations", "this", ".", "enableEventListeners", "(", ")", ";", "}", "this", ".", "state", ".", "eventsEnabled", "=", "eventsEnabled", ";", "}" ]
Create a new Popper.js instance @class Popper @param {HTMLElement|referenceObject} reference - The reference element used to position the popper @param {HTMLElement} popper - The HTML element used as popper. @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) @return {Object} instance - The generated Popper.js instance
[ "Create", "a", "new", "Popper", ".", "js", "instance" ]
d5405d27d994151b676eb91c12b389316d7f6679
https://github.com/heyui/heyui/blob/d5405d27d994151b676eb91c12b389316d7f6679/src/plugins/popper/index.js#L2433-L2473
1,551
ngrx/platform
projects/ngrx.io/src/app/search/search-worker.js
queryIndex
function queryIndex(query) { try { if (query.length) { var results = index.search(query); if (results.length === 0) { // Add a relaxed search in the title for the first word in the query // E.g. if the search is "ngCont guide" then we search for "ngCont guide titleWords:ngCont*" var titleQuery = 'titleWords:*' + query.split(' ', 1)[0] + '*'; results = index.search(query + ' ' + titleQuery); } // Map the hits into info about each page to be returned as results return results.map(function(hit) { return pages[hit.ref]; }); } } catch(e) { // If the search query cannot be parsed the index throws an error // Log it and recover console.log(e); } return []; }
javascript
function queryIndex(query) { try { if (query.length) { var results = index.search(query); if (results.length === 0) { // Add a relaxed search in the title for the first word in the query // E.g. if the search is "ngCont guide" then we search for "ngCont guide titleWords:ngCont*" var titleQuery = 'titleWords:*' + query.split(' ', 1)[0] + '*'; results = index.search(query + ' ' + titleQuery); } // Map the hits into info about each page to be returned as results return results.map(function(hit) { return pages[hit.ref]; }); } } catch(e) { // If the search query cannot be parsed the index throws an error // Log it and recover console.log(e); } return []; }
[ "function", "queryIndex", "(", "query", ")", "{", "try", "{", "if", "(", "query", ".", "length", ")", "{", "var", "results", "=", "index", ".", "search", "(", "query", ")", ";", "if", "(", "results", ".", "length", "===", "0", ")", "{", "// Add a relaxed search in the title for the first word in the query", "// E.g. if the search is \"ngCont guide\" then we search for \"ngCont guide titleWords:ngCont*\"", "var", "titleQuery", "=", "'titleWords:*'", "+", "query", ".", "split", "(", "' '", ",", "1", ")", "[", "0", "]", "+", "'*'", ";", "results", "=", "index", ".", "search", "(", "query", "+", "' '", "+", "titleQuery", ")", ";", "}", "// Map the hits into info about each page to be returned as results", "return", "results", ".", "map", "(", "function", "(", "hit", ")", "{", "return", "pages", "[", "hit", ".", "ref", "]", ";", "}", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "// If the search query cannot be parsed the index throws an error", "// Log it and recover", "console", ".", "log", "(", "e", ")", ";", "}", "return", "[", "]", ";", "}" ]
Query the index and return the processed results
[ "Query", "the", "index", "and", "return", "the", "processed", "results" ]
eec9cc615440526ddedac04ae0082bfecef13d50
https://github.com/ngrx/platform/blob/eec9cc615440526ddedac04ae0082bfecef13d50/projects/ngrx.io/src/app/search/search-worker.js#L87-L106
1,552
ngrx/platform
projects/ngrx.io/tools/examples/run-example-e2e.js
runE2e
function runE2e() { if (argv.setup) { // Run setup. console.log('runE2e: setup boilerplate'); const installPackagesCommand = `example-use-${argv.local ? 'local' : 'npm'}`; const addBoilerplateCommand = 'boilerplate:add'; shelljs.exec(`yarn ${installPackagesCommand}`, { cwd: AIO_PATH }); shelljs.exec(`yarn ${addBoilerplateCommand}`, { cwd: AIO_PATH }); } const outputFile = path.join(AIO_PATH, './protractor-results.txt'); return Promise.resolve() .then(() => findAndRunE2eTests(argv.filter, outputFile, argv.shard)) .then((status) => { reportStatus(status, outputFile); if (status.failed.length > 0) { return Promise.reject('Some test suites failed'); } }).catch(function (e) { console.log(e); process.exitCode = 1; }); }
javascript
function runE2e() { if (argv.setup) { // Run setup. console.log('runE2e: setup boilerplate'); const installPackagesCommand = `example-use-${argv.local ? 'local' : 'npm'}`; const addBoilerplateCommand = 'boilerplate:add'; shelljs.exec(`yarn ${installPackagesCommand}`, { cwd: AIO_PATH }); shelljs.exec(`yarn ${addBoilerplateCommand}`, { cwd: AIO_PATH }); } const outputFile = path.join(AIO_PATH, './protractor-results.txt'); return Promise.resolve() .then(() => findAndRunE2eTests(argv.filter, outputFile, argv.shard)) .then((status) => { reportStatus(status, outputFile); if (status.failed.length > 0) { return Promise.reject('Some test suites failed'); } }).catch(function (e) { console.log(e); process.exitCode = 1; }); }
[ "function", "runE2e", "(", ")", "{", "if", "(", "argv", ".", "setup", ")", "{", "// Run setup.", "console", ".", "log", "(", "'runE2e: setup boilerplate'", ")", ";", "const", "installPackagesCommand", "=", "`", "${", "argv", ".", "local", "?", "'local'", ":", "'npm'", "}", "`", ";", "const", "addBoilerplateCommand", "=", "'boilerplate:add'", ";", "shelljs", ".", "exec", "(", "`", "${", "installPackagesCommand", "}", "`", ",", "{", "cwd", ":", "AIO_PATH", "}", ")", ";", "shelljs", ".", "exec", "(", "`", "${", "addBoilerplateCommand", "}", "`", ",", "{", "cwd", ":", "AIO_PATH", "}", ")", ";", "}", "const", "outputFile", "=", "path", ".", "join", "(", "AIO_PATH", ",", "'./protractor-results.txt'", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "findAndRunE2eTests", "(", "argv", ".", "filter", ",", "outputFile", ",", "argv", ".", "shard", ")", ")", ".", "then", "(", "(", "status", ")", "=>", "{", "reportStatus", "(", "status", ",", "outputFile", ")", ";", "if", "(", "status", ".", "failed", ".", "length", ">", "0", ")", "{", "return", "Promise", ".", "reject", "(", "'Some test suites failed'", ")", ";", "}", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "console", ".", "log", "(", "e", ")", ";", "process", ".", "exitCode", "=", "1", ";", "}", ")", ";", "}" ]
Run Protractor End-to-End Tests for Doc Samples Flags --filter to filter/select _example app subdir names e.g. --filter=foo // all example apps with 'foo' in their folder names. --setup run yarn install, copy boilerplate and update webdriver e.g. --setup --local to use the locally built Angular packages, rather than versions from npm Must be used in conjunction with --setup as this is when the packages are copied. e.g. --setup --local --shard to shard the specs into groups to allow you to run them in parallel e.g. --shard=0/2 // the even specs: 0, 2, 4, etc e.g. --shard=1/2 // the odd specs: 1, 3, 5, etc e.g. --shard=1/3 // the second of every three specs: 1, 4, 7, etc
[ "Run", "Protractor", "End", "-", "to", "-", "End", "Tests", "for", "Doc", "Samples" ]
eec9cc615440526ddedac04ae0082bfecef13d50
https://github.com/ngrx/platform/blob/eec9cc615440526ddedac04ae0082bfecef13d50/projects/ngrx.io/tools/examples/run-example-e2e.js#L42-L65
1,553
ngrx/platform
projects/ngrx.io/tools/examples/run-example-e2e.js
getE2eSpecsFor
function getE2eSpecsFor(basePath, specFile, filter) { // Only get spec file at the example root. const e2eSpecGlob = `${filter ? `*${filter}*` : '*'}/${specFile}`; return globby(e2eSpecGlob, { cwd: basePath, nodir: true }) .then(paths => paths .filter(file => !IGNORED_EXAMPLES.some(ignored => file.startsWith(ignored))) .map(file => path.join(basePath, file)) ); }
javascript
function getE2eSpecsFor(basePath, specFile, filter) { // Only get spec file at the example root. const e2eSpecGlob = `${filter ? `*${filter}*` : '*'}/${specFile}`; return globby(e2eSpecGlob, { cwd: basePath, nodir: true }) .then(paths => paths .filter(file => !IGNORED_EXAMPLES.some(ignored => file.startsWith(ignored))) .map(file => path.join(basePath, file)) ); }
[ "function", "getE2eSpecsFor", "(", "basePath", ",", "specFile", ",", "filter", ")", "{", "// Only get spec file at the example root.", "const", "e2eSpecGlob", "=", "`", "${", "filter", "?", "`", "${", "filter", "}", "`", ":", "'*'", "}", "${", "specFile", "}", "`", ";", "return", "globby", "(", "e2eSpecGlob", ",", "{", "cwd", ":", "basePath", ",", "nodir", ":", "true", "}", ")", ".", "then", "(", "paths", "=>", "paths", ".", "filter", "(", "file", "=>", "!", "IGNORED_EXAMPLES", ".", "some", "(", "ignored", "=>", "file", ".", "startsWith", "(", "ignored", ")", ")", ")", ".", "map", "(", "file", "=>", "path", ".", "join", "(", "basePath", ",", "file", ")", ")", ")", ";", "}" ]
Find all e2e specs in a given example folder.
[ "Find", "all", "e2e", "specs", "in", "a", "given", "example", "folder", "." ]
eec9cc615440526ddedac04ae0082bfecef13d50
https://github.com/ngrx/platform/blob/eec9cc615440526ddedac04ae0082bfecef13d50/projects/ngrx.io/tools/examples/run-example-e2e.js#L296-L304
1,554
google/material-design-lite
gulpfile.babel.js
watch
function watch() { gulp.watch(['src/**/*.js', '!src/**/README.md'], ['scripts', 'demos', 'components', reload]); gulp.watch(['src/**/*.{scss,css}'], ['styles', 'styles-grid', 'styletemplates', reload]); gulp.watch(['src/**/*.html'], ['pages', reload]); gulp.watch(['src/**/*.{svg,png,jpg}'], ['images', reload]); gulp.watch(['src/**/README.md'], ['pages', reload]); gulp.watch(['templates/**/*'], ['templates', reload]); gulp.watch(['docs/**/*'], ['pages', 'assets', reload]); gulp.watch(['package.json', 'bower.json', 'LICENSE'], ['metadata']); }
javascript
function watch() { gulp.watch(['src/**/*.js', '!src/**/README.md'], ['scripts', 'demos', 'components', reload]); gulp.watch(['src/**/*.{scss,css}'], ['styles', 'styles-grid', 'styletemplates', reload]); gulp.watch(['src/**/*.html'], ['pages', reload]); gulp.watch(['src/**/*.{svg,png,jpg}'], ['images', reload]); gulp.watch(['src/**/README.md'], ['pages', reload]); gulp.watch(['templates/**/*'], ['templates', reload]); gulp.watch(['docs/**/*'], ['pages', 'assets', reload]); gulp.watch(['package.json', 'bower.json', 'LICENSE'], ['metadata']); }
[ "function", "watch", "(", ")", "{", "gulp", ".", "watch", "(", "[", "'src/**/*.js'", ",", "'!src/**/README.md'", "]", ",", "[", "'scripts'", ",", "'demos'", ",", "'components'", ",", "reload", "]", ")", ";", "gulp", ".", "watch", "(", "[", "'src/**/*.{scss,css}'", "]", ",", "[", "'styles'", ",", "'styles-grid'", ",", "'styletemplates'", ",", "reload", "]", ")", ";", "gulp", ".", "watch", "(", "[", "'src/**/*.html'", "]", ",", "[", "'pages'", ",", "reload", "]", ")", ";", "gulp", ".", "watch", "(", "[", "'src/**/*.{svg,png,jpg}'", "]", ",", "[", "'images'", ",", "reload", "]", ")", ";", "gulp", ".", "watch", "(", "[", "'src/**/README.md'", "]", ",", "[", "'pages'", ",", "reload", "]", ")", ";", "gulp", ".", "watch", "(", "[", "'templates/**/*'", "]", ",", "[", "'templates'", ",", "reload", "]", ")", ";", "gulp", ".", "watch", "(", "[", "'docs/**/*'", "]", ",", "[", "'pages'", ",", "'assets'", ",", "reload", "]", ")", ";", "gulp", ".", "watch", "(", "[", "'package.json'", ",", "'bower.json'", ",", "'LICENSE'", "]", ",", "[", "'metadata'", "]", ")", ";", "}" ]
Defines the list of resources to watch for changes.
[ "Defines", "the", "list", "of", "resources", "to", "watch", "for", "changes", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/gulpfile.babel.js#L493-L504
1,555
google/material-design-lite
gulpfile.babel.js
mdlPublish
function mdlPublish(pubScope) { let cacheTtl = null; let src = null; let dest = null; if (pubScope === 'staging') { // Set staging specific vars here. cacheTtl = 0; src = 'dist/*'; dest = bucketStaging; } else if (pubScope === 'prod') { // Set prod specific vars here. cacheTtl = 60; src = 'dist/*'; dest = bucketProd; } else if (pubScope === 'promote') { // Set promote (essentially prod) specific vars here. cacheTtl = 60; src = `${bucketStaging}/*`; dest = bucketProd; } let infoMsg = `Publishing ${pubScope}/${pkg.version} to GCS (${dest})`; if (src) { infoMsg += ` from ${src}`; } console.log(infoMsg); // Build gsutil commands: // The gsutil -h option is used to set metadata headers. // The gsutil -m option requests parallel copies. // The gsutil -R option is used for recursive file copy. const cacheControl = `-h "Cache-Control:public,max-age=${cacheTtl}"`; const gsutilCacheCmd = `gsutil -m setmeta ${cacheControl} ${dest}/**`; const gsutilCpCmd = `gsutil -m cp -r -z html,css,js,svg ${src} ${dest}`; gulp.src('').pipe($.shell([gsutilCpCmd, gsutilCacheCmd])); }
javascript
function mdlPublish(pubScope) { let cacheTtl = null; let src = null; let dest = null; if (pubScope === 'staging') { // Set staging specific vars here. cacheTtl = 0; src = 'dist/*'; dest = bucketStaging; } else if (pubScope === 'prod') { // Set prod specific vars here. cacheTtl = 60; src = 'dist/*'; dest = bucketProd; } else if (pubScope === 'promote') { // Set promote (essentially prod) specific vars here. cacheTtl = 60; src = `${bucketStaging}/*`; dest = bucketProd; } let infoMsg = `Publishing ${pubScope}/${pkg.version} to GCS (${dest})`; if (src) { infoMsg += ` from ${src}`; } console.log(infoMsg); // Build gsutil commands: // The gsutil -h option is used to set metadata headers. // The gsutil -m option requests parallel copies. // The gsutil -R option is used for recursive file copy. const cacheControl = `-h "Cache-Control:public,max-age=${cacheTtl}"`; const gsutilCacheCmd = `gsutil -m setmeta ${cacheControl} ${dest}/**`; const gsutilCpCmd = `gsutil -m cp -r -z html,css,js,svg ${src} ${dest}`; gulp.src('').pipe($.shell([gsutilCpCmd, gsutilCacheCmd])); }
[ "function", "mdlPublish", "(", "pubScope", ")", "{", "let", "cacheTtl", "=", "null", ";", "let", "src", "=", "null", ";", "let", "dest", "=", "null", ";", "if", "(", "pubScope", "===", "'staging'", ")", "{", "// Set staging specific vars here.", "cacheTtl", "=", "0", ";", "src", "=", "'dist/*'", ";", "dest", "=", "bucketStaging", ";", "}", "else", "if", "(", "pubScope", "===", "'prod'", ")", "{", "// Set prod specific vars here.", "cacheTtl", "=", "60", ";", "src", "=", "'dist/*'", ";", "dest", "=", "bucketProd", ";", "}", "else", "if", "(", "pubScope", "===", "'promote'", ")", "{", "// Set promote (essentially prod) specific vars here.", "cacheTtl", "=", "60", ";", "src", "=", "`", "${", "bucketStaging", "}", "`", ";", "dest", "=", "bucketProd", ";", "}", "let", "infoMsg", "=", "`", "${", "pubScope", "}", "${", "pkg", ".", "version", "}", "${", "dest", "}", "`", ";", "if", "(", "src", ")", "{", "infoMsg", "+=", "`", "${", "src", "}", "`", ";", "}", "console", ".", "log", "(", "infoMsg", ")", ";", "// Build gsutil commands:", "// The gsutil -h option is used to set metadata headers.", "// The gsutil -m option requests parallel copies.", "// The gsutil -R option is used for recursive file copy.", "const", "cacheControl", "=", "`", "${", "cacheTtl", "}", "`", ";", "const", "gsutilCacheCmd", "=", "`", "${", "cacheControl", "}", "${", "dest", "}", "`", ";", "const", "gsutilCpCmd", "=", "`", "${", "src", "}", "${", "dest", "}", "`", ";", "gulp", ".", "src", "(", "''", ")", ".", "pipe", "(", "$", ".", "shell", "(", "[", "gsutilCpCmd", ",", "gsutilCacheCmd", "]", ")", ")", ";", "}" ]
Function to publish staging or prod version from local tree, or to promote staging to prod, per passed arg. @param {string} pubScope the scope to publish to.
[ "Function", "to", "publish", "staging", "or", "prod", "version", "from", "local", "tree", "or", "to", "promote", "staging", "to", "prod", "per", "passed", "arg", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/gulpfile.babel.js#L634-L671
1,556
google/material-design-lite
src/mdlComponentHandler.js
findRegisteredClass_
function findRegisteredClass_(name, optReplace) { for (var i = 0; i < registeredComponents_.length; i++) { if (registeredComponents_[i].className === name) { if (typeof optReplace !== 'undefined') { registeredComponents_[i] = optReplace; } return registeredComponents_[i]; } } return false; }
javascript
function findRegisteredClass_(name, optReplace) { for (var i = 0; i < registeredComponents_.length; i++) { if (registeredComponents_[i].className === name) { if (typeof optReplace !== 'undefined') { registeredComponents_[i] = optReplace; } return registeredComponents_[i]; } } return false; }
[ "function", "findRegisteredClass_", "(", "name", ",", "optReplace", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "registeredComponents_", ".", "length", ";", "i", "++", ")", "{", "if", "(", "registeredComponents_", "[", "i", "]", ".", "className", "===", "name", ")", "{", "if", "(", "typeof", "optReplace", "!==", "'undefined'", ")", "{", "registeredComponents_", "[", "i", "]", "=", "optReplace", ";", "}", "return", "registeredComponents_", "[", "i", "]", ";", "}", "}", "return", "false", ";", "}" ]
Searches registered components for a class we are interested in using. Optionally replaces a match with passed object if specified. @param {string} name The name of a class we want to use. @param {componentHandler.ComponentConfig=} optReplace Optional object to replace match with. @return {!Object|boolean} @private
[ "Searches", "registered", "components", "for", "a", "class", "we", "are", "interested", "in", "using", ".", "Optionally", "replaces", "a", "match", "with", "passed", "object", "if", "specified", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L104-L114
1,557
google/material-design-lite
src/mdlComponentHandler.js
createEvent_
function createEvent_(eventType, bubbles, cancelable) { if ('CustomEvent' in window && typeof window.CustomEvent === 'function') { return new CustomEvent(eventType, { bubbles: bubbles, cancelable: cancelable }); } else { var ev = document.createEvent('Events'); ev.initEvent(eventType, bubbles, cancelable); return ev; } }
javascript
function createEvent_(eventType, bubbles, cancelable) { if ('CustomEvent' in window && typeof window.CustomEvent === 'function') { return new CustomEvent(eventType, { bubbles: bubbles, cancelable: cancelable }); } else { var ev = document.createEvent('Events'); ev.initEvent(eventType, bubbles, cancelable); return ev; } }
[ "function", "createEvent_", "(", "eventType", ",", "bubbles", ",", "cancelable", ")", "{", "if", "(", "'CustomEvent'", "in", "window", "&&", "typeof", "window", ".", "CustomEvent", "===", "'function'", ")", "{", "return", "new", "CustomEvent", "(", "eventType", ",", "{", "bubbles", ":", "bubbles", ",", "cancelable", ":", "cancelable", "}", ")", ";", "}", "else", "{", "var", "ev", "=", "document", ".", "createEvent", "(", "'Events'", ")", ";", "ev", ".", "initEvent", "(", "eventType", ",", "bubbles", ",", "cancelable", ")", ";", "return", "ev", ";", "}", "}" ]
Create an event object. @param {string} eventType The type name of the event. @param {boolean} bubbles Whether the event should bubble up the DOM. @param {boolean} cancelable Whether the event can be canceled. @returns {!Event}
[ "Create", "an", "event", "object", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L151-L162
1,558
google/material-design-lite
src/mdlComponentHandler.js
upgradeDomInternal
function upgradeDomInternal(optJsClass, optCssClass) { if (typeof optJsClass === 'undefined' && typeof optCssClass === 'undefined') { for (var i = 0; i < registeredComponents_.length; i++) { upgradeDomInternal(registeredComponents_[i].className, registeredComponents_[i].cssClass); } } else { var jsClass = /** @type {string} */ (optJsClass); if (typeof optCssClass === 'undefined') { var registeredClass = findRegisteredClass_(jsClass); if (registeredClass) { optCssClass = registeredClass.cssClass; } } var elements = document.querySelectorAll('.' + optCssClass); for (var n = 0; n < elements.length; n++) { upgradeElementInternal(elements[n], jsClass); } } }
javascript
function upgradeDomInternal(optJsClass, optCssClass) { if (typeof optJsClass === 'undefined' && typeof optCssClass === 'undefined') { for (var i = 0; i < registeredComponents_.length; i++) { upgradeDomInternal(registeredComponents_[i].className, registeredComponents_[i].cssClass); } } else { var jsClass = /** @type {string} */ (optJsClass); if (typeof optCssClass === 'undefined') { var registeredClass = findRegisteredClass_(jsClass); if (registeredClass) { optCssClass = registeredClass.cssClass; } } var elements = document.querySelectorAll('.' + optCssClass); for (var n = 0; n < elements.length; n++) { upgradeElementInternal(elements[n], jsClass); } } }
[ "function", "upgradeDomInternal", "(", "optJsClass", ",", "optCssClass", ")", "{", "if", "(", "typeof", "optJsClass", "===", "'undefined'", "&&", "typeof", "optCssClass", "===", "'undefined'", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "registeredComponents_", ".", "length", ";", "i", "++", ")", "{", "upgradeDomInternal", "(", "registeredComponents_", "[", "i", "]", ".", "className", ",", "registeredComponents_", "[", "i", "]", ".", "cssClass", ")", ";", "}", "}", "else", "{", "var", "jsClass", "=", "/** @type {string} */", "(", "optJsClass", ")", ";", "if", "(", "typeof", "optCssClass", "===", "'undefined'", ")", "{", "var", "registeredClass", "=", "findRegisteredClass_", "(", "jsClass", ")", ";", "if", "(", "registeredClass", ")", "{", "optCssClass", "=", "registeredClass", ".", "cssClass", ";", "}", "}", "var", "elements", "=", "document", ".", "querySelectorAll", "(", "'.'", "+", "optCssClass", ")", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "elements", ".", "length", ";", "n", "++", ")", "{", "upgradeElementInternal", "(", "elements", "[", "n", "]", ",", "jsClass", ")", ";", "}", "}", "}" ]
Searches existing DOM for elements of our component type and upgrades them if they have not already been upgraded. @param {string=} optJsClass the programatic name of the element class we need to create a new instance of. @param {string=} optCssClass the name of the CSS class elements of this type will have.
[ "Searches", "existing", "DOM", "for", "elements", "of", "our", "component", "type", "and", "upgrades", "them", "if", "they", "have", "not", "already", "been", "upgraded", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L173-L194
1,559
google/material-design-lite
src/mdlComponentHandler.js
upgradeElementsInternal
function upgradeElementsInternal(elements) { if (!Array.isArray(elements)) { if (elements instanceof Element) { elements = [elements]; } else { elements = Array.prototype.slice.call(elements); } } for (var i = 0, n = elements.length, element; i < n; i++) { element = elements[i]; if (element instanceof HTMLElement) { upgradeElementInternal(element); if (element.children.length > 0) { upgradeElementsInternal(element.children); } } } }
javascript
function upgradeElementsInternal(elements) { if (!Array.isArray(elements)) { if (elements instanceof Element) { elements = [elements]; } else { elements = Array.prototype.slice.call(elements); } } for (var i = 0, n = elements.length, element; i < n; i++) { element = elements[i]; if (element instanceof HTMLElement) { upgradeElementInternal(element); if (element.children.length > 0) { upgradeElementsInternal(element.children); } } } }
[ "function", "upgradeElementsInternal", "(", "elements", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "elements", ")", ")", "{", "if", "(", "elements", "instanceof", "Element", ")", "{", "elements", "=", "[", "elements", "]", ";", "}", "else", "{", "elements", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "elements", ")", ";", "}", "}", "for", "(", "var", "i", "=", "0", ",", "n", "=", "elements", ".", "length", ",", "element", ";", "i", "<", "n", ";", "i", "++", ")", "{", "element", "=", "elements", "[", "i", "]", ";", "if", "(", "element", "instanceof", "HTMLElement", ")", "{", "upgradeElementInternal", "(", "element", ")", ";", "if", "(", "element", ".", "children", ".", "length", ">", "0", ")", "{", "upgradeElementsInternal", "(", "element", ".", "children", ")", ";", "}", "}", "}", "}" ]
Upgrades a specific list of elements rather than all in the DOM. @param {!Element|!Array<!Element>|!NodeList|!HTMLCollection} elements The elements we wish to upgrade.
[ "Upgrades", "a", "specific", "list", "of", "elements", "rather", "than", "all", "in", "the", "DOM", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L268-L285
1,560
google/material-design-lite
src/mdlComponentHandler.js
registerInternal
function registerInternal(config) { // In order to support both Closure-compiled and uncompiled code accessing // this method, we need to allow for both the dot and array syntax for // property access. You'll therefore see the `foo.bar || foo['bar']` // pattern repeated across this method. var widgetMissing = (typeof config.widget === 'undefined' && typeof config['widget'] === 'undefined'); var widget = true; if (!widgetMissing) { widget = config.widget || config['widget']; } var newConfig = /** @type {componentHandler.ComponentConfig} */ ({ classConstructor: config.constructor || config['constructor'], className: config.classAsString || config['classAsString'], cssClass: config.cssClass || config['cssClass'], widget: widget, callbacks: [] }); registeredComponents_.forEach(function(item) { if (item.cssClass === newConfig.cssClass) { throw new Error('The provided cssClass has already been registered: ' + item.cssClass); } if (item.className === newConfig.className) { throw new Error('The provided className has already been registered'); } }); if (config.constructor.prototype .hasOwnProperty(componentConfigProperty_)) { throw new Error( 'MDL component classes must not have ' + componentConfigProperty_ + ' defined as a property.'); } var found = findRegisteredClass_(config.classAsString, newConfig); if (!found) { registeredComponents_.push(newConfig); } }
javascript
function registerInternal(config) { // In order to support both Closure-compiled and uncompiled code accessing // this method, we need to allow for both the dot and array syntax for // property access. You'll therefore see the `foo.bar || foo['bar']` // pattern repeated across this method. var widgetMissing = (typeof config.widget === 'undefined' && typeof config['widget'] === 'undefined'); var widget = true; if (!widgetMissing) { widget = config.widget || config['widget']; } var newConfig = /** @type {componentHandler.ComponentConfig} */ ({ classConstructor: config.constructor || config['constructor'], className: config.classAsString || config['classAsString'], cssClass: config.cssClass || config['cssClass'], widget: widget, callbacks: [] }); registeredComponents_.forEach(function(item) { if (item.cssClass === newConfig.cssClass) { throw new Error('The provided cssClass has already been registered: ' + item.cssClass); } if (item.className === newConfig.className) { throw new Error('The provided className has already been registered'); } }); if (config.constructor.prototype .hasOwnProperty(componentConfigProperty_)) { throw new Error( 'MDL component classes must not have ' + componentConfigProperty_ + ' defined as a property.'); } var found = findRegisteredClass_(config.classAsString, newConfig); if (!found) { registeredComponents_.push(newConfig); } }
[ "function", "registerInternal", "(", "config", ")", "{", "// In order to support both Closure-compiled and uncompiled code accessing", "// this method, we need to allow for both the dot and array syntax for", "// property access. You'll therefore see the `foo.bar || foo['bar']`", "// pattern repeated across this method.", "var", "widgetMissing", "=", "(", "typeof", "config", ".", "widget", "===", "'undefined'", "&&", "typeof", "config", "[", "'widget'", "]", "===", "'undefined'", ")", ";", "var", "widget", "=", "true", ";", "if", "(", "!", "widgetMissing", ")", "{", "widget", "=", "config", ".", "widget", "||", "config", "[", "'widget'", "]", ";", "}", "var", "newConfig", "=", "/** @type {componentHandler.ComponentConfig} */", "(", "{", "classConstructor", ":", "config", ".", "constructor", "||", "config", "[", "'constructor'", "]", ",", "className", ":", "config", ".", "classAsString", "||", "config", "[", "'classAsString'", "]", ",", "cssClass", ":", "config", ".", "cssClass", "||", "config", "[", "'cssClass'", "]", ",", "widget", ":", "widget", ",", "callbacks", ":", "[", "]", "}", ")", ";", "registeredComponents_", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "item", ".", "cssClass", "===", "newConfig", ".", "cssClass", ")", "{", "throw", "new", "Error", "(", "'The provided cssClass has already been registered: '", "+", "item", ".", "cssClass", ")", ";", "}", "if", "(", "item", ".", "className", "===", "newConfig", ".", "className", ")", "{", "throw", "new", "Error", "(", "'The provided className has already been registered'", ")", ";", "}", "}", ")", ";", "if", "(", "config", ".", "constructor", ".", "prototype", ".", "hasOwnProperty", "(", "componentConfigProperty_", ")", ")", "{", "throw", "new", "Error", "(", "'MDL component classes must not have '", "+", "componentConfigProperty_", "+", "' defined as a property.'", ")", ";", "}", "var", "found", "=", "findRegisteredClass_", "(", "config", ".", "classAsString", ",", "newConfig", ")", ";", "if", "(", "!", "found", ")", "{", "registeredComponents_", ".", "push", "(", "newConfig", ")", ";", "}", "}" ]
Registers a class for future use and attempts to upgrade existing DOM. @param {componentHandler.ComponentConfigPublic} config
[ "Registers", "a", "class", "for", "future", "use", "and", "attempts", "to", "upgrade", "existing", "DOM", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L292-L334
1,561
google/material-design-lite
src/mdlComponentHandler.js
registerUpgradedCallbackInternal
function registerUpgradedCallbackInternal(jsClass, callback) { var regClass = findRegisteredClass_(jsClass); if (regClass) { regClass.callbacks.push(callback); } }
javascript
function registerUpgradedCallbackInternal(jsClass, callback) { var regClass = findRegisteredClass_(jsClass); if (regClass) { regClass.callbacks.push(callback); } }
[ "function", "registerUpgradedCallbackInternal", "(", "jsClass", ",", "callback", ")", "{", "var", "regClass", "=", "findRegisteredClass_", "(", "jsClass", ")", ";", "if", "(", "regClass", ")", "{", "regClass", ".", "callbacks", ".", "push", "(", "callback", ")", ";", "}", "}" ]
Allows user to be alerted to any upgrades that are performed for a given component type @param {string} jsClass The class name of the MDL component we wish to hook into for any upgrades performed. @param {function(!HTMLElement)} callback The function to call upon an upgrade. This function should expect 1 parameter - the HTMLElement which got upgraded.
[ "Allows", "user", "to", "be", "alerted", "to", "any", "upgrades", "that", "are", "performed", "for", "a", "given", "component", "type" ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L346-L351
1,562
google/material-design-lite
src/mdlComponentHandler.js
upgradeAllRegisteredInternal
function upgradeAllRegisteredInternal() { for (var n = 0; n < registeredComponents_.length; n++) { upgradeDomInternal(registeredComponents_[n].className); } }
javascript
function upgradeAllRegisteredInternal() { for (var n = 0; n < registeredComponents_.length; n++) { upgradeDomInternal(registeredComponents_[n].className); } }
[ "function", "upgradeAllRegisteredInternal", "(", ")", "{", "for", "(", "var", "n", "=", "0", ";", "n", "<", "registeredComponents_", ".", "length", ";", "n", "++", ")", "{", "upgradeDomInternal", "(", "registeredComponents_", "[", "n", "]", ".", "className", ")", ";", "}", "}" ]
Upgrades all registered components found in the current DOM. This is automatically called on window load.
[ "Upgrades", "all", "registered", "components", "found", "in", "the", "current", "DOM", ".", "This", "is", "automatically", "called", "on", "window", "load", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L357-L361
1,563
google/material-design-lite
src/mdlComponentHandler.js
downgradeNodesInternal
function downgradeNodesInternal(nodes) { /** * Auxiliary function to downgrade a single node. * @param {!Node} node the node to be downgraded */ var downgradeNode = function(node) { createdComponents_.filter(function(item) { return item.element_ === node; }).forEach(deconstructComponentInternal); }; if (nodes instanceof Array || nodes instanceof NodeList) { for (var n = 0; n < nodes.length; n++) { downgradeNode(nodes[n]); } } else if (nodes instanceof Node) { downgradeNode(nodes); } else { throw new Error('Invalid argument provided to downgrade MDL nodes.'); } }
javascript
function downgradeNodesInternal(nodes) { /** * Auxiliary function to downgrade a single node. * @param {!Node} node the node to be downgraded */ var downgradeNode = function(node) { createdComponents_.filter(function(item) { return item.element_ === node; }).forEach(deconstructComponentInternal); }; if (nodes instanceof Array || nodes instanceof NodeList) { for (var n = 0; n < nodes.length; n++) { downgradeNode(nodes[n]); } } else if (nodes instanceof Node) { downgradeNode(nodes); } else { throw new Error('Invalid argument provided to downgrade MDL nodes.'); } }
[ "function", "downgradeNodesInternal", "(", "nodes", ")", "{", "/**\n * Auxiliary function to downgrade a single node.\n * @param {!Node} node the node to be downgraded\n */", "var", "downgradeNode", "=", "function", "(", "node", ")", "{", "createdComponents_", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", ".", "element_", "===", "node", ";", "}", ")", ".", "forEach", "(", "deconstructComponentInternal", ")", ";", "}", ";", "if", "(", "nodes", "instanceof", "Array", "||", "nodes", "instanceof", "NodeList", ")", "{", "for", "(", "var", "n", "=", "0", ";", "n", "<", "nodes", ".", "length", ";", "n", "++", ")", "{", "downgradeNode", "(", "nodes", "[", "n", "]", ")", ";", "}", "}", "else", "if", "(", "nodes", "instanceof", "Node", ")", "{", "downgradeNode", "(", "nodes", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid argument provided to downgrade MDL nodes.'", ")", ";", "}", "}" ]
Downgrade either a given node, an array of nodes, or a NodeList. @param {!Node|!Array<!Node>|!NodeList} nodes
[ "Downgrade", "either", "a", "given", "node", "an", "array", "of", "nodes", "or", "a", "NodeList", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/src/mdlComponentHandler.js#L390-L409
1,564
google/material-design-lite
docs/_assets/components.js
MaterialComponentsNav
function MaterialComponentsNav() { 'use strict'; this.element_ = document.querySelector('.mdl-js-components'); if (this.element_) { this.componentLinks = this.element_.querySelectorAll('.mdl-components__link'); this.activeLink = null; this.activePage = null; this.init(); } }
javascript
function MaterialComponentsNav() { 'use strict'; this.element_ = document.querySelector('.mdl-js-components'); if (this.element_) { this.componentLinks = this.element_.querySelectorAll('.mdl-components__link'); this.activeLink = null; this.activePage = null; this.init(); } }
[ "function", "MaterialComponentsNav", "(", ")", "{", "'use strict'", ";", "this", ".", "element_", "=", "document", ".", "querySelector", "(", "'.mdl-js-components'", ")", ";", "if", "(", "this", ".", "element_", ")", "{", "this", ".", "componentLinks", "=", "this", ".", "element_", ".", "querySelectorAll", "(", "'.mdl-components__link'", ")", ";", "this", ".", "activeLink", "=", "null", ";", "this", ".", "activePage", "=", "null", ";", "this", ".", "init", "(", ")", ";", "}", "}" ]
Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Copyright", "2015", "Google", "Inc", ".", "All", "Rights", "Reserved", "." ]
60f441a22ed98ed2c03f6179adf460d888bf459f
https://github.com/google/material-design-lite/blob/60f441a22ed98ed2c03f6179adf460d888bf459f/docs/_assets/components.js#L17-L28
1,565
aframevr/aframe
src/components/scene/pool.js
function () { var el; el = document.createElement('a-entity'); el.play = this.wrapPlay(el.play); el.setAttribute('mixin', this.data.mixin); el.object3D.visible = false; el.pause(); this.container.appendChild(el); this.availableEls.push(el); }
javascript
function () { var el; el = document.createElement('a-entity'); el.play = this.wrapPlay(el.play); el.setAttribute('mixin', this.data.mixin); el.object3D.visible = false; el.pause(); this.container.appendChild(el); this.availableEls.push(el); }
[ "function", "(", ")", "{", "var", "el", ";", "el", "=", "document", ".", "createElement", "(", "'a-entity'", ")", ";", "el", ".", "play", "=", "this", ".", "wrapPlay", "(", "el", ".", "play", ")", ";", "el", ".", "setAttribute", "(", "'mixin'", ",", "this", ".", "data", ".", "mixin", ")", ";", "el", ".", "object3D", ".", "visible", "=", "false", ";", "el", ".", "pause", "(", ")", ";", "this", ".", "container", ".", "appendChild", "(", "el", ")", ";", "this", ".", "availableEls", ".", "push", "(", "el", ")", ";", "}" ]
Add a new entity to the list of available entities.
[ "Add", "a", "new", "entity", "to", "the", "list", "of", "available", "entities", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/pool.js#L57-L66
1,566
aframevr/aframe
src/components/scene/pool.js
function () { var el; if (this.availableEls.length === 0) { if (this.data.dynamic === false) { warn('Requested entity from empty pool: ' + this.attrName); return; } else { warn('Requested entity from empty pool. This pool is dynamic and will resize ' + 'automatically. You might want to increase its initial size: ' + this.attrName); } this.createEntity(); } el = this.availableEls.shift(); this.usedEls.push(el); el.object3D.visible = true; return el; }
javascript
function () { var el; if (this.availableEls.length === 0) { if (this.data.dynamic === false) { warn('Requested entity from empty pool: ' + this.attrName); return; } else { warn('Requested entity from empty pool. This pool is dynamic and will resize ' + 'automatically. You might want to increase its initial size: ' + this.attrName); } this.createEntity(); } el = this.availableEls.shift(); this.usedEls.push(el); el.object3D.visible = true; return el; }
[ "function", "(", ")", "{", "var", "el", ";", "if", "(", "this", ".", "availableEls", ".", "length", "===", "0", ")", "{", "if", "(", "this", ".", "data", ".", "dynamic", "===", "false", ")", "{", "warn", "(", "'Requested entity from empty pool: '", "+", "this", ".", "attrName", ")", ";", "return", ";", "}", "else", "{", "warn", "(", "'Requested entity from empty pool. This pool is dynamic and will resize '", "+", "'automatically. You might want to increase its initial size: '", "+", "this", ".", "attrName", ")", ";", "}", "this", ".", "createEntity", "(", ")", ";", "}", "el", "=", "this", ".", "availableEls", ".", "shift", "(", ")", ";", "this", ".", "usedEls", ".", "push", "(", "el", ")", ";", "el", ".", "object3D", ".", "visible", "=", "true", ";", "return", "el", ";", "}" ]
Used to request one of the available entities of the pool.
[ "Used", "to", "request", "one", "of", "the", "available", "entities", "of", "the", "pool", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/pool.js#L83-L99
1,567
aframevr/aframe
src/components/scene/pool.js
function (el) { var index = this.usedEls.indexOf(el); if (index === -1) { warn('The returned entity was not previously pooled from ' + this.attrName); return; } this.usedEls.splice(index, 1); this.availableEls.push(el); el.object3D.visible = false; el.pause(); return el; }
javascript
function (el) { var index = this.usedEls.indexOf(el); if (index === -1) { warn('The returned entity was not previously pooled from ' + this.attrName); return; } this.usedEls.splice(index, 1); this.availableEls.push(el); el.object3D.visible = false; el.pause(); return el; }
[ "function", "(", "el", ")", "{", "var", "index", "=", "this", ".", "usedEls", ".", "indexOf", "(", "el", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "warn", "(", "'The returned entity was not previously pooled from '", "+", "this", ".", "attrName", ")", ";", "return", ";", "}", "this", ".", "usedEls", ".", "splice", "(", "index", ",", "1", ")", ";", "this", ".", "availableEls", ".", "push", "(", "el", ")", ";", "el", ".", "object3D", ".", "visible", "=", "false", ";", "el", ".", "pause", "(", ")", ";", "return", "el", ";", "}" ]
Used to return a used entity to the pool.
[ "Used", "to", "return", "a", "used", "entity", "to", "the", "pool", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/scene/pool.js#L104-L115
1,568
aframevr/aframe
src/core/a-entity.js
isComponentMixedIn
function isComponentMixedIn (name, mixinEls) { var i; var inMixin = false; for (i = 0; i < mixinEls.length; ++i) { inMixin = mixinEls[i].hasAttribute(name); if (inMixin) { break; } } return inMixin; }
javascript
function isComponentMixedIn (name, mixinEls) { var i; var inMixin = false; for (i = 0; i < mixinEls.length; ++i) { inMixin = mixinEls[i].hasAttribute(name); if (inMixin) { break; } } return inMixin; }
[ "function", "isComponentMixedIn", "(", "name", ",", "mixinEls", ")", "{", "var", "i", ";", "var", "inMixin", "=", "false", ";", "for", "(", "i", "=", "0", ";", "i", "<", "mixinEls", ".", "length", ";", "++", "i", ")", "{", "inMixin", "=", "mixinEls", "[", "i", "]", ".", "hasAttribute", "(", "name", ")", ";", "if", "(", "inMixin", ")", "{", "break", ";", "}", "}", "return", "inMixin", ";", "}" ]
Check if any mixins contains a component. @param {string} name - Component name. @param {array} mixinEls - Array of <a-mixin>s.
[ "Check", "if", "any", "mixins", "contains", "a", "component", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-entity.js#L883-L891
1,569
aframevr/aframe
src/core/a-entity.js
mergeComponentData
function mergeComponentData (attrValue, extraData) { // Extra data not defined, just return attrValue. if (!extraData) { return attrValue; } // Merge multi-property data. if (extraData.constructor === Object) { return utils.extend(extraData, utils.styleParser.parse(attrValue || {})); } // Return data, precendence to the defined value. return attrValue || extraData; }
javascript
function mergeComponentData (attrValue, extraData) { // Extra data not defined, just return attrValue. if (!extraData) { return attrValue; } // Merge multi-property data. if (extraData.constructor === Object) { return utils.extend(extraData, utils.styleParser.parse(attrValue || {})); } // Return data, precendence to the defined value. return attrValue || extraData; }
[ "function", "mergeComponentData", "(", "attrValue", ",", "extraData", ")", "{", "// Extra data not defined, just return attrValue.", "if", "(", "!", "extraData", ")", "{", "return", "attrValue", ";", "}", "// Merge multi-property data.", "if", "(", "extraData", ".", "constructor", "===", "Object", ")", "{", "return", "utils", ".", "extend", "(", "extraData", ",", "utils", ".", "styleParser", ".", "parse", "(", "attrValue", "||", "{", "}", ")", ")", ";", "}", "// Return data, precendence to the defined value.", "return", "attrValue", "||", "extraData", ";", "}" ]
Given entity defined value, merge in extra data if necessary. Handle both single and multi-property components. @param {string} attrValue - Entity data. @param extraData - Entity data from another source to merge in.
[ "Given", "entity", "defined", "value", "merge", "in", "extra", "data", "if", "necessary", ".", "Handle", "both", "single", "and", "multi", "-", "property", "components", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/a-entity.js#L900-L911
1,570
aframevr/aframe
src/core/component.js
function (value, silent) { var schema = this.schema; if (this.isSingleProperty) { return parseProperty(value, schema); } return parseProperties(styleParser.parse(value), schema, true, this.name, silent); }
javascript
function (value, silent) { var schema = this.schema; if (this.isSingleProperty) { return parseProperty(value, schema); } return parseProperties(styleParser.parse(value), schema, true, this.name, silent); }
[ "function", "(", "value", ",", "silent", ")", "{", "var", "schema", "=", "this", ".", "schema", ";", "if", "(", "this", ".", "isSingleProperty", ")", "{", "return", "parseProperty", "(", "value", ",", "schema", ")", ";", "}", "return", "parseProperties", "(", "styleParser", ".", "parse", "(", "value", ")", ",", "schema", ",", "true", ",", "this", ".", "name", ",", "silent", ")", ";", "}" ]
Parses each property based on property type. If component is single-property, then parses the single property value. @param {string} value - HTML attribute value. @param {boolean} silent - Suppress warning messages. @returns {object} Component data.
[ "Parses", "each", "property", "based", "on", "property", "type", ".", "If", "component", "is", "single", "-", "property", "then", "parses", "the", "single", "property", "value", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L157-L161
1,571
aframevr/aframe
src/core/component.js
function (data) { var schema = this.schema; if (typeof data === 'string') { return data; } if (this.isSingleProperty) { return stringifyProperty(data, schema); } data = stringifyProperties(data, schema); return styleParser.stringify(data); }
javascript
function (data) { var schema = this.schema; if (typeof data === 'string') { return data; } if (this.isSingleProperty) { return stringifyProperty(data, schema); } data = stringifyProperties(data, schema); return styleParser.stringify(data); }
[ "function", "(", "data", ")", "{", "var", "schema", "=", "this", ".", "schema", ";", "if", "(", "typeof", "data", "===", "'string'", ")", "{", "return", "data", ";", "}", "if", "(", "this", ".", "isSingleProperty", ")", "{", "return", "stringifyProperty", "(", "data", ",", "schema", ")", ";", "}", "data", "=", "stringifyProperties", "(", "data", ",", "schema", ")", ";", "return", "styleParser", ".", "stringify", "(", "data", ")", ";", "}" ]
Stringify properties if necessary. Only called from `Entity.setAttribute` for properties whose parsers accept a non-string value (e.g., selector, vec3 property types). @param {object} data - Complete component data. @returns {string}
[ "Stringify", "properties", "if", "necessary", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L172-L178
1,572
aframevr/aframe
src/core/component.js
function (value, clobber) { var newAttrValue; var tempObject; var property; if (value === undefined) { return; } // If null value is the new attribute value, make the attribute value falsy. if (value === null) { if (this.isObjectBased && this.attrValue) { this.objectPool.recycle(this.attrValue); } this.attrValue = undefined; return; } if (value instanceof Object && !(value instanceof window.HTMLElement)) { // If value is an object, copy it to our pooled newAttrValue object to use to update // the attrValue. tempObject = this.objectPool.use(); newAttrValue = utils.extend(tempObject, value); } else { newAttrValue = this.parseAttrValueForCache(value); } // Merge new data with previous `attrValue` if updating and not clobbering. if (this.isObjectBased && !clobber && this.attrValue) { for (property in this.attrValue) { if (newAttrValue[property] === undefined) { newAttrValue[property] = this.attrValue[property]; } } } // Update attrValue. if (this.isObjectBased && !this.attrValue) { this.attrValue = this.objectPool.use(); } utils.objectPool.clearObject(this.attrValue); this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased); utils.objectPool.clearObject(tempObject); }
javascript
function (value, clobber) { var newAttrValue; var tempObject; var property; if (value === undefined) { return; } // If null value is the new attribute value, make the attribute value falsy. if (value === null) { if (this.isObjectBased && this.attrValue) { this.objectPool.recycle(this.attrValue); } this.attrValue = undefined; return; } if (value instanceof Object && !(value instanceof window.HTMLElement)) { // If value is an object, copy it to our pooled newAttrValue object to use to update // the attrValue. tempObject = this.objectPool.use(); newAttrValue = utils.extend(tempObject, value); } else { newAttrValue = this.parseAttrValueForCache(value); } // Merge new data with previous `attrValue` if updating and not clobbering. if (this.isObjectBased && !clobber && this.attrValue) { for (property in this.attrValue) { if (newAttrValue[property] === undefined) { newAttrValue[property] = this.attrValue[property]; } } } // Update attrValue. if (this.isObjectBased && !this.attrValue) { this.attrValue = this.objectPool.use(); } utils.objectPool.clearObject(this.attrValue); this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased); utils.objectPool.clearObject(tempObject); }
[ "function", "(", "value", ",", "clobber", ")", "{", "var", "newAttrValue", ";", "var", "tempObject", ";", "var", "property", ";", "if", "(", "value", "===", "undefined", ")", "{", "return", ";", "}", "// If null value is the new attribute value, make the attribute value falsy.", "if", "(", "value", "===", "null", ")", "{", "if", "(", "this", ".", "isObjectBased", "&&", "this", ".", "attrValue", ")", "{", "this", ".", "objectPool", ".", "recycle", "(", "this", ".", "attrValue", ")", ";", "}", "this", ".", "attrValue", "=", "undefined", ";", "return", ";", "}", "if", "(", "value", "instanceof", "Object", "&&", "!", "(", "value", "instanceof", "window", ".", "HTMLElement", ")", ")", "{", "// If value is an object, copy it to our pooled newAttrValue object to use to update", "// the attrValue.", "tempObject", "=", "this", ".", "objectPool", ".", "use", "(", ")", ";", "newAttrValue", "=", "utils", ".", "extend", "(", "tempObject", ",", "value", ")", ";", "}", "else", "{", "newAttrValue", "=", "this", ".", "parseAttrValueForCache", "(", "value", ")", ";", "}", "// Merge new data with previous `attrValue` if updating and not clobbering.", "if", "(", "this", ".", "isObjectBased", "&&", "!", "clobber", "&&", "this", ".", "attrValue", ")", "{", "for", "(", "property", "in", "this", ".", "attrValue", ")", "{", "if", "(", "newAttrValue", "[", "property", "]", "===", "undefined", ")", "{", "newAttrValue", "[", "property", "]", "=", "this", ".", "attrValue", "[", "property", "]", ";", "}", "}", "}", "// Update attrValue.", "if", "(", "this", ".", "isObjectBased", "&&", "!", "this", ".", "attrValue", ")", "{", "this", ".", "attrValue", "=", "this", ".", "objectPool", ".", "use", "(", ")", ";", "}", "utils", ".", "objectPool", ".", "clearObject", "(", "this", ".", "attrValue", ")", ";", "this", ".", "attrValue", "=", "extendProperties", "(", "this", ".", "attrValue", ",", "newAttrValue", ",", "this", ".", "isObjectBased", ")", ";", "utils", ".", "objectPool", ".", "clearObject", "(", "tempObject", ")", ";", "}" ]
Update the cache of the pre-parsed attribute value. @param {string} value - New data. @param {boolean } clobber - Whether to wipe out and replace previous data.
[ "Update", "the", "cache", "of", "the", "pre", "-", "parsed", "attribute", "value", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L186-L227
1,573
aframevr/aframe
src/core/component.js
function (value) { var parsedValue; if (typeof value !== 'string') { return value; } if (this.isSingleProperty) { parsedValue = this.schema.parse(value); /** * To avoid bogus double parsings. Cached values will be parsed when building * component data. For instance when parsing a src id to its url, we want to cache * original string and not the parsed one (#monster -> models/monster.dae) * so when building data we parse the expected value. */ if (typeof parsedValue === 'string') { parsedValue = value; } } else { // Parse using the style parser to avoid double parsing of individual properties. utils.objectPool.clearObject(this.parsingAttrValue); parsedValue = styleParser.parse(value, this.parsingAttrValue); } return parsedValue; }
javascript
function (value) { var parsedValue; if (typeof value !== 'string') { return value; } if (this.isSingleProperty) { parsedValue = this.schema.parse(value); /** * To avoid bogus double parsings. Cached values will be parsed when building * component data. For instance when parsing a src id to its url, we want to cache * original string and not the parsed one (#monster -> models/monster.dae) * so when building data we parse the expected value. */ if (typeof parsedValue === 'string') { parsedValue = value; } } else { // Parse using the style parser to avoid double parsing of individual properties. utils.objectPool.clearObject(this.parsingAttrValue); parsedValue = styleParser.parse(value, this.parsingAttrValue); } return parsedValue; }
[ "function", "(", "value", ")", "{", "var", "parsedValue", ";", "if", "(", "typeof", "value", "!==", "'string'", ")", "{", "return", "value", ";", "}", "if", "(", "this", ".", "isSingleProperty", ")", "{", "parsedValue", "=", "this", ".", "schema", ".", "parse", "(", "value", ")", ";", "/**\n * To avoid bogus double parsings. Cached values will be parsed when building\n * component data. For instance when parsing a src id to its url, we want to cache\n * original string and not the parsed one (#monster -> models/monster.dae)\n * so when building data we parse the expected value.\n */", "if", "(", "typeof", "parsedValue", "===", "'string'", ")", "{", "parsedValue", "=", "value", ";", "}", "}", "else", "{", "// Parse using the style parser to avoid double parsing of individual properties.", "utils", ".", "objectPool", ".", "clearObject", "(", "this", ".", "parsingAttrValue", ")", ";", "parsedValue", "=", "styleParser", ".", "parse", "(", "value", ",", "this", ".", "parsingAttrValue", ")", ";", "}", "return", "parsedValue", ";", "}" ]
Given an HTML attribute value parses the string based on the component schema. To avoid double parsings of strings into strings we store the original instead of the parsed one @param {string} value - HTML attribute value
[ "Given", "an", "HTML", "attribute", "value", "parses", "the", "string", "based", "on", "the", "component", "schema", ".", "To", "avoid", "double", "parsings", "of", "strings", "into", "strings", "we", "store", "the", "original", "instead", "of", "the", "parsed", "one" ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L236-L254
1,574
aframevr/aframe
src/core/component.js
function (isDefault) { var attrValue = isDefault ? this.data : this.attrValue; if (attrValue === null || attrValue === undefined) { return; } window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName, this.stringify(attrValue)); }
javascript
function (isDefault) { var attrValue = isDefault ? this.data : this.attrValue; if (attrValue === null || attrValue === undefined) { return; } window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName, this.stringify(attrValue)); }
[ "function", "(", "isDefault", ")", "{", "var", "attrValue", "=", "isDefault", "?", "this", ".", "data", ":", "this", ".", "attrValue", ";", "if", "(", "attrValue", "===", "null", "||", "attrValue", "===", "undefined", ")", "{", "return", ";", "}", "window", ".", "HTMLElement", ".", "prototype", ".", "setAttribute", ".", "call", "(", "this", ".", "el", ",", "this", ".", "attrName", ",", "this", ".", "stringify", "(", "attrValue", ")", ")", ";", "}" ]
Write cached attribute data to the entity DOM element. @param {boolean} isDefault - Whether component is a default component. Always flush for default components.
[ "Write", "cached", "attribute", "data", "to", "the", "entity", "DOM", "element", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L262-L267
1,575
aframevr/aframe
src/core/component.js
function () { var hasComponentChanged; // Store the previous old data before we calculate the new oldData. if (this.previousOldData instanceof Object) { utils.objectPool.clearObject(this.previousOldData); } if (this.isObjectBased) { copyData(this.previousOldData, this.oldData); } else { this.previousOldData = this.oldData; } hasComponentChanged = !utils.deepEqual(this.oldData, this.data); // Don't update if properties haven't changed. // Always update rotation, position, scale. if (!this.isPositionRotationScale && !hasComponentChanged) { return; } // Store current data as previous data for future updates. // Reuse `this.oldData` object to try not to allocate another one. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); } this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased); // Update component with the previous old data. this.update(this.previousOldData); this.throttledEmitComponentChanged(); }
javascript
function () { var hasComponentChanged; // Store the previous old data before we calculate the new oldData. if (this.previousOldData instanceof Object) { utils.objectPool.clearObject(this.previousOldData); } if (this.isObjectBased) { copyData(this.previousOldData, this.oldData); } else { this.previousOldData = this.oldData; } hasComponentChanged = !utils.deepEqual(this.oldData, this.data); // Don't update if properties haven't changed. // Always update rotation, position, scale. if (!this.isPositionRotationScale && !hasComponentChanged) { return; } // Store current data as previous data for future updates. // Reuse `this.oldData` object to try not to allocate another one. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); } this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased); // Update component with the previous old data. this.update(this.previousOldData); this.throttledEmitComponentChanged(); }
[ "function", "(", ")", "{", "var", "hasComponentChanged", ";", "// Store the previous old data before we calculate the new oldData.", "if", "(", "this", ".", "previousOldData", "instanceof", "Object", ")", "{", "utils", ".", "objectPool", ".", "clearObject", "(", "this", ".", "previousOldData", ")", ";", "}", "if", "(", "this", ".", "isObjectBased", ")", "{", "copyData", "(", "this", ".", "previousOldData", ",", "this", ".", "oldData", ")", ";", "}", "else", "{", "this", ".", "previousOldData", "=", "this", ".", "oldData", ";", "}", "hasComponentChanged", "=", "!", "utils", ".", "deepEqual", "(", "this", ".", "oldData", ",", "this", ".", "data", ")", ";", "// Don't update if properties haven't changed.", "// Always update rotation, position, scale.", "if", "(", "!", "this", ".", "isPositionRotationScale", "&&", "!", "hasComponentChanged", ")", "{", "return", ";", "}", "// Store current data as previous data for future updates.", "// Reuse `this.oldData` object to try not to allocate another one.", "if", "(", "this", ".", "oldData", "instanceof", "Object", ")", "{", "utils", ".", "objectPool", ".", "clearObject", "(", "this", ".", "oldData", ")", ";", "}", "this", ".", "oldData", "=", "extendProperties", "(", "this", ".", "oldData", ",", "this", ".", "data", ",", "this", ".", "isObjectBased", ")", ";", "// Update component with the previous old data.", "this", ".", "update", "(", "this", ".", "previousOldData", ")", ";", "this", ".", "throttledEmitComponentChanged", "(", ")", ";", "}" ]
Check if component should fire update and fire update lifecycle handler.
[ "Check", "if", "component", "should", "fire", "update", "and", "fire", "update", "lifecycle", "handler", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L392-L420
1,576
aframevr/aframe
src/core/component.js
function (propertyName) { if (this.isObjectBased) { if (!(propertyName in this.attrValue)) { return; } delete this.attrValue[propertyName]; this.data[propertyName] = this.schema[propertyName].default; } else { this.attrValue = this.schema.default; this.data = this.schema.default; } this.updateProperties(this.attrValue); }
javascript
function (propertyName) { if (this.isObjectBased) { if (!(propertyName in this.attrValue)) { return; } delete this.attrValue[propertyName]; this.data[propertyName] = this.schema[propertyName].default; } else { this.attrValue = this.schema.default; this.data = this.schema.default; } this.updateProperties(this.attrValue); }
[ "function", "(", "propertyName", ")", "{", "if", "(", "this", ".", "isObjectBased", ")", "{", "if", "(", "!", "(", "propertyName", "in", "this", ".", "attrValue", ")", ")", "{", "return", ";", "}", "delete", "this", ".", "attrValue", "[", "propertyName", "]", ";", "this", ".", "data", "[", "propertyName", "]", "=", "this", ".", "schema", "[", "propertyName", "]", ".", "default", ";", "}", "else", "{", "this", ".", "attrValue", "=", "this", ".", "schema", ".", "default", ";", "this", ".", "data", "=", "this", ".", "schema", ".", "default", ";", "}", "this", ".", "updateProperties", "(", "this", ".", "attrValue", ")", ";", "}" ]
Reset value of a property to the property's default value. If single-prop component, reset value to component's default value. @param {string} propertyName - Name of property to reset.
[ "Reset", "value", "of", "a", "property", "to", "the", "property", "s", "default", "value", ".", "If", "single", "-", "prop", "component", "reset", "value", "to", "component", "s", "default", "value", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L433-L443
1,577
aframevr/aframe
src/core/component.js
function (schemaAddon) { var extendedSchema; // Clone base schema. extendedSchema = utils.extend({}, components[this.name].schema); // Extend base schema with new schema chunk. utils.extend(extendedSchema, schemaAddon); this.schema = processSchema(extendedSchema); this.el.emit('schemachanged', this.evtDetail); }
javascript
function (schemaAddon) { var extendedSchema; // Clone base schema. extendedSchema = utils.extend({}, components[this.name].schema); // Extend base schema with new schema chunk. utils.extend(extendedSchema, schemaAddon); this.schema = processSchema(extendedSchema); this.el.emit('schemachanged', this.evtDetail); }
[ "function", "(", "schemaAddon", ")", "{", "var", "extendedSchema", ";", "// Clone base schema.", "extendedSchema", "=", "utils", ".", "extend", "(", "{", "}", ",", "components", "[", "this", ".", "name", "]", ".", "schema", ")", ";", "// Extend base schema with new schema chunk.", "utils", ".", "extend", "(", "extendedSchema", ",", "schemaAddon", ")", ";", "this", ".", "schema", "=", "processSchema", "(", "extendedSchema", ")", ";", "this", ".", "el", ".", "emit", "(", "'schemachanged'", ",", "this", ".", "evtDetail", ")", ";", "}" ]
Extend schema of component given a partial schema. Some components might want to mutate their schema based on certain properties. e.g., Material component changes its schema based on `shader` to account for different uniforms @param {object} schemaAddon - Schema chunk that extend base schema.
[ "Extend", "schema", "of", "component", "given", "a", "partial", "schema", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L454-L462
1,578
aframevr/aframe
src/core/component.js
function (newData, clobber, silent) { var componentDefined; var data; var defaultValue; var key; var mixinData; var nextData = this.nextData; var schema = this.schema; var i; var mixinEls = this.el.mixinEls; var previousData; // Whether component has a defined value. For arrays, treat empty as not defined. componentDefined = newData && newData.constructor === Array ? newData.length : newData !== undefined && newData !== null; if (this.isObjectBased) { utils.objectPool.clearObject(nextData); } // 1. Gather default values (lowest precendence). if (this.isSingleProperty) { if (this.isObjectBased) { // If object-based single-prop, then copy over the data to our pooled object. data = copyData(nextData, schema.default); } else { // If is plain single-prop, copy by value the default. data = isObjectOrArray(schema.default) ? utils.clone(schema.default) : schema.default; } } else { // Preserve previously set properties if clobber not enabled. previousData = !clobber && this.attrValue; // Clone default value if object so components don't share object data = previousData instanceof Object ? copyData(nextData, previousData) : nextData; // Apply defaults. for (key in schema) { defaultValue = schema[key].default; if (data[key] !== undefined) { continue; } // Clone default value if object so components don't share object data[key] = isObjectOrArray(defaultValue) ? utils.clone(defaultValue) : defaultValue; } } // 2. Gather mixin values. for (i = 0; i < mixinEls.length; i++) { mixinData = mixinEls[i].getAttribute(this.attrName); if (!mixinData) { continue; } data = extendProperties(data, mixinData, this.isObjectBased); } // 3. Gather attribute values (highest precendence). if (componentDefined) { if (this.isSingleProperty) { // If object-based, copy the value to not modify the original. if (isObject(newData)) { copyData(this.parsingAttrValue, newData); return parseProperty(this.parsingAttrValue, schema); } return parseProperty(newData, schema); } data = extendProperties(data, newData, this.isObjectBased); } else { // Parse and coerce using the schema. if (this.isSingleProperty) { return parseProperty(data, schema); } } return parseProperties(data, schema, undefined, this.name, silent); }
javascript
function (newData, clobber, silent) { var componentDefined; var data; var defaultValue; var key; var mixinData; var nextData = this.nextData; var schema = this.schema; var i; var mixinEls = this.el.mixinEls; var previousData; // Whether component has a defined value. For arrays, treat empty as not defined. componentDefined = newData && newData.constructor === Array ? newData.length : newData !== undefined && newData !== null; if (this.isObjectBased) { utils.objectPool.clearObject(nextData); } // 1. Gather default values (lowest precendence). if (this.isSingleProperty) { if (this.isObjectBased) { // If object-based single-prop, then copy over the data to our pooled object. data = copyData(nextData, schema.default); } else { // If is plain single-prop, copy by value the default. data = isObjectOrArray(schema.default) ? utils.clone(schema.default) : schema.default; } } else { // Preserve previously set properties if clobber not enabled. previousData = !clobber && this.attrValue; // Clone default value if object so components don't share object data = previousData instanceof Object ? copyData(nextData, previousData) : nextData; // Apply defaults. for (key in schema) { defaultValue = schema[key].default; if (data[key] !== undefined) { continue; } // Clone default value if object so components don't share object data[key] = isObjectOrArray(defaultValue) ? utils.clone(defaultValue) : defaultValue; } } // 2. Gather mixin values. for (i = 0; i < mixinEls.length; i++) { mixinData = mixinEls[i].getAttribute(this.attrName); if (!mixinData) { continue; } data = extendProperties(data, mixinData, this.isObjectBased); } // 3. Gather attribute values (highest precendence). if (componentDefined) { if (this.isSingleProperty) { // If object-based, copy the value to not modify the original. if (isObject(newData)) { copyData(this.parsingAttrValue, newData); return parseProperty(this.parsingAttrValue, schema); } return parseProperty(newData, schema); } data = extendProperties(data, newData, this.isObjectBased); } else { // Parse and coerce using the schema. if (this.isSingleProperty) { return parseProperty(data, schema); } } return parseProperties(data, schema, undefined, this.name, silent); }
[ "function", "(", "newData", ",", "clobber", ",", "silent", ")", "{", "var", "componentDefined", ";", "var", "data", ";", "var", "defaultValue", ";", "var", "key", ";", "var", "mixinData", ";", "var", "nextData", "=", "this", ".", "nextData", ";", "var", "schema", "=", "this", ".", "schema", ";", "var", "i", ";", "var", "mixinEls", "=", "this", ".", "el", ".", "mixinEls", ";", "var", "previousData", ";", "// Whether component has a defined value. For arrays, treat empty as not defined.", "componentDefined", "=", "newData", "&&", "newData", ".", "constructor", "===", "Array", "?", "newData", ".", "length", ":", "newData", "!==", "undefined", "&&", "newData", "!==", "null", ";", "if", "(", "this", ".", "isObjectBased", ")", "{", "utils", ".", "objectPool", ".", "clearObject", "(", "nextData", ")", ";", "}", "// 1. Gather default values (lowest precendence).", "if", "(", "this", ".", "isSingleProperty", ")", "{", "if", "(", "this", ".", "isObjectBased", ")", "{", "// If object-based single-prop, then copy over the data to our pooled object.", "data", "=", "copyData", "(", "nextData", ",", "schema", ".", "default", ")", ";", "}", "else", "{", "// If is plain single-prop, copy by value the default.", "data", "=", "isObjectOrArray", "(", "schema", ".", "default", ")", "?", "utils", ".", "clone", "(", "schema", ".", "default", ")", ":", "schema", ".", "default", ";", "}", "}", "else", "{", "// Preserve previously set properties if clobber not enabled.", "previousData", "=", "!", "clobber", "&&", "this", ".", "attrValue", ";", "// Clone default value if object so components don't share object", "data", "=", "previousData", "instanceof", "Object", "?", "copyData", "(", "nextData", ",", "previousData", ")", ":", "nextData", ";", "// Apply defaults.", "for", "(", "key", "in", "schema", ")", "{", "defaultValue", "=", "schema", "[", "key", "]", ".", "default", ";", "if", "(", "data", "[", "key", "]", "!==", "undefined", ")", "{", "continue", ";", "}", "// Clone default value if object so components don't share object", "data", "[", "key", "]", "=", "isObjectOrArray", "(", "defaultValue", ")", "?", "utils", ".", "clone", "(", "defaultValue", ")", ":", "defaultValue", ";", "}", "}", "// 2. Gather mixin values.", "for", "(", "i", "=", "0", ";", "i", "<", "mixinEls", ".", "length", ";", "i", "++", ")", "{", "mixinData", "=", "mixinEls", "[", "i", "]", ".", "getAttribute", "(", "this", ".", "attrName", ")", ";", "if", "(", "!", "mixinData", ")", "{", "continue", ";", "}", "data", "=", "extendProperties", "(", "data", ",", "mixinData", ",", "this", ".", "isObjectBased", ")", ";", "}", "// 3. Gather attribute values (highest precendence).", "if", "(", "componentDefined", ")", "{", "if", "(", "this", ".", "isSingleProperty", ")", "{", "// If object-based, copy the value to not modify the original.", "if", "(", "isObject", "(", "newData", ")", ")", "{", "copyData", "(", "this", ".", "parsingAttrValue", ",", "newData", ")", ";", "return", "parseProperty", "(", "this", ".", "parsingAttrValue", ",", "schema", ")", ";", "}", "return", "parseProperty", "(", "newData", ",", "schema", ")", ";", "}", "data", "=", "extendProperties", "(", "data", ",", "newData", ",", "this", ".", "isObjectBased", ")", ";", "}", "else", "{", "// Parse and coerce using the schema.", "if", "(", "this", ".", "isSingleProperty", ")", "{", "return", "parseProperty", "(", "data", ",", "schema", ")", ";", "}", "}", "return", "parseProperties", "(", "data", ",", "schema", ",", "undefined", ",", "this", ".", "name", ",", "silent", ")", ";", "}" ]
Build component data from the current state of the entity.data. Precedence: 1. Defaults data 2. Mixin data. 3. Attribute data. Finally coerce the data to the types of the defaults. @param {object} newData - Element new data. @param {boolean} clobber - The previous data is completely replaced by the new one. @param {boolean} silent - Suppress warning messages. @return {object} The component data
[ "Build", "component", "data", "from", "the", "current", "state", "of", "the", "entity", ".", "data", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L479-L553
1,579
aframevr/aframe
src/core/component.js
function () { this.objectPool.recycle(this.attrValue); this.objectPool.recycle(this.oldData); this.objectPool.recycle(this.parsingAttrValue); this.attrValue = this.oldData = this.parsingAttrValue = undefined; }
javascript
function () { this.objectPool.recycle(this.attrValue); this.objectPool.recycle(this.oldData); this.objectPool.recycle(this.parsingAttrValue); this.attrValue = this.oldData = this.parsingAttrValue = undefined; }
[ "function", "(", ")", "{", "this", ".", "objectPool", ".", "recycle", "(", "this", ".", "attrValue", ")", ";", "this", ".", "objectPool", ".", "recycle", "(", "this", ".", "oldData", ")", ";", "this", ".", "objectPool", ".", "recycle", "(", "this", ".", "parsingAttrValue", ")", ";", "this", ".", "attrValue", "=", "this", ".", "oldData", "=", "this", ".", "parsingAttrValue", "=", "undefined", ";", "}" ]
Release and free memory.
[ "Release", "and", "free", "memory", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L580-L585
1,580
aframevr/aframe
src/core/component.js
copyData
function copyData (dest, sourceData) { var parsedProperty; var key; for (key in sourceData) { if (sourceData[key] === undefined) { continue; } parsedProperty = sourceData[key]; dest[key] = isObjectOrArray(parsedProperty) ? utils.clone(parsedProperty) : parsedProperty; } return dest; }
javascript
function copyData (dest, sourceData) { var parsedProperty; var key; for (key in sourceData) { if (sourceData[key] === undefined) { continue; } parsedProperty = sourceData[key]; dest[key] = isObjectOrArray(parsedProperty) ? utils.clone(parsedProperty) : parsedProperty; } return dest; }
[ "function", "copyData", "(", "dest", ",", "sourceData", ")", "{", "var", "parsedProperty", ";", "var", "key", ";", "for", "(", "key", "in", "sourceData", ")", "{", "if", "(", "sourceData", "[", "key", "]", "===", "undefined", ")", "{", "continue", ";", "}", "parsedProperty", "=", "sourceData", "[", "key", "]", ";", "dest", "[", "key", "]", "=", "isObjectOrArray", "(", "parsedProperty", ")", "?", "utils", ".", "clone", "(", "parsedProperty", ")", ":", "parsedProperty", ";", "}", "return", "dest", ";", "}" ]
Clone component data. Clone only the properties that are plain objects while keeping a reference for the rest. @param data - Component data to clone. @returns Cloned data.
[ "Clone", "component", "data", ".", "Clone", "only", "the", "properties", "that", "are", "plain", "objects", "while", "keeping", "a", "reference", "for", "the", "rest", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L711-L722
1,581
aframevr/aframe
src/core/component.js
extendProperties
function extendProperties (dest, source, isObjectBased) { var key; if (isObjectBased && source.constructor === Object) { for (key in source) { if (source[key] === undefined) { continue; } if (source[key] && source[key].constructor === Object) { dest[key] = utils.clone(source[key]); } else { dest[key] = source[key]; } } return dest; } return source; }
javascript
function extendProperties (dest, source, isObjectBased) { var key; if (isObjectBased && source.constructor === Object) { for (key in source) { if (source[key] === undefined) { continue; } if (source[key] && source[key].constructor === Object) { dest[key] = utils.clone(source[key]); } else { dest[key] = source[key]; } } return dest; } return source; }
[ "function", "extendProperties", "(", "dest", ",", "source", ",", "isObjectBased", ")", "{", "var", "key", ";", "if", "(", "isObjectBased", "&&", "source", ".", "constructor", "===", "Object", ")", "{", "for", "(", "key", "in", "source", ")", "{", "if", "(", "source", "[", "key", "]", "===", "undefined", ")", "{", "continue", ";", "}", "if", "(", "source", "[", "key", "]", "&&", "source", "[", "key", "]", ".", "constructor", "===", "Object", ")", "{", "dest", "[", "key", "]", "=", "utils", ".", "clone", "(", "source", "[", "key", "]", ")", ";", "}", "else", "{", "dest", "[", "key", "]", "=", "source", "[", "key", "]", ";", "}", "}", "return", "dest", ";", "}", "return", "source", ";", "}" ]
Object extending with checking for single-property schema. @param dest - Destination object or value. @param source - Source object or value @param {boolean} isObjectBased - Whether values are objects. @returns Overridden object or value.
[ "Object", "extending", "with", "checking", "for", "single", "-", "property", "schema", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L732-L746
1,582
aframevr/aframe
src/core/component.js
wrapPause
function wrapPause (pauseMethod) { return function pause () { var sceneEl = this.el.sceneEl; if (!this.isPlaying) { return; } pauseMethod.call(this); this.isPlaying = false; this.eventsDetach(); // Remove tick behavior. if (!hasBehavior(this)) { return; } sceneEl.removeBehavior(this); }; }
javascript
function wrapPause (pauseMethod) { return function pause () { var sceneEl = this.el.sceneEl; if (!this.isPlaying) { return; } pauseMethod.call(this); this.isPlaying = false; this.eventsDetach(); // Remove tick behavior. if (!hasBehavior(this)) { return; } sceneEl.removeBehavior(this); }; }
[ "function", "wrapPause", "(", "pauseMethod", ")", "{", "return", "function", "pause", "(", ")", "{", "var", "sceneEl", "=", "this", ".", "el", ".", "sceneEl", ";", "if", "(", "!", "this", ".", "isPlaying", ")", "{", "return", ";", "}", "pauseMethod", ".", "call", "(", "this", ")", ";", "this", ".", "isPlaying", "=", "false", ";", "this", ".", "eventsDetach", "(", ")", ";", "// Remove tick behavior.", "if", "(", "!", "hasBehavior", "(", "this", ")", ")", "{", "return", ";", "}", "sceneEl", ".", "removeBehavior", "(", "this", ")", ";", "}", ";", "}" ]
Wrapper for defined pause method. Pause component by removing tick behavior and calling user's pause method. @param pauseMethod {function}
[ "Wrapper", "for", "defined", "pause", "method", ".", "Pause", "component", "by", "removing", "tick", "behavior", "and", "calling", "user", "s", "pause", "method", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L761-L772
1,583
aframevr/aframe
src/core/component.js
wrapPlay
function wrapPlay (playMethod) { return function play () { var sceneEl = this.el.sceneEl; var shouldPlay = this.el.isPlaying && !this.isPlaying; if (!this.initialized || !shouldPlay) { return; } playMethod.call(this); this.isPlaying = true; this.eventsAttach(); // Add tick behavior. if (!hasBehavior(this)) { return; } sceneEl.addBehavior(this); }; }
javascript
function wrapPlay (playMethod) { return function play () { var sceneEl = this.el.sceneEl; var shouldPlay = this.el.isPlaying && !this.isPlaying; if (!this.initialized || !shouldPlay) { return; } playMethod.call(this); this.isPlaying = true; this.eventsAttach(); // Add tick behavior. if (!hasBehavior(this)) { return; } sceneEl.addBehavior(this); }; }
[ "function", "wrapPlay", "(", "playMethod", ")", "{", "return", "function", "play", "(", ")", "{", "var", "sceneEl", "=", "this", ".", "el", ".", "sceneEl", ";", "var", "shouldPlay", "=", "this", ".", "el", ".", "isPlaying", "&&", "!", "this", ".", "isPlaying", ";", "if", "(", "!", "this", ".", "initialized", "||", "!", "shouldPlay", ")", "{", "return", ";", "}", "playMethod", ".", "call", "(", "this", ")", ";", "this", ".", "isPlaying", "=", "true", ";", "this", ".", "eventsAttach", "(", ")", ";", "// Add tick behavior.", "if", "(", "!", "hasBehavior", "(", "this", ")", ")", "{", "return", ";", "}", "sceneEl", ".", "addBehavior", "(", "this", ")", ";", "}", ";", "}" ]
Wrapper for defined play method. Play component by adding tick behavior and calling user's play method. @param playMethod {function}
[ "Wrapper", "for", "defined", "play", "method", ".", "Play", "component", "by", "adding", "tick", "behavior", "and", "calling", "user", "s", "play", "method", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/component.js#L780-L792
1,584
aframevr/aframe
src/systems/geometry.js
function (data) { var cache = this.cache; var cachedGeometry; var hash; // Skip all caching logic. if (data.skipCache) { return createGeometry(data); } // Try to retrieve from cache first. hash = this.hash(data); cachedGeometry = cache[hash]; incrementCacheCount(this.cacheCount, hash); if (cachedGeometry) { return cachedGeometry; } // Create geometry. cachedGeometry = createGeometry(data); // Cache and return geometry. cache[hash] = cachedGeometry; return cachedGeometry; }
javascript
function (data) { var cache = this.cache; var cachedGeometry; var hash; // Skip all caching logic. if (data.skipCache) { return createGeometry(data); } // Try to retrieve from cache first. hash = this.hash(data); cachedGeometry = cache[hash]; incrementCacheCount(this.cacheCount, hash); if (cachedGeometry) { return cachedGeometry; } // Create geometry. cachedGeometry = createGeometry(data); // Cache and return geometry. cache[hash] = cachedGeometry; return cachedGeometry; }
[ "function", "(", "data", ")", "{", "var", "cache", "=", "this", ".", "cache", ";", "var", "cachedGeometry", ";", "var", "hash", ";", "// Skip all caching logic.", "if", "(", "data", ".", "skipCache", ")", "{", "return", "createGeometry", "(", "data", ")", ";", "}", "// Try to retrieve from cache first.", "hash", "=", "this", ".", "hash", "(", "data", ")", ";", "cachedGeometry", "=", "cache", "[", "hash", "]", ";", "incrementCacheCount", "(", "this", ".", "cacheCount", ",", "hash", ")", ";", "if", "(", "cachedGeometry", ")", "{", "return", "cachedGeometry", ";", "}", "// Create geometry.", "cachedGeometry", "=", "createGeometry", "(", "data", ")", ";", "// Cache and return geometry.", "cache", "[", "hash", "]", "=", "cachedGeometry", ";", "return", "cachedGeometry", ";", "}" ]
Attempt to retrieve from cache. @returns {Object|null} A geometry if it exists, else null.
[ "Attempt", "to", "retrieve", "from", "cache", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/geometry.js#L32-L53
1,585
aframevr/aframe
src/systems/geometry.js
function (data) { var cache = this.cache; var cacheCount = this.cacheCount; var geometry; var hash; if (data.skipCache) { return; } hash = this.hash(data); if (!cache[hash]) { return; } decrementCacheCount(cacheCount, hash); // Another entity is still using this geometry. No need to do anything. if (cacheCount[hash] > 0) { return; } // No more entities are using this geometry. Dispose. geometry = cache[hash]; geometry.dispose(); delete cache[hash]; delete cacheCount[hash]; }
javascript
function (data) { var cache = this.cache; var cacheCount = this.cacheCount; var geometry; var hash; if (data.skipCache) { return; } hash = this.hash(data); if (!cache[hash]) { return; } decrementCacheCount(cacheCount, hash); // Another entity is still using this geometry. No need to do anything. if (cacheCount[hash] > 0) { return; } // No more entities are using this geometry. Dispose. geometry = cache[hash]; geometry.dispose(); delete cache[hash]; delete cacheCount[hash]; }
[ "function", "(", "data", ")", "{", "var", "cache", "=", "this", ".", "cache", ";", "var", "cacheCount", "=", "this", ".", "cacheCount", ";", "var", "geometry", ";", "var", "hash", ";", "if", "(", "data", ".", "skipCache", ")", "{", "return", ";", "}", "hash", "=", "this", ".", "hash", "(", "data", ")", ";", "if", "(", "!", "cache", "[", "hash", "]", ")", "{", "return", ";", "}", "decrementCacheCount", "(", "cacheCount", ",", "hash", ")", ";", "// Another entity is still using this geometry. No need to do anything.", "if", "(", "cacheCount", "[", "hash", "]", ">", "0", ")", "{", "return", ";", "}", "// No more entities are using this geometry. Dispose.", "geometry", "=", "cache", "[", "hash", "]", ";", "geometry", ".", "dispose", "(", ")", ";", "delete", "cache", "[", "hash", "]", ";", "delete", "cacheCount", "[", "hash", "]", ";", "}" ]
Let system know that an entity is no longer using a geometry.
[ "Let", "system", "know", "that", "an", "entity", "is", "no", "longer", "using", "a", "geometry", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/geometry.js#L58-L80
1,586
aframevr/aframe
src/systems/geometry.js
createGeometry
function createGeometry (data) { var geometryType = data.primitive; var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry; var geometryInstance = new GeometryClass(); if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); } geometryInstance.init(data); return toBufferGeometry(geometryInstance.geometry, data.buffer); }
javascript
function createGeometry (data) { var geometryType = data.primitive; var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry; var geometryInstance = new GeometryClass(); if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); } geometryInstance.init(data); return toBufferGeometry(geometryInstance.geometry, data.buffer); }
[ "function", "createGeometry", "(", "data", ")", "{", "var", "geometryType", "=", "data", ".", "primitive", ";", "var", "GeometryClass", "=", "geometries", "[", "geometryType", "]", "&&", "geometries", "[", "geometryType", "]", ".", "Geometry", ";", "var", "geometryInstance", "=", "new", "GeometryClass", "(", ")", ";", "if", "(", "!", "GeometryClass", ")", "{", "throw", "new", "Error", "(", "'Unknown geometry `'", "+", "geometryType", "+", "'`'", ")", ";", "}", "geometryInstance", ".", "init", "(", "data", ")", ";", "return", "toBufferGeometry", "(", "geometryInstance", ".", "geometry", ",", "data", ".", "buffer", ")", ";", "}" ]
Create geometry using component data. @param {object} data - Component data. @returns {object} Geometry.
[ "Create", "geometry", "using", "component", "data", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/geometry.js#L98-L107
1,587
aframevr/aframe
src/systems/geometry.js
incrementCacheCount
function incrementCacheCount (cacheCount, hash) { cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1; }
javascript
function incrementCacheCount (cacheCount, hash) { cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1; }
[ "function", "incrementCacheCount", "(", "cacheCount", ",", "hash", ")", "{", "cacheCount", "[", "hash", "]", "=", "cacheCount", "[", "hash", "]", "===", "undefined", "?", "1", ":", "cacheCount", "[", "hash", "]", "+", "1", ";", "}" ]
Increase count of entity using a geometry.
[ "Increase", "count", "of", "entity", "using", "a", "geometry", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/geometry.js#L119-L121
1,588
aframevr/aframe
src/systems/geometry.js
toBufferGeometry
function toBufferGeometry (geometry, doBuffer) { var bufferGeometry; if (!doBuffer) { return geometry; } bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry); bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}}; geometry.dispose(); // Dispose no longer needed non-buffer geometry. return bufferGeometry; }
javascript
function toBufferGeometry (geometry, doBuffer) { var bufferGeometry; if (!doBuffer) { return geometry; } bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry); bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}}; geometry.dispose(); // Dispose no longer needed non-buffer geometry. return bufferGeometry; }
[ "function", "toBufferGeometry", "(", "geometry", ",", "doBuffer", ")", "{", "var", "bufferGeometry", ";", "if", "(", "!", "doBuffer", ")", "{", "return", "geometry", ";", "}", "bufferGeometry", "=", "new", "THREE", ".", "BufferGeometry", "(", ")", ".", "fromGeometry", "(", "geometry", ")", ";", "bufferGeometry", ".", "metadata", "=", "{", "type", ":", "geometry", ".", "type", ",", "parameters", ":", "geometry", ".", "parameters", "||", "{", "}", "}", ";", "geometry", ".", "dispose", "(", ")", ";", "// Dispose no longer needed non-buffer geometry.", "return", "bufferGeometry", ";", "}" ]
Transform geometry to BufferGeometry if `doBuffer`. @param {object} geometry @param {boolean} doBuffer @returns {object} Geometry.
[ "Transform", "geometry", "to", "BufferGeometry", "if", "doBuffer", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/systems/geometry.js#L130-L138
1,589
aframevr/aframe
src/utils/material.js
handleTextureEvents
function handleTextureEvents (el, texture) { if (!texture) { return; } el.emit('materialtextureloaded', {src: texture.image, texture: texture}); // Video events. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; } texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () { // Check to see if we need to use iOS 10 HLS shader. // Only override the shader if it is stock shader that we know doesn't correct. if (!el.components || !el.components.material) { return; } if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY && ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) { el.setAttribute('material', 'shader', 'ios10hls'); } el.emit('materialvideoloadeddata', {src: texture.image, texture: texture}); }); texture.image.addEventListener('ended', function emitVideoTextureEndedAll () { // Works for non-looping videos only. el.emit('materialvideoended', {src: texture.image, texture: texture}); }); }
javascript
function handleTextureEvents (el, texture) { if (!texture) { return; } el.emit('materialtextureloaded', {src: texture.image, texture: texture}); // Video events. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; } texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () { // Check to see if we need to use iOS 10 HLS shader. // Only override the shader if it is stock shader that we know doesn't correct. if (!el.components || !el.components.material) { return; } if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY && ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) { el.setAttribute('material', 'shader', 'ios10hls'); } el.emit('materialvideoloadeddata', {src: texture.image, texture: texture}); }); texture.image.addEventListener('ended', function emitVideoTextureEndedAll () { // Works for non-looping videos only. el.emit('materialvideoended', {src: texture.image, texture: texture}); }); }
[ "function", "handleTextureEvents", "(", "el", ",", "texture", ")", "{", "if", "(", "!", "texture", ")", "{", "return", ";", "}", "el", ".", "emit", "(", "'materialtextureloaded'", ",", "{", "src", ":", "texture", ".", "image", ",", "texture", ":", "texture", "}", ")", ";", "// Video events.", "if", "(", "!", "texture", ".", "image", "||", "texture", ".", "image", ".", "tagName", "!==", "'VIDEO'", ")", "{", "return", ";", "}", "texture", ".", "image", ".", "addEventListener", "(", "'loadeddata'", ",", "function", "emitVideoTextureLoadedDataAll", "(", ")", "{", "// Check to see if we need to use iOS 10 HLS shader.", "// Only override the shader if it is stock shader that we know doesn't correct.", "if", "(", "!", "el", ".", "components", "||", "!", "el", ".", "components", ".", "material", ")", "{", "return", ";", "}", "if", "(", "texture", ".", "needsCorrectionBGRA", "&&", "texture", ".", "needsCorrectionFlipY", "&&", "[", "'standard'", ",", "'flat'", "]", ".", "indexOf", "(", "el", ".", "components", ".", "material", ".", "data", ".", "shader", ")", "!==", "-", "1", ")", "{", "el", ".", "setAttribute", "(", "'material'", ",", "'shader'", ",", "'ios10hls'", ")", ";", "}", "el", ".", "emit", "(", "'materialvideoloadeddata'", ",", "{", "src", ":", "texture", ".", "image", ",", "texture", ":", "texture", "}", ")", ";", "}", ")", ";", "texture", ".", "image", ".", "addEventListener", "(", "'ended'", ",", "function", "emitVideoTextureEndedAll", "(", ")", "{", "// Works for non-looping videos only.", "el", ".", "emit", "(", "'materialvideoended'", ",", "{", "src", ":", "texture", ".", "image", ",", "texture", ":", "texture", "}", ")", ";", "}", ")", ";", "}" ]
Emit event on entities on texture-related events. @param {Element} el - Entity. @param {object} texture - three.js Texture.
[ "Emit", "event", "on", "entities", "on", "texture", "-", "related", "events", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/material.js#L132-L156
1,590
aframevr/aframe
src/utils/device.js
isTablet
function isTablet (mockUserAgent) { var userAgent = mockUserAgent || window.navigator.userAgent; return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent); }
javascript
function isTablet (mockUserAgent) { var userAgent = mockUserAgent || window.navigator.userAgent; return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent); }
[ "function", "isTablet", "(", "mockUserAgent", ")", "{", "var", "userAgent", "=", "mockUserAgent", "||", "window", ".", "navigator", ".", "userAgent", ";", "return", "/", "ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle", "/", "i", ".", "test", "(", "userAgent", ")", ";", "}" ]
Detect tablet devices. @param {string} mockUserAgent - Allow passing a mock user agent for testing.
[ "Detect", "tablet", "devices", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/utils/device.js#L76-L79
1,591
aframevr/aframe
src/shaders/standard.js
function (data) { var self = this; var material = this.material; var envMap = data.envMap; var sphericalEnvMap = data.sphericalEnvMap; // No envMap defined or already loading. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) { material.envMap = null; material.needsUpdate = true; return; } this.isLoadingEnvMap = true; // if a spherical env map is defined then use it. if (sphericalEnvMap) { this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) { self.isLoadingEnvMap = false; texture.mapping = THREE.SphericalReflectionMapping; material.envMap = texture; utils.material.handleTextureEvents(self.el, texture); material.needsUpdate = true; }); return; } // Another material is already loading this texture. Wait on promise. if (texturePromises[envMap]) { texturePromises[envMap].then(function (cube) { self.isLoadingEnvMap = false; material.envMap = cube; utils.material.handleTextureEvents(self.el, cube); material.needsUpdate = true; }); return; } // Material is first to load this texture. Load and resolve texture. texturePromises[envMap] = new Promise(function (resolve) { utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) { CubeLoader.load(urls, function (cube) { // Texture loaded. self.isLoadingEnvMap = false; material.envMap = cube; utils.material.handleTextureEvents(self.el, cube); resolve(cube); }); }); }); }
javascript
function (data) { var self = this; var material = this.material; var envMap = data.envMap; var sphericalEnvMap = data.sphericalEnvMap; // No envMap defined or already loading. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) { material.envMap = null; material.needsUpdate = true; return; } this.isLoadingEnvMap = true; // if a spherical env map is defined then use it. if (sphericalEnvMap) { this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) { self.isLoadingEnvMap = false; texture.mapping = THREE.SphericalReflectionMapping; material.envMap = texture; utils.material.handleTextureEvents(self.el, texture); material.needsUpdate = true; }); return; } // Another material is already loading this texture. Wait on promise. if (texturePromises[envMap]) { texturePromises[envMap].then(function (cube) { self.isLoadingEnvMap = false; material.envMap = cube; utils.material.handleTextureEvents(self.el, cube); material.needsUpdate = true; }); return; } // Material is first to load this texture. Load and resolve texture. texturePromises[envMap] = new Promise(function (resolve) { utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) { CubeLoader.load(urls, function (cube) { // Texture loaded. self.isLoadingEnvMap = false; material.envMap = cube; utils.material.handleTextureEvents(self.el, cube); resolve(cube); }); }); }); }
[ "function", "(", "data", ")", "{", "var", "self", "=", "this", ";", "var", "material", "=", "this", ".", "material", ";", "var", "envMap", "=", "data", ".", "envMap", ";", "var", "sphericalEnvMap", "=", "data", ".", "sphericalEnvMap", ";", "// No envMap defined or already loading.", "if", "(", "(", "!", "envMap", "&&", "!", "sphericalEnvMap", ")", "||", "this", ".", "isLoadingEnvMap", ")", "{", "material", ".", "envMap", "=", "null", ";", "material", ".", "needsUpdate", "=", "true", ";", "return", ";", "}", "this", ".", "isLoadingEnvMap", "=", "true", ";", "// if a spherical env map is defined then use it.", "if", "(", "sphericalEnvMap", ")", "{", "this", ".", "el", ".", "sceneEl", ".", "systems", ".", "material", ".", "loadTexture", "(", "sphericalEnvMap", ",", "{", "src", ":", "sphericalEnvMap", "}", ",", "function", "textureLoaded", "(", "texture", ")", "{", "self", ".", "isLoadingEnvMap", "=", "false", ";", "texture", ".", "mapping", "=", "THREE", ".", "SphericalReflectionMapping", ";", "material", ".", "envMap", "=", "texture", ";", "utils", ".", "material", ".", "handleTextureEvents", "(", "self", ".", "el", ",", "texture", ")", ";", "material", ".", "needsUpdate", "=", "true", ";", "}", ")", ";", "return", ";", "}", "// Another material is already loading this texture. Wait on promise.", "if", "(", "texturePromises", "[", "envMap", "]", ")", "{", "texturePromises", "[", "envMap", "]", ".", "then", "(", "function", "(", "cube", ")", "{", "self", ".", "isLoadingEnvMap", "=", "false", ";", "material", ".", "envMap", "=", "cube", ";", "utils", ".", "material", ".", "handleTextureEvents", "(", "self", ".", "el", ",", "cube", ")", ";", "material", ".", "needsUpdate", "=", "true", ";", "}", ")", ";", "return", ";", "}", "// Material is first to load this texture. Load and resolve texture.", "texturePromises", "[", "envMap", "]", "=", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "utils", ".", "srcLoader", ".", "validateCubemapSrc", "(", "envMap", ",", "function", "loadEnvMap", "(", "urls", ")", "{", "CubeLoader", ".", "load", "(", "urls", ",", "function", "(", "cube", ")", "{", "// Texture loaded.", "self", ".", "isLoadingEnvMap", "=", "false", ";", "material", ".", "envMap", "=", "cube", ";", "utils", ".", "material", ".", "handleTextureEvents", "(", "self", ".", "el", ",", "cube", ")", ";", "resolve", "(", "cube", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Handle environment cubemap. Textures are cached in texturePromises.
[ "Handle", "environment", "cubemap", ".", "Textures", "are", "cached", "in", "texturePromises", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/shaders/standard.js#L109-L158
1,592
aframevr/aframe
src/components/light.js
function () { var el = this.el; var data = this.data; var light = this.light; light.castShadow = data.castShadow; // Shadow camera helper. var cameraHelper = el.getObject3D('cameraHelper'); if (data.shadowCameraVisible && !cameraHelper) { el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera)); } else if (!data.shadowCameraVisible && cameraHelper) { el.removeObject3D('cameraHelper'); } if (!data.castShadow) { return light; } // Shadow appearance. light.shadow.bias = data.shadowBias; light.shadow.radius = data.shadowRadius; light.shadow.mapSize.height = data.shadowMapHeight; light.shadow.mapSize.width = data.shadowMapWidth; // Shadow camera. light.shadow.camera.near = data.shadowCameraNear; light.shadow.camera.far = data.shadowCameraFar; if (light.shadow.camera instanceof THREE.OrthographicCamera) { light.shadow.camera.top = data.shadowCameraTop; light.shadow.camera.right = data.shadowCameraRight; light.shadow.camera.bottom = data.shadowCameraBottom; light.shadow.camera.left = data.shadowCameraLeft; } else { light.shadow.camera.fov = data.shadowCameraFov; } light.shadow.camera.updateProjectionMatrix(); if (cameraHelper) { cameraHelper.update(); } }
javascript
function () { var el = this.el; var data = this.data; var light = this.light; light.castShadow = data.castShadow; // Shadow camera helper. var cameraHelper = el.getObject3D('cameraHelper'); if (data.shadowCameraVisible && !cameraHelper) { el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera)); } else if (!data.shadowCameraVisible && cameraHelper) { el.removeObject3D('cameraHelper'); } if (!data.castShadow) { return light; } // Shadow appearance. light.shadow.bias = data.shadowBias; light.shadow.radius = data.shadowRadius; light.shadow.mapSize.height = data.shadowMapHeight; light.shadow.mapSize.width = data.shadowMapWidth; // Shadow camera. light.shadow.camera.near = data.shadowCameraNear; light.shadow.camera.far = data.shadowCameraFar; if (light.shadow.camera instanceof THREE.OrthographicCamera) { light.shadow.camera.top = data.shadowCameraTop; light.shadow.camera.right = data.shadowCameraRight; light.shadow.camera.bottom = data.shadowCameraBottom; light.shadow.camera.left = data.shadowCameraLeft; } else { light.shadow.camera.fov = data.shadowCameraFov; } light.shadow.camera.updateProjectionMatrix(); if (cameraHelper) { cameraHelper.update(); } }
[ "function", "(", ")", "{", "var", "el", "=", "this", ".", "el", ";", "var", "data", "=", "this", ".", "data", ";", "var", "light", "=", "this", ".", "light", ";", "light", ".", "castShadow", "=", "data", ".", "castShadow", ";", "// Shadow camera helper.", "var", "cameraHelper", "=", "el", ".", "getObject3D", "(", "'cameraHelper'", ")", ";", "if", "(", "data", ".", "shadowCameraVisible", "&&", "!", "cameraHelper", ")", "{", "el", ".", "setObject3D", "(", "'cameraHelper'", ",", "new", "THREE", ".", "CameraHelper", "(", "light", ".", "shadow", ".", "camera", ")", ")", ";", "}", "else", "if", "(", "!", "data", ".", "shadowCameraVisible", "&&", "cameraHelper", ")", "{", "el", ".", "removeObject3D", "(", "'cameraHelper'", ")", ";", "}", "if", "(", "!", "data", ".", "castShadow", ")", "{", "return", "light", ";", "}", "// Shadow appearance.", "light", ".", "shadow", ".", "bias", "=", "data", ".", "shadowBias", ";", "light", ".", "shadow", ".", "radius", "=", "data", ".", "shadowRadius", ";", "light", ".", "shadow", ".", "mapSize", ".", "height", "=", "data", ".", "shadowMapHeight", ";", "light", ".", "shadow", ".", "mapSize", ".", "width", "=", "data", ".", "shadowMapWidth", ";", "// Shadow camera.", "light", ".", "shadow", ".", "camera", ".", "near", "=", "data", ".", "shadowCameraNear", ";", "light", ".", "shadow", ".", "camera", ".", "far", "=", "data", ".", "shadowCameraFar", ";", "if", "(", "light", ".", "shadow", ".", "camera", "instanceof", "THREE", ".", "OrthographicCamera", ")", "{", "light", ".", "shadow", ".", "camera", ".", "top", "=", "data", ".", "shadowCameraTop", ";", "light", ".", "shadow", ".", "camera", ".", "right", "=", "data", ".", "shadowCameraRight", ";", "light", ".", "shadow", ".", "camera", ".", "bottom", "=", "data", ".", "shadowCameraBottom", ";", "light", ".", "shadow", ".", "camera", ".", "left", "=", "data", ".", "shadowCameraLeft", ";", "}", "else", "{", "light", ".", "shadow", ".", "camera", ".", "fov", "=", "data", ".", "shadowCameraFov", ";", "}", "light", ".", "shadow", ".", "camera", ".", "updateProjectionMatrix", "(", ")", ";", "if", "(", "cameraHelper", ")", "{", "cameraHelper", ".", "update", "(", ")", ";", "}", "}" ]
Updates shadow-related properties on the current light.
[ "Updates", "shadow", "-", "related", "properties", "on", "the", "current", "light", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/light.js#L168-L205
1,593
aframevr/aframe
src/components/light.js
function (data) { var angle = data.angle; var color = new THREE.Color(data.color); this.rendererSystem.applyColorCorrection(color); color = color.getHex(); var decay = data.decay; var distance = data.distance; var groundColor = new THREE.Color(data.groundColor); this.rendererSystem.applyColorCorrection(groundColor); groundColor = groundColor.getHex(); var intensity = data.intensity; var type = data.type; var target = data.target; var light = null; switch (type.toLowerCase()) { case 'ambient': { return new THREE.AmbientLight(color, intensity); } case 'directional': { light = new THREE.DirectionalLight(color, intensity); this.defaultTarget = light.target; if (target) { if (target.hasLoaded) { this.onSetTarget(target, light); } else { target.addEventListener('loaded', bind(this.onSetTarget, this, target, light)); } } return light; } case 'hemisphere': { return new THREE.HemisphereLight(color, groundColor, intensity); } case 'point': { return new THREE.PointLight(color, intensity, distance, decay); } case 'spot': { light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay); this.defaultTarget = light.target; if (target) { if (target.hasLoaded) { this.onSetTarget(target, light); } else { target.addEventListener('loaded', bind(this.onSetTarget, this, target, light)); } } return light; } default: { warn('%s is not a valid light type. ' + 'Choose from ambient, directional, hemisphere, point, spot.', type); } } }
javascript
function (data) { var angle = data.angle; var color = new THREE.Color(data.color); this.rendererSystem.applyColorCorrection(color); color = color.getHex(); var decay = data.decay; var distance = data.distance; var groundColor = new THREE.Color(data.groundColor); this.rendererSystem.applyColorCorrection(groundColor); groundColor = groundColor.getHex(); var intensity = data.intensity; var type = data.type; var target = data.target; var light = null; switch (type.toLowerCase()) { case 'ambient': { return new THREE.AmbientLight(color, intensity); } case 'directional': { light = new THREE.DirectionalLight(color, intensity); this.defaultTarget = light.target; if (target) { if (target.hasLoaded) { this.onSetTarget(target, light); } else { target.addEventListener('loaded', bind(this.onSetTarget, this, target, light)); } } return light; } case 'hemisphere': { return new THREE.HemisphereLight(color, groundColor, intensity); } case 'point': { return new THREE.PointLight(color, intensity, distance, decay); } case 'spot': { light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay); this.defaultTarget = light.target; if (target) { if (target.hasLoaded) { this.onSetTarget(target, light); } else { target.addEventListener('loaded', bind(this.onSetTarget, this, target, light)); } } return light; } default: { warn('%s is not a valid light type. ' + 'Choose from ambient, directional, hemisphere, point, spot.', type); } } }
[ "function", "(", "data", ")", "{", "var", "angle", "=", "data", ".", "angle", ";", "var", "color", "=", "new", "THREE", ".", "Color", "(", "data", ".", "color", ")", ";", "this", ".", "rendererSystem", ".", "applyColorCorrection", "(", "color", ")", ";", "color", "=", "color", ".", "getHex", "(", ")", ";", "var", "decay", "=", "data", ".", "decay", ";", "var", "distance", "=", "data", ".", "distance", ";", "var", "groundColor", "=", "new", "THREE", ".", "Color", "(", "data", ".", "groundColor", ")", ";", "this", ".", "rendererSystem", ".", "applyColorCorrection", "(", "groundColor", ")", ";", "groundColor", "=", "groundColor", ".", "getHex", "(", ")", ";", "var", "intensity", "=", "data", ".", "intensity", ";", "var", "type", "=", "data", ".", "type", ";", "var", "target", "=", "data", ".", "target", ";", "var", "light", "=", "null", ";", "switch", "(", "type", ".", "toLowerCase", "(", ")", ")", "{", "case", "'ambient'", ":", "{", "return", "new", "THREE", ".", "AmbientLight", "(", "color", ",", "intensity", ")", ";", "}", "case", "'directional'", ":", "{", "light", "=", "new", "THREE", ".", "DirectionalLight", "(", "color", ",", "intensity", ")", ";", "this", ".", "defaultTarget", "=", "light", ".", "target", ";", "if", "(", "target", ")", "{", "if", "(", "target", ".", "hasLoaded", ")", "{", "this", ".", "onSetTarget", "(", "target", ",", "light", ")", ";", "}", "else", "{", "target", ".", "addEventListener", "(", "'loaded'", ",", "bind", "(", "this", ".", "onSetTarget", ",", "this", ",", "target", ",", "light", ")", ")", ";", "}", "}", "return", "light", ";", "}", "case", "'hemisphere'", ":", "{", "return", "new", "THREE", ".", "HemisphereLight", "(", "color", ",", "groundColor", ",", "intensity", ")", ";", "}", "case", "'point'", ":", "{", "return", "new", "THREE", ".", "PointLight", "(", "color", ",", "intensity", ",", "distance", ",", "decay", ")", ";", "}", "case", "'spot'", ":", "{", "light", "=", "new", "THREE", ".", "SpotLight", "(", "color", ",", "intensity", ",", "distance", ",", "degToRad", "(", "angle", ")", ",", "data", ".", "penumbra", ",", "decay", ")", ";", "this", ".", "defaultTarget", "=", "light", ".", "target", ";", "if", "(", "target", ")", "{", "if", "(", "target", ".", "hasLoaded", ")", "{", "this", ".", "onSetTarget", "(", "target", ",", "light", ")", ";", "}", "else", "{", "target", ".", "addEventListener", "(", "'loaded'", ",", "bind", "(", "this", ".", "onSetTarget", ",", "this", ",", "target", ",", "light", ")", ")", ";", "}", "}", "return", "light", ";", "}", "default", ":", "{", "warn", "(", "'%s is not a valid light type. '", "+", "'Choose from ambient, directional, hemisphere, point, spot.'", ",", "type", ")", ";", "}", "}", "}" ]
Creates a new three.js light object given data object defining the light. @param {object} data
[ "Creates", "a", "new", "three", ".", "js", "light", "object", "given", "data", "object", "defining", "the", "light", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/light.js#L212-L271
1,594
aframevr/aframe
src/core/system.js
function (rawData) { var oldData = this.data; if (!Object.keys(schema).length) { return; } this.buildData(rawData); this.update(oldData); }
javascript
function (rawData) { var oldData = this.data; if (!Object.keys(schema).length) { return; } this.buildData(rawData); this.update(oldData); }
[ "function", "(", "rawData", ")", "{", "var", "oldData", "=", "this", ".", "data", ";", "if", "(", "!", "Object", ".", "keys", "(", "schema", ")", ".", "length", ")", "{", "return", ";", "}", "this", ".", "buildData", "(", "rawData", ")", ";", "this", ".", "update", "(", "oldData", ")", ";", "}" ]
Build data and call update handler. @private
[ "Build", "data", "and", "call", "update", "handler", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/core/system.js#L69-L74
1,595
aframevr/aframe
src/components/rotation.js
function () { var data = this.data; var object3D = this.el.object3D; object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z)); object3D.rotation.order = 'YXZ'; }
javascript
function () { var data = this.data; var object3D = this.el.object3D; object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z)); object3D.rotation.order = 'YXZ'; }
[ "function", "(", ")", "{", "var", "data", "=", "this", ".", "data", ";", "var", "object3D", "=", "this", ".", "el", ".", "object3D", ";", "object3D", ".", "rotation", ".", "set", "(", "degToRad", "(", "data", ".", "x", ")", ",", "degToRad", "(", "data", ".", "y", ")", ",", "degToRad", "(", "data", ".", "z", ")", ")", ";", "object3D", ".", "rotation", ".", "order", "=", "'YXZ'", ";", "}" ]
Updates object3D rotation.
[ "Updates", "object3D", "rotation", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/rotation.js#L10-L15
1,596
aframevr/aframe
src/components/material.js
function (oldData) { var data = this.data; if (!this.shader || data.shader !== oldData.shader) { this.updateShader(data.shader); } this.shader.update(this.data); this.updateMaterial(oldData); }
javascript
function (oldData) { var data = this.data; if (!this.shader || data.shader !== oldData.shader) { this.updateShader(data.shader); } this.shader.update(this.data); this.updateMaterial(oldData); }
[ "function", "(", "oldData", ")", "{", "var", "data", "=", "this", ".", "data", ";", "if", "(", "!", "this", ".", "shader", "||", "data", ".", "shader", "!==", "oldData", ".", "shader", ")", "{", "this", ".", "updateShader", "(", "data", ".", "shader", ")", ";", "}", "this", ".", "shader", ".", "update", "(", "this", ".", "data", ")", ";", "this", ".", "updateMaterial", "(", "oldData", ")", ";", "}" ]
Update or create material. @param {object|null} oldData
[ "Update", "or", "create", "material", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/material.js#L46-L53
1,597
aframevr/aframe
src/components/material.js
function (oldData) { var data = this.data; var material = this.material; var oldDataHasKeys; // Base material properties. material.alphaTest = data.alphaTest; material.depthTest = data.depthTest !== false; material.depthWrite = data.depthWrite !== false; material.opacity = data.opacity; material.flatShading = data.flatShading; material.side = parseSide(data.side); material.transparent = data.transparent !== false || data.opacity < 1.0; material.vertexColors = parseVertexColors(data.vertexColors); material.visible = data.visible; material.blending = parseBlending(data.blending); // Check if material needs update. for (oldDataHasKeys in oldData) { break; } if (oldDataHasKeys && (oldData.alphaTest !== data.alphaTest || oldData.side !== data.side || oldData.vertexColors !== data.vertexColors)) { material.needsUpdate = true; } }
javascript
function (oldData) { var data = this.data; var material = this.material; var oldDataHasKeys; // Base material properties. material.alphaTest = data.alphaTest; material.depthTest = data.depthTest !== false; material.depthWrite = data.depthWrite !== false; material.opacity = data.opacity; material.flatShading = data.flatShading; material.side = parseSide(data.side); material.transparent = data.transparent !== false || data.opacity < 1.0; material.vertexColors = parseVertexColors(data.vertexColors); material.visible = data.visible; material.blending = parseBlending(data.blending); // Check if material needs update. for (oldDataHasKeys in oldData) { break; } if (oldDataHasKeys && (oldData.alphaTest !== data.alphaTest || oldData.side !== data.side || oldData.vertexColors !== data.vertexColors)) { material.needsUpdate = true; } }
[ "function", "(", "oldData", ")", "{", "var", "data", "=", "this", ".", "data", ";", "var", "material", "=", "this", ".", "material", ";", "var", "oldDataHasKeys", ";", "// Base material properties.", "material", ".", "alphaTest", "=", "data", ".", "alphaTest", ";", "material", ".", "depthTest", "=", "data", ".", "depthTest", "!==", "false", ";", "material", ".", "depthWrite", "=", "data", ".", "depthWrite", "!==", "false", ";", "material", ".", "opacity", "=", "data", ".", "opacity", ";", "material", ".", "flatShading", "=", "data", ".", "flatShading", ";", "material", ".", "side", "=", "parseSide", "(", "data", ".", "side", ")", ";", "material", ".", "transparent", "=", "data", ".", "transparent", "!==", "false", "||", "data", ".", "opacity", "<", "1.0", ";", "material", ".", "vertexColors", "=", "parseVertexColors", "(", "data", ".", "vertexColors", ")", ";", "material", ".", "visible", "=", "data", ".", "visible", ";", "material", ".", "blending", "=", "parseBlending", "(", "data", ".", "blending", ")", ";", "// Check if material needs update.", "for", "(", "oldDataHasKeys", "in", "oldData", ")", "{", "break", ";", "}", "if", "(", "oldDataHasKeys", "&&", "(", "oldData", ".", "alphaTest", "!==", "data", ".", "alphaTest", "||", "oldData", ".", "side", "!==", "data", ".", "side", "||", "oldData", ".", "vertexColors", "!==", "data", ".", "vertexColors", ")", ")", "{", "material", ".", "needsUpdate", "=", "true", ";", "}", "}" ]
Set and update base material properties. Set `needsUpdate` when needed.
[ "Set", "and", "update", "base", "material", "properties", ".", "Set", "needsUpdate", "when", "needed", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/material.js#L124-L149
1,598
aframevr/aframe
src/components/material.js
parseBlending
function parseBlending (blending) { switch (blending) { case 'none': { return THREE.NoBlending; } case 'additive': { return THREE.AdditiveBlending; } case 'subtractive': { return THREE.SubtractiveBlending; } case 'multiply': { return THREE.MultiplyBlending; } default: { return THREE.NormalBlending; } } }
javascript
function parseBlending (blending) { switch (blending) { case 'none': { return THREE.NoBlending; } case 'additive': { return THREE.AdditiveBlending; } case 'subtractive': { return THREE.SubtractiveBlending; } case 'multiply': { return THREE.MultiplyBlending; } default: { return THREE.NormalBlending; } } }
[ "function", "parseBlending", "(", "blending", ")", "{", "switch", "(", "blending", ")", "{", "case", "'none'", ":", "{", "return", "THREE", ".", "NoBlending", ";", "}", "case", "'additive'", ":", "{", "return", "THREE", ".", "AdditiveBlending", ";", "}", "case", "'subtractive'", ":", "{", "return", "THREE", ".", "SubtractiveBlending", ";", "}", "case", "'multiply'", ":", "{", "return", "THREE", ".", "MultiplyBlending", ";", "}", "default", ":", "{", "return", "THREE", ".", "NormalBlending", ";", "}", "}", "}" ]
Return a three.js constant determining blending @param {string} [blending=normal] - `none`, additive`, `subtractive`,`multiply` or `normal`. @returns {number}
[ "Return", "a", "three", ".", "js", "constant", "determining", "blending" ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/material.js#L241-L259
1,599
aframevr/aframe
src/components/camera.js
function () { var camera; var el = this.el; // Create camera. camera = this.camera = new THREE.PerspectiveCamera(); el.setObject3D('camera', camera); }
javascript
function () { var camera; var el = this.el; // Create camera. camera = this.camera = new THREE.PerspectiveCamera(); el.setObject3D('camera', camera); }
[ "function", "(", ")", "{", "var", "camera", ";", "var", "el", "=", "this", ".", "el", ";", "// Create camera.", "camera", "=", "this", ".", "camera", "=", "new", "THREE", ".", "PerspectiveCamera", "(", ")", ";", "el", ".", "setObject3D", "(", "'camera'", ",", "camera", ")", ";", "}" ]
Initialize three.js camera and add it to the entity. Add reference from scene to this entity as the camera.
[ "Initialize", "three", ".", "js", "camera", "and", "add", "it", "to", "the", "entity", ".", "Add", "reference", "from", "scene", "to", "this", "entity", "as", "the", "camera", "." ]
24acc78a7299a4cdfe3ef617f4d40ddf6275c992
https://github.com/aframevr/aframe/blob/24acc78a7299a4cdfe3ef617f4d40ddf6275c992/src/components/camera.js#L22-L29