language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function CanvasLine(gameCanvas, xStart, yStart, xEnd, yEnd, isFatal, isEndpoint) { var self = this; this.gameCanvas = gameCanvas; this.xStart = xStart; this.yStart = yStart; this.xEnd = xEnd; this.yEnd = yEnd; this.isFatal = isFatal || false; this.isEndpoint = isEndpoint || false; this.tickRate = 500; /** Draw this line on the canvas. */ this.draw = function(){ var yStartFixed = this.gameCanvas.groundOffset - this.yStart; var yEndFixed = this.gameCanvas.groundOffset - this.yEnd; // Draw the wall on the canvas var context = this.gameCanvas.context; context.beginPath(); context.moveTo(this.xStart, yStartFixed); context.lineTo(this.xEnd, yEndFixed); context.closePath(); context.stroke(); } if (this.isFatal) { var level = this.gameCanvas.currentLevel; level.intervals.push(setInterval(function(){ self.tick_check_fatalities(); }, this.tickRate)); } /** Check if each active character in the gameWorld is on this line, and if it is, kill and respawn it. */ this.tick_check_fatalities = function(){ this.gameCanvas.characters.forEach(function (character) { if (character.is_on_line(self)) { character.respawn (); } }); } if (this.isEndpoint) { var level = this.gameCanvas.currentLevel; level.intervals.push(setInterval(function(){ self.tick_check_endpoints(); }, this.tickRate)); } /** Check if each active character in the gameWorld is on this line, and if it is, teleport it to the next level. */ this.tick_check_endpoints = function(){ this.gameCanvas.characters.forEach(function (character) { if (character.is_on_line(self)) { self.gameCanvas.complete_level(); } }); } }
function CanvasLine(gameCanvas, xStart, yStart, xEnd, yEnd, isFatal, isEndpoint) { var self = this; this.gameCanvas = gameCanvas; this.xStart = xStart; this.yStart = yStart; this.xEnd = xEnd; this.yEnd = yEnd; this.isFatal = isFatal || false; this.isEndpoint = isEndpoint || false; this.tickRate = 500; /** Draw this line on the canvas. */ this.draw = function(){ var yStartFixed = this.gameCanvas.groundOffset - this.yStart; var yEndFixed = this.gameCanvas.groundOffset - this.yEnd; // Draw the wall on the canvas var context = this.gameCanvas.context; context.beginPath(); context.moveTo(this.xStart, yStartFixed); context.lineTo(this.xEnd, yEndFixed); context.closePath(); context.stroke(); } if (this.isFatal) { var level = this.gameCanvas.currentLevel; level.intervals.push(setInterval(function(){ self.tick_check_fatalities(); }, this.tickRate)); } /** Check if each active character in the gameWorld is on this line, and if it is, kill and respawn it. */ this.tick_check_fatalities = function(){ this.gameCanvas.characters.forEach(function (character) { if (character.is_on_line(self)) { character.respawn (); } }); } if (this.isEndpoint) { var level = this.gameCanvas.currentLevel; level.intervals.push(setInterval(function(){ self.tick_check_endpoints(); }, this.tickRate)); } /** Check if each active character in the gameWorld is on this line, and if it is, teleport it to the next level. */ this.tick_check_endpoints = function(){ this.gameCanvas.characters.forEach(function (character) { if (character.is_on_line(self)) { self.gameCanvas.complete_level(); } }); } }
JavaScript
function KeyBindings(character) { this.character = character; this.bind_defaults = function(){ var character = this.character; // Bind keys for moving left Mousetrap.bind(["a", "left"], function(){ character.isPlanningMovement = true; character.isFacingLeft = true; character.isWalking = true; character.start_walking(); //console.log("left"); }); Mousetrap.bind(["a", "left"], function(){ if (character.isFacingLeft) { character.begin_movement_stop(); } //console.log("left_up"); }, "keyup"); // Bind keys for moving right Mousetrap.bind(["d", "right"], function(){ character.isPlanningMovement = true; character.isFacingLeft = false; character.isWalking = true; character.start_walking(); //console.log("right"); }); Mousetrap.bind(["d", "right"], function(){ if (!character.isFacingLeft) { character.begin_movement_stop(); } //console.log("right_up"); }, "keyup"); // Bind keys for jumping Mousetrap.bind(["w", "up", "space"], function (e) { // Remove default behavior of buttons (page scrolling) if (e.preventDefault()) { e.preventDefault(); } else { e.returnValue = false; //IE } character.attempt_jump(); }); // Bind keys for crouching Mousetrap.bind(["s", "down"], function (e) { // Remove default behavior of buttons (page scrolling) if (e.preventDefault()) { e.preventDefault(); } else { e.returnValue = false; //IE } //character.start_crouching(); character.stop_moving(); }); // Bind key for running Mousetrap.bind(["q", "capslock"], function(){ character.start_running(); }); // Bind key for respawning Mousetrap.bind("c", function(){ character.respawn (); }); // Bind key for pausing Mousetrap.bind("z", function(){ var canvas = character.gameCanvas; if (canvas.isPaused) { canvas.unpause(); } else { canvas.pause(); } }); // Bind key for restarting the game Mousetrap.bind("x", function(){ character.gameCanvas.reset_game(); }); } this.unbind_all = function(){ Mousetrap.unbind(["a", "left", "d", "right", "w", "up", "space", "s", "down", "q", "c", "z", "x", "capslock"]); } }
function KeyBindings(character) { this.character = character; this.bind_defaults = function(){ var character = this.character; // Bind keys for moving left Mousetrap.bind(["a", "left"], function(){ character.isPlanningMovement = true; character.isFacingLeft = true; character.isWalking = true; character.start_walking(); //console.log("left"); }); Mousetrap.bind(["a", "left"], function(){ if (character.isFacingLeft) { character.begin_movement_stop(); } //console.log("left_up"); }, "keyup"); // Bind keys for moving right Mousetrap.bind(["d", "right"], function(){ character.isPlanningMovement = true; character.isFacingLeft = false; character.isWalking = true; character.start_walking(); //console.log("right"); }); Mousetrap.bind(["d", "right"], function(){ if (!character.isFacingLeft) { character.begin_movement_stop(); } //console.log("right_up"); }, "keyup"); // Bind keys for jumping Mousetrap.bind(["w", "up", "space"], function (e) { // Remove default behavior of buttons (page scrolling) if (e.preventDefault()) { e.preventDefault(); } else { e.returnValue = false; //IE } character.attempt_jump(); }); // Bind keys for crouching Mousetrap.bind(["s", "down"], function (e) { // Remove default behavior of buttons (page scrolling) if (e.preventDefault()) { e.preventDefault(); } else { e.returnValue = false; //IE } //character.start_crouching(); character.stop_moving(); }); // Bind key for running Mousetrap.bind(["q", "capslock"], function(){ character.start_running(); }); // Bind key for respawning Mousetrap.bind("c", function(){ character.respawn (); }); // Bind key for pausing Mousetrap.bind("z", function(){ var canvas = character.gameCanvas; if (canvas.isPaused) { canvas.unpause(); } else { canvas.pause(); } }); // Bind key for restarting the game Mousetrap.bind("x", function(){ character.gameCanvas.reset_game(); }); } this.unbind_all = function(){ Mousetrap.unbind(["a", "left", "d", "right", "w", "up", "space", "s", "down", "q", "c", "z", "x", "capslock"]); } }
JavaScript
function isPalindrome(number) { let strNumber = number + '' let first, last, difference while (true) { first = parseInt(strNumber[0]) last = parseInt(strNumber[strNumber.length - 1]) difference = first - last if (strNumber.length <= 1) { return true } else if (difference === 0) { strNumber = strNumber.slice(1, strNumber.length - 1) + '' } else if (difference !== 0) { return false } } }
function isPalindrome(number) { let strNumber = number + '' let first, last, difference while (true) { first = parseInt(strNumber[0]) last = parseInt(strNumber[strNumber.length - 1]) difference = first - last if (strNumber.length <= 1) { return true } else if (difference === 0) { strNumber = strNumber.slice(1, strNumber.length - 1) + '' } else if (difference !== 0) { return false } } }
JavaScript
function formatCanvas() { //Resize canvas const c = document.getElementById('blankCanvas'); c.width = window.innerWidth * 3 / 4; c.height = window.innerHeight * 7 / 8; const ctx = c.getContext('2d'); //Fill in with gradient const grd = ctx.createRadialGradient(c.width/2, c.height/2, c.height/6, c.width/2 + 10, c.height/2 + 10, c.width/2); grd.addColorStop(0, 'lightsteelblue'); grd.addColorStop(1, 'white'); // Fill with gradient ctx.fillStyle = grd; ctx.fillRect(0, 0, c.width, c.height); }
function formatCanvas() { //Resize canvas const c = document.getElementById('blankCanvas'); c.width = window.innerWidth * 3 / 4; c.height = window.innerHeight * 7 / 8; const ctx = c.getContext('2d'); //Fill in with gradient const grd = ctx.createRadialGradient(c.width/2, c.height/2, c.height/6, c.width/2 + 10, c.height/2 + 10, c.width/2); grd.addColorStop(0, 'lightsteelblue'); grd.addColorStop(1, 'white'); // Fill with gradient ctx.fillStyle = grd; ctx.fillRect(0, 0, c.width, c.height); }
JavaScript
function initBody() { createMap(); formatCanvas(); addTextOnCanvas(); displayGalleryElements(); getComments(); getLoginStatus(); fetchBlobstoreUrlAndShowForm(); }
function initBody() { createMap(); formatCanvas(); addTextOnCanvas(); displayGalleryElements(); getComments(); getLoginStatus(); fetchBlobstoreUrlAndShowForm(); }
JavaScript
function createComment(comment) { let div = document.createElement('div'); let myH3 = document.createElement('h3'); myH3.innerText = getEmoji(comment.sentiment) + ' ' + comment.username; div.appendChild(myH3); let myH5 = document.createElement('h5'); myH5.innerText = comment.email; myH5.style = 'margin-top:-5px;' div.appendChild(myH5); let mySubject = document.createElement('p'); mySubject.innerText = comment.subject; div.appendChild(mySubject); let deleteButtonElement = document.createElement('button'); let buttonPicture = document.createElement('img'); buttonPicture.src = 'images/trash.png'; deleteButtonElement.appendChild(buttonPicture); deleteButtonElement.addEventListener('click', () => { deleteComment(comment); // Remove the task from the DOM. div.remove(); }); div.appendChild(deleteButtonElement); if (comment.blobKey !== undefined && comment.blobKey !== null) { fetch('/serveImage?blobKey=' + comment.blobKey) .then(response => response.blob()) .then(myBlob => { let image = document.createElement('img'); image.src = URL.createObjectURL(myBlob); image.style = "max-width:300px;max-height:300px"; div.appendChild(image); }); const imageAnalyseParahraph = document.createElement('p'); imageAnalyseParahraph.innerText = 'TAGS: ' + comment.imageAnalyseResult; imageAnalyseParahraph.style = "color:rgb(141, 140, 140);" div.appendChild(imageAnalyseParahraph); } return div; }
function createComment(comment) { let div = document.createElement('div'); let myH3 = document.createElement('h3'); myH3.innerText = getEmoji(comment.sentiment) + ' ' + comment.username; div.appendChild(myH3); let myH5 = document.createElement('h5'); myH5.innerText = comment.email; myH5.style = 'margin-top:-5px;' div.appendChild(myH5); let mySubject = document.createElement('p'); mySubject.innerText = comment.subject; div.appendChild(mySubject); let deleteButtonElement = document.createElement('button'); let buttonPicture = document.createElement('img'); buttonPicture.src = 'images/trash.png'; deleteButtonElement.appendChild(buttonPicture); deleteButtonElement.addEventListener('click', () => { deleteComment(comment); // Remove the task from the DOM. div.remove(); }); div.appendChild(deleteButtonElement); if (comment.blobKey !== undefined && comment.blobKey !== null) { fetch('/serveImage?blobKey=' + comment.blobKey) .then(response => response.blob()) .then(myBlob => { let image = document.createElement('img'); image.src = URL.createObjectURL(myBlob); image.style = "max-width:300px;max-height:300px"; div.appendChild(image); }); const imageAnalyseParahraph = document.createElement('p'); imageAnalyseParahraph.innerText = 'TAGS: ' + comment.imageAnalyseResult; imageAnalyseParahraph.style = "color:rgb(141, 140, 140);" div.appendChild(imageAnalyseParahraph); } return div; }
JavaScript
function showCommentForm(userInfo) { if (userInfo.isUserLoggedIn) { makeFormElementVisible('submitForm'); makeFormElementVisible('usernameForm'); makeFormElementVisible('signOutLinkHeader', userInfo.logoutUrl); fetch('/userInfo') .then(response => response.json()) .then(user => { const usernameInput = document.getElementById('usernameInput'); usernameInput.value = user.username; }); } else { const link = document.getElementById('signUpLink'); link.href = userInfo.loginUrl; makeFormElementVisible('signIn'); makeFormElementVisible('signInLinkHeader', userInfo.loginUrl) } }
function showCommentForm(userInfo) { if (userInfo.isUserLoggedIn) { makeFormElementVisible('submitForm'); makeFormElementVisible('usernameForm'); makeFormElementVisible('signOutLinkHeader', userInfo.logoutUrl); fetch('/userInfo') .then(response => response.json()) .then(user => { const usernameInput = document.getElementById('usernameInput'); usernameInput.value = user.username; }); } else { const link = document.getElementById('signUpLink'); link.href = userInfo.loginUrl; makeFormElementVisible('signIn'); makeFormElementVisible('signInLinkHeader', userInfo.loginUrl) } }
JavaScript
function createMap() { const map = new google.maps.Map( document.getElementById('map'), { center: {lat: 47.889019, lng: 3.7831301}, zoom: 5, styles:[ { "elementType": "geometry", "stylers": [{"color": "#1d2c4d"}] }, { "elementType": "labels.text.fill", "stylers": [{"color": "#8ec3b9"}] }, { "elementType": "labels.text.stroke", "stylers": [{"color": "#1a3646"}] }, { "featureType": "administrative.country", "elementType": "geometry.stroke", "stylers": [{"color": "#7faa09"}, {"visibility": "on"}, {"weight": 1}, ] }, { "featureType": "administrative.country", "elementType": "labels.text.stroke", "stylers": [{"visibility": "on"}] }, { "featureType": "administrative.land_parcel", "elementType": "labels.text.fill", "stylers": [{"color": "#64779e" }] }, { "featureType": "administrative.province", "elementType": "geometry.stroke", "stylers": [{"color": "#4b6878"}] }, { "featureType": "landscape.man_made", "elementType": "geometry.stroke", "stylers": [{"color": "#334e87"}] }, { "featureType": "landscape.natural", "elementType": "geometry", "stylers": [{"color": "#023e58"}] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{"color": "#283d6a"}] }, { "featureType": "poi", "elementType": "labels.text.fill", "stylers": [{"color": "#6f9ba5"}] }, { "featureType": "poi", "elementType": "labels.text.stroke", "stylers": [{"color": "#1d2c4d"}] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{"color": "#023e58"}] }, { "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [{"color": "#3C7680"}] }, { "featureType": "road", "elementType": "geometry", "stylers": [{"color": "#304a7d"}] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{"color": "#98a5be"}] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [{"color": "#1d2c4d"}] }, { "featureType": "road.highway", "elementType": "geometry", "stylers": [{"color": "#2c6675"}] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [ {"color": "#255763"}] }, { "featureType": "road.highway", "elementType": "labels.text.fill", "stylers": [{"color": "#b0d5ce"}] }, { "featureType": "road.highway", "elementType": "labels.text.stroke", "stylers": [{"color": "#023e58"}] }, { "featureType": "transit", "elementType": "labels.text.fill", "stylers": [{"color": "#98a5be"}] }, { "featureType": "transit", "elementType": "labels.text.stroke", "stylers": [{"color": "#1d2c4d"}] }, { "featureType": "transit.line", "elementType": "geometry.fill", "stylers": [{"color": "#283d6a"}] }, { "featureType": "transit.station", "elementType": "geometry", "stylers": [{"color": "#3a4762"}] }, { "featureType": "water", "elementType": "geometry", "stylers": [{"color": "#0e1626"}] }, { "featureType": "water", "elementType": "labels.text.fill", "stylers": [{"color": "#4e6d70"}] } ] }); map.setMapTypeId('terrain'); const romania = {lat: 45.9432, lng: 24.9668}; const marker = new google.maps.Marker({ position: romania, icon: { url:'http://maps.google.com/mapfiles/kml/shapes/homegardenbusiness.png', size: new google.maps.Size(32, 32), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(0, 32), scaledSize: new google.maps.Size(32, 32), }, map: map, title: 'My Home Country', animation: google.maps.Animation.DROP, }); const infoWindow = new google.maps.InfoWindow({ content: 'This is my home country', maxWidth: 150 }); marker.addListener('click', function () { if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); } }); infoWindow.open(map, marker); }
function createMap() { const map = new google.maps.Map( document.getElementById('map'), { center: {lat: 47.889019, lng: 3.7831301}, zoom: 5, styles:[ { "elementType": "geometry", "stylers": [{"color": "#1d2c4d"}] }, { "elementType": "labels.text.fill", "stylers": [{"color": "#8ec3b9"}] }, { "elementType": "labels.text.stroke", "stylers": [{"color": "#1a3646"}] }, { "featureType": "administrative.country", "elementType": "geometry.stroke", "stylers": [{"color": "#7faa09"}, {"visibility": "on"}, {"weight": 1}, ] }, { "featureType": "administrative.country", "elementType": "labels.text.stroke", "stylers": [{"visibility": "on"}] }, { "featureType": "administrative.land_parcel", "elementType": "labels.text.fill", "stylers": [{"color": "#64779e" }] }, { "featureType": "administrative.province", "elementType": "geometry.stroke", "stylers": [{"color": "#4b6878"}] }, { "featureType": "landscape.man_made", "elementType": "geometry.stroke", "stylers": [{"color": "#334e87"}] }, { "featureType": "landscape.natural", "elementType": "geometry", "stylers": [{"color": "#023e58"}] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{"color": "#283d6a"}] }, { "featureType": "poi", "elementType": "labels.text.fill", "stylers": [{"color": "#6f9ba5"}] }, { "featureType": "poi", "elementType": "labels.text.stroke", "stylers": [{"color": "#1d2c4d"}] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{"color": "#023e58"}] }, { "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [{"color": "#3C7680"}] }, { "featureType": "road", "elementType": "geometry", "stylers": [{"color": "#304a7d"}] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{"color": "#98a5be"}] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [{"color": "#1d2c4d"}] }, { "featureType": "road.highway", "elementType": "geometry", "stylers": [{"color": "#2c6675"}] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [ {"color": "#255763"}] }, { "featureType": "road.highway", "elementType": "labels.text.fill", "stylers": [{"color": "#b0d5ce"}] }, { "featureType": "road.highway", "elementType": "labels.text.stroke", "stylers": [{"color": "#023e58"}] }, { "featureType": "transit", "elementType": "labels.text.fill", "stylers": [{"color": "#98a5be"}] }, { "featureType": "transit", "elementType": "labels.text.stroke", "stylers": [{"color": "#1d2c4d"}] }, { "featureType": "transit.line", "elementType": "geometry.fill", "stylers": [{"color": "#283d6a"}] }, { "featureType": "transit.station", "elementType": "geometry", "stylers": [{"color": "#3a4762"}] }, { "featureType": "water", "elementType": "geometry", "stylers": [{"color": "#0e1626"}] }, { "featureType": "water", "elementType": "labels.text.fill", "stylers": [{"color": "#4e6d70"}] } ] }); map.setMapTypeId('terrain'); const romania = {lat: 45.9432, lng: 24.9668}; const marker = new google.maps.Marker({ position: romania, icon: { url:'http://maps.google.com/mapfiles/kml/shapes/homegardenbusiness.png', size: new google.maps.Size(32, 32), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(0, 32), scaledSize: new google.maps.Size(32, 32), }, map: map, title: 'My Home Country', animation: google.maps.Animation.DROP, }); const infoWindow = new google.maps.InfoWindow({ content: 'This is my home country', maxWidth: 150 }); marker.addListener('click', function () { if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); } }); infoWindow.open(map, marker); }
JavaScript
function safelyCallComponentWillUnmount(current, instance) { if (__DEV__) { invokeGuardedCallback( null, callComponentWillUnmountWithTimer, null, current, instance, ); if (hasCaughtError()) { const unmountError = clearCaughtError(); captureError(current, unmountError); } } else { try { callComponentWillUnmountWithTimer(current, instance); } catch (unmountError) { captureError(current, unmountError); } } }
function safelyCallComponentWillUnmount(current, instance) { if (__DEV__) { invokeGuardedCallback( null, callComponentWillUnmountWithTimer, null, current, instance, ); if (hasCaughtError()) { const unmountError = clearCaughtError(); captureError(current, unmountError); } } else { try { callComponentWillUnmountWithTimer(current, instance); } catch (unmountError) { captureError(current, unmountError); } } }
JavaScript
function editIncomeClicked() { const userIncome = $('#income') .val() .trim(); const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); renderModal('Edit Income', userId, { income: userIncome }); }
function editIncomeClicked() { const userIncome = $('#income') .val() .trim(); const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); renderModal('Edit Income', userId, { income: userIncome }); }
JavaScript
function editCategoryClicked() { const editId = parseInt($(this).attr('editId')); // get the edit button id const categoryValue = $(this).attr('categoryValue'); // get the category text const goalValue = parseFloat($(this).attr('goalValue')); // get the goal value const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); renderModal('Edit Category', userId, { categoryValue, goalValue, editId }); }
function editCategoryClicked() { const editId = parseInt($(this).attr('editId')); // get the edit button id const categoryValue = $(this).attr('categoryValue'); // get the category text const goalValue = parseFloat($(this).attr('goalValue')); // get the goal value const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); renderModal('Edit Category', userId, { categoryValue, goalValue, editId }); }
JavaScript
function editExpenseClicked() { const editId = parseInt($(this).attr('editId')); // get the edit button id const description = $(`.description-${editId}`).attr('value'); // get the description const amount = parseFloat($(`.amount-${editId}`).attr('value')); // get the amount const date = $(`.date-${editId}`).attr('value'); // get the amount const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); const categoryValue = $(this).attr('categoryValue'); // get the category text renderModal('Edit Expense', userId, { description, amount, date, categoryValue, editId }); }
function editExpenseClicked() { const editId = parseInt($(this).attr('editId')); // get the edit button id const description = $(`.description-${editId}`).attr('value'); // get the description const amount = parseFloat($(`.amount-${editId}`).attr('value')); // get the amount const date = $(`.date-${editId}`).attr('value'); // get the amount const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); const categoryValue = $(this).attr('categoryValue'); // get the category text renderModal('Edit Expense', userId, { description, amount, date, categoryValue, editId }); }
JavaScript
function deleteCategoryClicked() { const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); const deleteId = parseInt($(this).attr('deleteId')); renderConfirmationModal('Are you sure you want to delete the category?', () => { deleteCategory(userId, deleteId); }); }
function deleteCategoryClicked() { const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); const deleteId = parseInt($(this).attr('deleteId')); renderConfirmationModal('Are you sure you want to delete the category?', () => { deleteCategory(userId, deleteId); }); }
JavaScript
function deleteExpenseClicked() { const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); const deleteId = parseInt($(this).attr('deleteId')); renderConfirmationModal('Are you sure you want to delete the Expense?', () => { deleteExpense(userId, deleteId); }); }
function deleteExpenseClicked() { const userId = parseInt( window.location.href.split('/')[window.location.href.split('/').length - 2] ); const deleteId = parseInt($(this).attr('deleteId')); renderConfirmationModal('Are you sure you want to delete the Expense?', () => { deleteExpense(userId, deleteId); }); }
JavaScript
static search(props, state, seekIndex, expand, singleSearch) { const { onChange, getNodeKey, searchFinishCallback, searchQuery, searchMethod, searchFocusOffset, onlyExpandSearchedNodes, } = props; const { instanceProps } = state; // Skip search if no conditions are specified if (!searchQuery && !searchMethod) { if (searchFinishCallback) { searchFinishCallback([]); } return { searchMatches: [] }; } const newState = {}; // if onlyExpandSearchedNodes collapse the tree and search const { treeData: expandedTreeData, matches: searchMatches } = find({ getNodeKey, treeData: onlyExpandSearchedNodes ? toggleExpandedForAll({ treeData: instanceProps.treeData, expanded: false, }) : instanceProps.treeData, searchQuery, searchMethod: searchMethod || defaultSearchMethod, searchFocusOffset, expandAllMatchPaths: expand && !singleSearch, expandFocusMatchPaths: !!expand, }); // Update the tree with data leaving all paths leading to matching nodes open if (expand) { newState.ignoreOneTreeUpdate = true; // Prevents infinite loop onChange(expandedTreeData); } if (searchFinishCallback) { searchFinishCallback(searchMatches); } let searchFocusTreeIndex = null; if ( seekIndex && searchFocusOffset !== null && searchFocusOffset < searchMatches.length ) { searchFocusTreeIndex = searchMatches[searchFocusOffset].treeIndex; } newState.searchMatches = searchMatches; newState.searchFocusTreeIndex = searchFocusTreeIndex; return newState; }
static search(props, state, seekIndex, expand, singleSearch) { const { onChange, getNodeKey, searchFinishCallback, searchQuery, searchMethod, searchFocusOffset, onlyExpandSearchedNodes, } = props; const { instanceProps } = state; // Skip search if no conditions are specified if (!searchQuery && !searchMethod) { if (searchFinishCallback) { searchFinishCallback([]); } return { searchMatches: [] }; } const newState = {}; // if onlyExpandSearchedNodes collapse the tree and search const { treeData: expandedTreeData, matches: searchMatches } = find({ getNodeKey, treeData: onlyExpandSearchedNodes ? toggleExpandedForAll({ treeData: instanceProps.treeData, expanded: false, }) : instanceProps.treeData, searchQuery, searchMethod: searchMethod || defaultSearchMethod, searchFocusOffset, expandAllMatchPaths: expand && !singleSearch, expandFocusMatchPaths: !!expand, }); // Update the tree with data leaving all paths leading to matching nodes open if (expand) { newState.ignoreOneTreeUpdate = true; // Prevents infinite loop onChange(expandedTreeData); } if (searchFinishCallback) { searchFinishCallback(searchMatches); } let searchFocusTreeIndex = null; if ( seekIndex && searchFocusOffset !== null && searchFocusOffset < searchMatches.length ) { searchFocusTreeIndex = searchMatches[searchFocusOffset].treeIndex; } newState.searchMatches = searchMatches; newState.searchFocusTreeIndex = searchFocusTreeIndex; return newState; }
JavaScript
function GetResults(term) { $('input.dirty').val(''); //clear input field GetSearch.getWiki(term).success(function(data) { Render(data); }); }
function GetResults(term) { $('input.dirty').val(''); //clear input field GetSearch.getWiki(term).success(function(data) { Render(data); }); }
JavaScript
function generateBoard(state) { var q = createEmptyBoard(state, DISABLED); state.board = q; addRandomOnToEachRow(state, q); flipOnsToOffsRandomly(state, q); fillGapsInBoardRandomly(state, q); ensureEachRowHasMoreThanOneButton(state, q); flipColumnsRandomly(state, q); return q; }
function generateBoard(state) { var q = createEmptyBoard(state, DISABLED); state.board = q; addRandomOnToEachRow(state, q); flipOnsToOffsRandomly(state, q); fillGapsInBoardRandomly(state, q); ensureEachRowHasMoreThanOneButton(state, q); flipColumnsRandomly(state, q); return q; }
JavaScript
function emptyInput(target) { if (target=="rule"){ if(document.getElementById("NameRule").value==="" || document.getElementById("ruleField").value==="" || document.getElementById("ruleValue").value==="") { document.getElementById('send').disabled = true; } else { document.getElementById('send').disabled = false; } } else{ if(document.getElementById("ruleNum").value==="" || document.getElementById("repeated").value==="" || document.getElementById("TIMEOUT").value==="" || document.getElementById("eventName").value==="") { document.getElementById('send2').disabled = true; } else { document.getElementById('send2').disabled = false; } } }
function emptyInput(target) { if (target=="rule"){ if(document.getElementById("NameRule").value==="" || document.getElementById("ruleField").value==="" || document.getElementById("ruleValue").value==="") { document.getElementById('send').disabled = true; } else { document.getElementById('send').disabled = false; } } else{ if(document.getElementById("ruleNum").value==="" || document.getElementById("repeated").value==="" || document.getElementById("TIMEOUT").value==="" || document.getElementById("eventName").value==="") { document.getElementById('send2').disabled = true; } else { document.getElementById('send2').disabled = false; } } }
JavaScript
function introspect (text) { return new Promise(function (resolve, reject) { try { var astDocument = parse(text) var schema = buildASTSchema(astDocument) graphql(schema, graphqlviz.query) .then(function (data) { resolve(data) }) .catch(function (e) { reject('Fatal error, exiting.') fatal(e, text) }) } catch (e) { reject('Fatal error, exiting.') fatal(e, text) } }) }
function introspect (text) { return new Promise(function (resolve, reject) { try { var astDocument = parse(text) var schema = buildASTSchema(astDocument) graphql(schema, graphqlviz.query) .then(function (data) { resolve(data) }) .catch(function (e) { reject('Fatal error, exiting.') fatal(e, text) }) } catch (e) { reject('Fatal error, exiting.') fatal(e, text) } }) }
JavaScript
function showStartQuiz() { $("#content").show(); $("#questiondiv").hide(); $("#scorediv").hide(); $('#highscoresdiv').hide(); }
function showStartQuiz() { $("#content").show(); $("#questiondiv").hide(); $("#scorediv").hide(); $('#highscoresdiv').hide(); }
JavaScript
function showQuestion() { $("#content").hide(); $("#questiondiv").show(); $("#scorediv").hide(); $('#highscoresdiv').hide(); }
function showQuestion() { $("#content").hide(); $("#questiondiv").show(); $("#scorediv").hide(); $('#highscoresdiv').hide(); }
JavaScript
function showSubmitScore(timeScore) { $("#content").hide(); $("#questiondiv").hide(); $("#scorediv").show(); $('#highscoresdiv').hide(); $('#score').text(timeScore); }
function showSubmitScore(timeScore) { $("#content").hide(); $("#questiondiv").hide(); $("#scorediv").show(); $('#highscoresdiv').hide(); $('#score').text(timeScore); }
JavaScript
function determineArguments(argv) { var result = { expressions: [], locations: [] }; argv.forEach(function(value, index, array) { if(value.indexOf('=') > -1) { var parts = value.split('='); result.expressions.push({ match: parts[0], value: parts[1] }); } else { result.locations.push(value); } }); return result; }
function determineArguments(argv) { var result = { expressions: [], locations: [] }; argv.forEach(function(value, index, array) { if(value.indexOf('=') > -1) { var parts = value.split('='); result.expressions.push({ match: parts[0], value: parts[1] }); } else { result.locations.push(value); } }); return result; }
JavaScript
function makeFileList(locations) { var result = []; locations.forEach(function(location) { pathutils.walkFiles(path.resolve(location), function(err, file) { result.push(file); }); }); return result; }
function makeFileList(locations) { var result = []; locations.forEach(function(location) { pathutils.walkFiles(path.resolve(location), function(err, file) { result.push(file); }); }); return result; }
JavaScript
function increaseVaultCube1() { if (vm.matchParts.vaultCube - 8 <= 0) { vm.matchParts.vaultCube += 1; } }
function increaseVaultCube1() { if (vm.matchParts.vaultCube - 8 <= 0) { vm.matchParts.vaultCube += 1; } }
JavaScript
toggle (visible) { this.visible = visible===undefined ? !this.visible : visible; this.elements.forEach(elem => { elem.show(this.visible); }); }
toggle (visible) { this.visible = visible===undefined ? !this.visible : visible; this.elements.forEach(elem => { elem.show(this.visible); }); }
JavaScript
function repeatUntil(fn, interval, promise) { let i = 0; const intervalId = setInterval(() => { fn(i); i += 1; }, interval); promise.then(() => clearInterval(intervalId)); return promise; }
function repeatUntil(fn, interval, promise) { let i = 0; const intervalId = setInterval(() => { fn(i); i += 1; }, interval); promise.then(() => clearInterval(intervalId)); return promise; }
JavaScript
function wait(duration, defaultValue = null) { return new Promise(resolve => { setTimeout(() => resolve(defaultValue || duration), duration); }); }
function wait(duration, defaultValue = null) { return new Promise(resolve => { setTimeout(() => resolve(defaultValue || duration), duration); }); }
JavaScript
function recurseThroughFileTree(directory) { //Loop through files and fill files property array //fs.readdir reads the contents of a directory //entire directory exists at directory.path fs.readdir(directory.path, (err, files) => { //I'm not sure what the purpose of pending is pending += files.length; //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } //files is an array of files that exist in the directory passed to the fs.readdir method //forEach is used to iterate over that array files.forEach((file) => { //filePath uses path.join() to join the path and file names together const filePath = path.join(directory.path, file); //fs.stat is a method that checks for file details associated with the inputted file //if status is good, it's details are available at the 'stats' variable fs.stat(filePath, (err, stats) => { if (err) { //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } } //checks if stats is true or truthy & stats.isFile() resolves to true if (stats && stats.isFile()) { //insertSorted pushes an object into the directory.files array //object pushed into the array has the following parameters: //path, type, name, ext, id insertSorted(new File(filePath, file, getFileExt), directory.files); //checks if the filePath is the same as the resolved value as path.join(...) & if the file contains the text of webpack.config.js if (filePath === path.join(projInfo.rootPath, file) && file.search(/webpack.config.js/) !== -1) { //if it does, then we invoke the readFile method to access the data in the file fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => { //created a regExp to check for a pattern that matches entry... const regExp = new RegExp('entry(.*?),', 'g'); //file is stringified and then searched for the match assigned to the regExp let entry = JSON.stringify(data).match(regExp); //????? let reactEntry = String(entry[0].split('\'')[1]); //reactEntry property inside of the projInfo object is updated to the resolved value of path.join(...) projInfo.reactEntry = path.join(projInfo.rootPath, reactEntry); }) } //look for index.html not in node_modules, get path if (!projInfo.htmlPath && filePath.search(/.*node\_modules.*/) === -1 && file.search(/.*index\.html/) !== -1) { projInfo.htmlPath = filePath; } //look for package.json and see if webpack is installed and react-dev-server is installed else if (!projInfo.webpack && file.search(/package.json/) !== -1 && filePath === path.join(projInfo.rootPath, file)) { //if projInfo.webpack is false, the file contains package.json, and the filePath matches the resolved value of projInfo.rootPath & file, readFile is invoked and passed the filePath variable fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => { //data is parsed into a JS object data = JSON.parse(data); //checks if the parsed object has a property of react-scripts if (data.dependencies['react-scripts']) { //if it does, the property of devServerScript is reassigned to 'start' projInfo.devServerScript = 'start', //if it does, the property of CRA is reassigned to 'true' projInfo.CRA = true; //checks if the parsed object has a property of webpack-dev-server } else if (data.devDependencies['webpack-dev-server']) { //if it does, the property of devServerScript is reassigned to 'run dev-server' projInfo.devServerScript = 'run dev-server'; // console.log(projInfo.devServerScript, '$$$') } //checks if data.main is true or truthy if (data.main) { //if it is, the mainEntry property is reassigned to the resolved value of path.join(...) projInfo.mainEntry = path.join(filePath, data.main); } }) } //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } } //checks if stats is true or truthy else if (stats) { //if it is, a const variable is declared and assigned the resolved value of invoking the Diretory constructor and passing it the filePath and file variables const subdirectory = new Directory(filePath, file); //put directories in front insertSorted(subdirectory, directory.subdirectories); recurseThroughFileTree(subdirectory); } }) }) }) }
function recurseThroughFileTree(directory) { //Loop through files and fill files property array //fs.readdir reads the contents of a directory //entire directory exists at directory.path fs.readdir(directory.path, (err, files) => { //I'm not sure what the purpose of pending is pending += files.length; //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } //files is an array of files that exist in the directory passed to the fs.readdir method //forEach is used to iterate over that array files.forEach((file) => { //filePath uses path.join() to join the path and file names together const filePath = path.join(directory.path, file); //fs.stat is a method that checks for file details associated with the inputted file //if status is good, it's details are available at the 'stats' variable fs.stat(filePath, (err, stats) => { if (err) { //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } } //checks if stats is true or truthy & stats.isFile() resolves to true if (stats && stats.isFile()) { //insertSorted pushes an object into the directory.files array //object pushed into the array has the following parameters: //path, type, name, ext, id insertSorted(new File(filePath, file, getFileExt), directory.files); //checks if the filePath is the same as the resolved value as path.join(...) & if the file contains the text of webpack.config.js if (filePath === path.join(projInfo.rootPath, file) && file.search(/webpack.config.js/) !== -1) { //if it does, then we invoke the readFile method to access the data in the file fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => { //created a regExp to check for a pattern that matches entry... const regExp = new RegExp('entry(.*?),', 'g'); //file is stringified and then searched for the match assigned to the regExp let entry = JSON.stringify(data).match(regExp); //????? let reactEntry = String(entry[0].split('\'')[1]); //reactEntry property inside of the projInfo object is updated to the resolved value of path.join(...) projInfo.reactEntry = path.join(projInfo.rootPath, reactEntry); }) } //look for index.html not in node_modules, get path if (!projInfo.htmlPath && filePath.search(/.*node\_modules.*/) === -1 && file.search(/.*index\.html/) !== -1) { projInfo.htmlPath = filePath; } //look for package.json and see if webpack is installed and react-dev-server is installed else if (!projInfo.webpack && file.search(/package.json/) !== -1 && filePath === path.join(projInfo.rootPath, file)) { //if projInfo.webpack is false, the file contains package.json, and the filePath matches the resolved value of projInfo.rootPath & file, readFile is invoked and passed the filePath variable fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => { //data is parsed into a JS object data = JSON.parse(data); //checks if the parsed object has a property of react-scripts if (data.dependencies['react-scripts']) { //if it does, the property of devServerScript is reassigned to 'start' projInfo.devServerScript = 'start', //if it does, the property of CRA is reassigned to 'true' projInfo.CRA = true; //checks if the parsed object has a property of webpack-dev-server } else if (data.devDependencies['webpack-dev-server']) { //if it does, the property of devServerScript is reassigned to 'run dev-server' projInfo.devServerScript = 'run dev-server'; // console.log(projInfo.devServerScript, '$$$') } //checks if data.main is true or truthy if (data.main) { //if it is, the mainEntry property is reassigned to the resolved value of path.join(...) projInfo.mainEntry = path.join(filePath, data.main); } }) } //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } } //checks if stats is true or truthy else if (stats) { //if it is, a const variable is declared and assigned the resolved value of invoking the Diretory constructor and passing it the filePath and file variables const subdirectory = new Directory(filePath, file); //put directories in front insertSorted(subdirectory, directory.subdirectories); recurseThroughFileTree(subdirectory); } }) }) }) }
JavaScript
_updateMarkers(message) { window.requestAnimationFrame(() => { const model = this.editor.getModel(); if (model && model.getVersionId() === message.data.version) { monaco.editor.setModelMarkers(model, 'eslint', message.data.markers); } }); }
_updateMarkers(message) { window.requestAnimationFrame(() => { const model = this.editor.getModel(); if (model && model.getVersionId() === message.data.version) { monaco.editor.setModelMarkers(model, 'eslint', message.data.markers); } }); }
JavaScript
_lintCode(code) { const model = this.editor.getModel(); monaco.editor.setModelMarkers(model, 'eslint', []); this._linterWorker.postMessage({ code, version: model.getVersionId(), }); }
_lintCode(code) { const model = this.editor.getModel(); monaco.editor.setModelMarkers(model, 'eslint', []); this._linterWorker.postMessage({ code, version: model.getVersionId(), }); }
JavaScript
_initializeFile(path) { const fs = window.require('fs'); const value = fs.readFileSync(path, { encoding: 'utf-8' }); let model = monaco.editor .getModels() .find(model => model.uri.path === path); if (model) { // If a model exists, we need to update it's value // This is needed because the content for the file might have been modified externally // Use `pushEditOperations` instead of `setValue` or `applyEdits` to preserve undo stack model.pushEditOperations( [], [ { range: model.getFullModelRange(), text: value, }, ] ); } else { model = monaco.editor.createModel( value, this._getLanguage(this.props.path), new monaco.Uri().with({ path }), ); model.updateOptions({ tabSize: 2, insertSpaces: true, }); } this.editor.setModel(model); return model; }
_initializeFile(path) { const fs = window.require('fs'); const value = fs.readFileSync(path, { encoding: 'utf-8' }); let model = monaco.editor .getModels() .find(model => model.uri.path === path); if (model) { // If a model exists, we need to update it's value // This is needed because the content for the file might have been modified externally // Use `pushEditOperations` instead of `setValue` or `applyEdits` to preserve undo stack model.pushEditOperations( [], [ { range: model.getFullModelRange(), text: value, }, ] ); } else { model = monaco.editor.createModel( value, this._getLanguage(this.props.path), new monaco.Uri().with({ path }), ); model.updateOptions({ tabSize: 2, insertSpaces: true, }); } this.editor.setModel(model); return model; }
JavaScript
_openFile(path) { let model = this._initializeFile(path); // Restore the editor state for the file const editorState = this.editorStates.get(path); if (editorState) { this.editor.restoreViewState(editorState); } // Bring browser focus to the editor text this.editor.focus(); // Subscribe to change in value so we can notify the parent this._subscription = model.onDidChangeContent(() => { const value = model.getValue(); this.props.onValueChange(value); this._lintCode(value); }); }
_openFile(path) { let model = this._initializeFile(path); // Restore the editor state for the file const editorState = this.editorStates.get(path); if (editorState) { this.editor.restoreViewState(editorState); } // Bring browser focus to the editor text this.editor.focus(); // Subscribe to change in value so we can notify the parent this._subscription = model.onDidChangeContent(() => { const value = model.getValue(); this.props.onValueChange(value); this._lintCode(value); }); }
JavaScript
_getLanguage(path) { if (path.includes('.')) { switch (path.split('.').pop()) { case 'js': return 'javascript'; case 'jsx': return 'javascript'; case 'ts': return 'typescript'; case 'json': return 'json'; case 'css': return 'css'; case 'html': return 'html'; case 'md': return 'markdown'; default: return undefined; } } }
_getLanguage(path) { if (path.includes('.')) { switch (path.split('.').pop()) { case 'js': return 'javascript'; case 'jsx': return 'javascript'; case 'ts': return 'typescript'; case 'json': return 'json'; case 'css': return 'css'; case 'html': return 'html'; case 'md': return 'markdown'; default: return undefined; } } }
JavaScript
renderChildrenTrees(children) { // children should be an array // children are the children components // if (children.length) should work if (children && children.length) { let renderArr = []; children.forEach(elem => { // push resolved value of invoking renderTree on each element renderArr.push(this.renderTree(elem)); }) // for every elemnt of the renderArr, we create a list items to 'tree_rows' unordered list return (<ul className="tree_rows">{renderArr}</ul>); } }
renderChildrenTrees(children) { // children should be an array // children are the children components // if (children.length) should work if (children && children.length) { let renderArr = []; children.forEach(elem => { // push resolved value of invoking renderTree on each element renderArr.push(this.renderTree(elem)); }) // for every elemnt of the renderArr, we create a list items to 'tree_rows' unordered list return (<ul className="tree_rows">{renderArr}</ul>); } }
JavaScript
renderStateProps(stateProps) { if (stateProps && Object.keys(stateProps).length) { let renderArr = []; // creates a list item of each element in stateProps object and pushes it to the renderArr array Object.keys(stateProps).forEach(key => { let value = typeof stateProps[key] === 'Object' ? stateProps[key] : JSON.stringify(stateProps[key]) renderArr.push(<li>{key} :{value}</li>) }) // here, we render each <li> in the renderArr array as children of an unordered list with a className of 'state_props' return ( <ul className="state_props"> {renderArr} </ul> ); } }
renderStateProps(stateProps) { if (stateProps && Object.keys(stateProps).length) { let renderArr = []; // creates a list item of each element in stateProps object and pushes it to the renderArr array Object.keys(stateProps).forEach(key => { let value = typeof stateProps[key] === 'Object' ? stateProps[key] : JSON.stringify(stateProps[key]) renderArr.push(<li>{key} :{value}</li>) }) // here, we render each <li> in the renderArr array as children of an unordered list with a className of 'state_props' return ( <ul className="state_props"> {renderArr} </ul> ); } }
JavaScript
renderChildProps(childProps) { // this conditional asks if childProps even exists if (childProps && childProps.length > 0) { let renderArr = []; // used forEach iterator to iterate over inputted childProps array childProps.forEach(elem => { // creates a list item of each element in childProps array and pushes it to the renderArr array renderArr.push(<li>{elem.name} <ul className="comp_props"> {Object.keys(elem.props).map(key => <li>{key}: <i>{elem.props[key]}</i></li> )} </ul> </li>); }); // here, we render each <li> in the renderArr array as children of an unordered list with a className of 'comp_refs' return ( <ul className="comp_refs"> {renderArr} </ul> ); } }
renderChildProps(childProps) { // this conditional asks if childProps even exists if (childProps && childProps.length > 0) { let renderArr = []; // used forEach iterator to iterate over inputted childProps array childProps.forEach(elem => { // creates a list item of each element in childProps array and pushes it to the renderArr array renderArr.push(<li>{elem.name} <ul className="comp_props"> {Object.keys(elem.props).map(key => <li>{key}: <i>{elem.props[key]}</i></li> )} </ul> </li>); }); // here, we render each <li> in the renderArr array as children of an unordered list with a className of 'comp_refs' return ( <ul className="comp_refs"> {renderArr} </ul> ); } }
JavaScript
renderTree(treeObj) { // we deconstructe the inputted treeObj to access these properties const { name, stateProps, childProps, children } = treeObj; //renderArr isn't used let renderArr = []; // here, we return the DOM for the Component Tree // this is the first element appened to the DOM // has a className of tree_row // inside of <li> w/ className of 'tree_row', there is an <input> element and a <label> element // when stateProps or childProps have lengths greater than 0, <div> element and <span> elements are added to the DOM // if stateProps has a length greater than 0, we appened React.Fragment that includes an <input> element, a <label> element, and the result of invoking renderStateProps w/ stateProps passed in as argument // if childProps has a length greater than 0, we appened React.Fragment that includes an <input> element, a <label> element, and the result of invoking renderchildProps w/ childProps passed in as argument // last element in <li> is the returned value of invoking renderChildrenTrees w/ children argument passed to it return ( <li key={'ct_node-li' + name} className="tree_row"> <input type="checkbox" id={'ct_node-npt_' + name} key={'ct_node-npt_' + name} /> <label key={'ct_node-lbl_' + name} id={'ct_node-lbl_' + name} className="tree_node" htmlFor={'ct_node-npt_' + name}>{name}</label> {(Object.keys(stateProps).length > 0 || childProps.length > 0) && ( <div className="props-container"> <span className="props-form"> {Object.keys(stateProps).length && ( <React.Fragment> <input type="checkbox" id={"ct_state-npt_" + name} /> <label htmlFor={"ct_state-npt_" + name}>[state_props] ({Object.keys(stateProps).length})</label><br /> {this.renderStateProps(stateProps)} </React.Fragment>)} {childProps.length > 0 && ( <React.Fragment> <input type="checkbox" id={"ct_child-npt_" + name} /> <label htmlFor={"ct_child-npt_" + name}>[comp_props] ({childProps.length})</label><br /> {this.renderChildProps(childProps)} </React.Fragment>)} </span> </div> )} {this.renderChildrenTrees(children)} </li> ); }
renderTree(treeObj) { // we deconstructe the inputted treeObj to access these properties const { name, stateProps, childProps, children } = treeObj; //renderArr isn't used let renderArr = []; // here, we return the DOM for the Component Tree // this is the first element appened to the DOM // has a className of tree_row // inside of <li> w/ className of 'tree_row', there is an <input> element and a <label> element // when stateProps or childProps have lengths greater than 0, <div> element and <span> elements are added to the DOM // if stateProps has a length greater than 0, we appened React.Fragment that includes an <input> element, a <label> element, and the result of invoking renderStateProps w/ stateProps passed in as argument // if childProps has a length greater than 0, we appened React.Fragment that includes an <input> element, a <label> element, and the result of invoking renderchildProps w/ childProps passed in as argument // last element in <li> is the returned value of invoking renderChildrenTrees w/ children argument passed to it return ( <li key={'ct_node-li' + name} className="tree_row"> <input type="checkbox" id={'ct_node-npt_' + name} key={'ct_node-npt_' + name} /> <label key={'ct_node-lbl_' + name} id={'ct_node-lbl_' + name} className="tree_node" htmlFor={'ct_node-npt_' + name}>{name}</label> {(Object.keys(stateProps).length > 0 || childProps.length > 0) && ( <div className="props-container"> <span className="props-form"> {Object.keys(stateProps).length && ( <React.Fragment> <input type="checkbox" id={"ct_state-npt_" + name} /> <label htmlFor={"ct_state-npt_" + name}>[state_props] ({Object.keys(stateProps).length})</label><br /> {this.renderStateProps(stateProps)} </React.Fragment>)} {childProps.length > 0 && ( <React.Fragment> <input type="checkbox" id={"ct_child-npt_" + name} /> <label htmlFor={"ct_child-npt_" + name}>[comp_props] ({childProps.length})</label><br /> {this.renderChildProps(childProps)} </React.Fragment>)} </span> </div> )} {this.renderChildrenTrees(children)} </li> ); }
JavaScript
render() { let componentTree = []; return ( <ul className="tree"> {this.renderTree(this.props.componentTreeObj)} </ul> ); }
render() { let componentTree = []; return ( <ul className="tree"> {this.renderTree(this.props.componentTreeObj)} </ul> ); }
JavaScript
function digStateInBlockStatement(obj) { if (obj.type !== 'BlockStatement') return; let ret = {}; obj.body.forEach((element) => { if (element.type === "ExpressionStatement" && element.expression.type === "AssignmentExpression") if (element.expression.left.property.name === 'state') { if (element.expression.right.type === "ObjectExpression"){ element.expression.right.properties.forEach(elem => { // ret[elem.key.name] = elem.value.value; ret[elem.key.name] = parseNestedObjects(elem) // console.log('parseNestedObjects return value', parseNestedObjects(elem)) }); } } }); // console.log('return' ,ret) return ret; }
function digStateInBlockStatement(obj) { if (obj.type !== 'BlockStatement') return; let ret = {}; obj.body.forEach((element) => { if (element.type === "ExpressionStatement" && element.expression.type === "AssignmentExpression") if (element.expression.left.property.name === 'state') { if (element.expression.right.type === "ObjectExpression"){ element.expression.right.properties.forEach(elem => { // ret[elem.key.name] = elem.value.value; ret[elem.key.name] = parseNestedObjects(elem) // console.log('parseNestedObjects return value', parseNestedObjects(elem)) }); } } }); // console.log('return' ,ret) return ret; }
JavaScript
function grabAttr(arrOfAttr) { return arrOfAttr.reduce((acc, curr) => { if (curr.value.type === 'JSXExpressionContainer') { if (curr.value.expression.type === 'ArrowFunctionExpression' || curr.value.expression.type === 'FunctionExpression') { if(curr.value.expression.body.body) { acc[curr.name.name] = curr.value.expression.body.body[0].expression.callee.name } else { acc[curr.name.name] = curr.value.expression.body.callee.name } } else if (curr.value.expression.type === 'Literal') { acc[curr.name.name] = curr.value.expression.value; } else if (curr.value.expression.type === 'MemberExpression') { acc[curr.name.name] = curr.value.expression.property.name; } else if (curr.value.expression.type === 'ConditionalExpression') { let condition, consequent, alternate; if(curr.value.expression.test.type === 'MemberExpression') { condition = curr.value.expression.test.property.name; } else{ condition = curr.value.expression.test.name; } if(curr.value.expression.consequent.type === 'MemberExpression') { consequent = curr.value.expression.consequent.property.name; } else { consequent = curr.value.expression.consequent.name; } if(curr.value.expression.alternate.type === 'MemberExpression') { alternate = curr.value.expression.alternate.property.name; } else{ alternate = curr.value.expression.consequent.name; } acc[curr.name.name + 'True'] = {condition: condition, value:consequent}; acc[curr.name.name + 'False'] = {condition: condition, value: alternate} } else { acc[curr.name.name] = curr.value.expression.name; } } else { acc[curr.name.name] = curr.value.value; } return acc; },{}) }
function grabAttr(arrOfAttr) { return arrOfAttr.reduce((acc, curr) => { if (curr.value.type === 'JSXExpressionContainer') { if (curr.value.expression.type === 'ArrowFunctionExpression' || curr.value.expression.type === 'FunctionExpression') { if(curr.value.expression.body.body) { acc[curr.name.name] = curr.value.expression.body.body[0].expression.callee.name } else { acc[curr.name.name] = curr.value.expression.body.callee.name } } else if (curr.value.expression.type === 'Literal') { acc[curr.name.name] = curr.value.expression.value; } else if (curr.value.expression.type === 'MemberExpression') { acc[curr.name.name] = curr.value.expression.property.name; } else if (curr.value.expression.type === 'ConditionalExpression') { let condition, consequent, alternate; if(curr.value.expression.test.type === 'MemberExpression') { condition = curr.value.expression.test.property.name; } else{ condition = curr.value.expression.test.name; } if(curr.value.expression.consequent.type === 'MemberExpression') { consequent = curr.value.expression.consequent.property.name; } else { consequent = curr.value.expression.consequent.name; } if(curr.value.expression.alternate.type === 'MemberExpression') { alternate = curr.value.expression.alternate.property.name; } else{ alternate = curr.value.expression.consequent.name; } acc[curr.name.name + 'True'] = {condition: condition, value:consequent}; acc[curr.name.name + 'False'] = {condition: condition, value: alternate} } else { acc[curr.name.name] = curr.value.expression.name; } } else { acc[curr.name.name] = curr.value.value; } return acc; },{}) }
JavaScript
function CacheMap(manager) { this.manager = manager; this._inner = {}; this._lastRemovedEntries = {}; this.updateTicks = 0; this.lastCheckTTL = 0; this.delayCheckTTL = 100.0; this.updateSeconds = Date.now(); }
function CacheMap(manager) { this.manager = manager; this._inner = {}; this._lastRemovedEntries = {}; this.updateTicks = 0; this.lastCheckTTL = 0; this.delayCheckTTL = 100.0; this.updateSeconds = Date.now(); }
JavaScript
function loadSuccess() { var guest = $(".editable[data-name='name'][data-value='Guest']"); guest.editable("disable"); $("input:radio.check_head:checked").each(function() { $(this).prop('checked', false); }); $(".header_select").each(function() { $(this).prop("selectedIndex", 0); }); $(".header_select").each(function() { $(this).prop("selectedIndex", 0); }); $('.multi_selector').selectpicker('deselectAll'); $('.multi_selector').selectpicker('refresh'); $(".editable[data-name='locale'][data-pk='"+guest.data("pk")+"']").editable("disable"); $(".editable[data-name='locale'][data-pk='"+guest.data("pk")+"']").hide(); $("input[data-name='admin_role'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $("input[data-name='passwd_role'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $("input[data-name='edit_shelf_role'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $("input[data-name='sidebar_read_and_unread'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $(".user-remove[data-pk='"+guest.data("pk")+"']").hide(); }
function loadSuccess() { var guest = $(".editable[data-name='name'][data-value='Guest']"); guest.editable("disable"); $("input:radio.check_head:checked").each(function() { $(this).prop('checked', false); }); $(".header_select").each(function() { $(this).prop("selectedIndex", 0); }); $(".header_select").each(function() { $(this).prop("selectedIndex", 0); }); $('.multi_selector').selectpicker('deselectAll'); $('.multi_selector').selectpicker('refresh'); $(".editable[data-name='locale'][data-pk='"+guest.data("pk")+"']").editable("disable"); $(".editable[data-name='locale'][data-pk='"+guest.data("pk")+"']").hide(); $("input[data-name='admin_role'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $("input[data-name='passwd_role'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $("input[data-name='edit_shelf_role'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $("input[data-name='sidebar_read_and_unread'][data-pk='"+guest.data("pk")+"']").prop("disabled", true); $(".user-remove[data-pk='"+guest.data("pk")+"']").hide(); }
JavaScript
function init(logType) { var d = document.getElementById("renderer"); d.innerHTML = "loading ..."; $.ajax({ url: window.location.pathname + "/../../ajax/log/" + logType, datatype: "text", cache: false }) .done( function(data) { var text; $("#renderer").text(""); text = (data).split("\n"); // console.log(text.length); for (var i = 0; i < text.length; i++) { $("#renderer").append( "<div>" + _sanitize(text[i]) + "</div>" ); } }); }
function init(logType) { var d = document.getElementById("renderer"); d.innerHTML = "loading ..."; $.ajax({ url: window.location.pathname + "/../../ajax/log/" + logType, datatype: "text", cache: false }) .done( function(data) { var text; $("#renderer").text(""); text = (data).split("\n"); // console.log(text.length); for (var i = 0; i < text.length; i++) { $("#renderer").append( "<div>" + _sanitize(text[i]) + "</div>" ); } }); }
JavaScript
function toggleFullscreen(elem) { if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) { if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } }
function toggleFullscreen(elem) { if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) { if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } }
JavaScript
function mapRawResponseToDevicesResponse(response) { // Rename properties on the server response utils.renameProperties(response, MESSAGING_DEVICES_RESPONSE_KEYS_MAP); if ('results' in response) { response.results.forEach(function (messagingDeviceResult) { utils.renameProperties(messagingDeviceResult, MESSAGING_DEVICE_RESULT_KEYS_MAP); // Map the FCM server's error strings to actual error objects. if ('error' in messagingDeviceResult) { var newError = error_1.FirebaseMessagingError.fromServerError(messagingDeviceResult.error, /* message */ undefined, messagingDeviceResult.error); messagingDeviceResult.error = newError; } }); } return response; }
function mapRawResponseToDevicesResponse(response) { // Rename properties on the server response utils.renameProperties(response, MESSAGING_DEVICES_RESPONSE_KEYS_MAP); if ('results' in response) { response.results.forEach(function (messagingDeviceResult) { utils.renameProperties(messagingDeviceResult, MESSAGING_DEVICE_RESULT_KEYS_MAP); // Map the FCM server's error strings to actual error objects. if ('error' in messagingDeviceResult) { var newError = error_1.FirebaseMessagingError.fromServerError(messagingDeviceResult.error, /* message */ undefined, messagingDeviceResult.error); messagingDeviceResult.error = newError; } }); } return response; }
JavaScript
function mapRawResponseToDeviceGroupResponse(response) { // Rename properties on the server response utils.renameProperties(response, MESSAGING_DEVICE_GROUP_RESPONSE_KEYS_MAP); // Add the 'failedRegistrationTokens' property if it does not exist on the response, which // it won't when the 'failureCount' property has a value of 0) response.failedRegistrationTokens = response.failedRegistrationTokens || []; return response; }
function mapRawResponseToDeviceGroupResponse(response) { // Rename properties on the server response utils.renameProperties(response, MESSAGING_DEVICE_GROUP_RESPONSE_KEYS_MAP); // Add the 'failedRegistrationTokens' property if it does not exist on the response, which // it won't when the 'failureCount' property has a value of 0) response.failedRegistrationTokens = response.failedRegistrationTokens || []; return response; }
JavaScript
function destructivelyUpdateObject(current, diff) { if (current === undefined || !(current instanceof Object)) { throw new Error('wrong call'); } angular.forEach(diff, function (val, key) { if (val === null) { delete current[key]; } else if (typeof val !== 'object') { current[key] = val; } else { // diff[key] is Object if (typeof current[key] !== 'object' || current[key] === null) { current[key] = val; } else { var hasPrice = (current[key].price !== undefined); var oldPrice; if (hasPrice) { oldPrice = current[key].price; } destructivelyUpdateObject(current[key], val); if (hasPrice) { current[key].price_change = (val.price === oldPrice) ? null : (oldPrice < val.price) * 2 - 1; } } } }); }
function destructivelyUpdateObject(current, diff) { if (current === undefined || !(current instanceof Object)) { throw new Error('wrong call'); } angular.forEach(diff, function (val, key) { if (val === null) { delete current[key]; } else if (typeof val !== 'object') { current[key] = val; } else { // diff[key] is Object if (typeof current[key] !== 'object' || current[key] === null) { current[key] = val; } else { var hasPrice = (current[key].price !== undefined); var oldPrice; if (hasPrice) { oldPrice = current[key].price; } destructivelyUpdateObject(current[key], val); if (hasPrice) { current[key].price_change = (val.price === oldPrice) ? null : (oldPrice < val.price) * 2 - 1; } } } }); }
JavaScript
function updateSubscribers(data) { angular.forEach(data.data, function (subDataDiff, subId) { var subscription = subscriptions[subId]; if (undefined !== subscription && undefined !== subscription.callback) { destructivelyUpdateObject(subscription.data, {data: subDataDiff}); // subscription.callback(subscription.data.data); } else if (subscriptions[subId] === undefined) { console.log('got update for unknown subscription', subId, 'trying to unsubscribe'); Zergling.unsubscribe(subId); } }); }
function updateSubscribers(data) { angular.forEach(data.data, function (subDataDiff, subId) { var subscription = subscriptions[subId]; if (undefined !== subscription && undefined !== subscription.callback) { destructivelyUpdateObject(subscription.data, {data: subDataDiff}); // subscription.callback(subscription.data.data); } else if (subscriptions[subId] === undefined) { console.log('got update for unknown subscription', subId, 'trying to unsubscribe'); Zergling.unsubscribe(subId); } }); }
JavaScript
function whatsUp() { if (session) { getSession() .then(function (session_id) { var data = { 'command': 'whats_up' }; var headers = { 'swarm-session': session_id }; return $http.post(getLongPollUrl(), JSON.stringify(data), { 'headers': headers }); }) .then(function (response) { handleSubscriptionResponse(response); $timeout(whatsUp, 500); })['catch'](function (reason) { console.log(reason); if (reason.status === 404) { session = null } $timeout(whatsUp, 5000); }); } else { $timeout(whatsUp, 1000); } }
function whatsUp() { if (session) { getSession() .then(function (session_id) { var data = { 'command': 'whats_up' }; var headers = { 'swarm-session': session_id }; return $http.post(getLongPollUrl(), JSON.stringify(data), { 'headers': headers }); }) .then(function (response) { handleSubscriptionResponse(response); $timeout(whatsUp, 500); })['catch'](function (reason) { console.log(reason); if (reason.status === 404) { session = null } $timeout(whatsUp, 5000); }); } else { $timeout(whatsUp, 1000); } }
JavaScript
handleBeforeRequest({requestId, url, method, frameId, tabId, type, timeStamp, originUrl, documentUrl}) { try { if (this.events.has(requestId)) { // redirect (TODO: test) return; } // tabId = -1 means the request is from an extension / internal / etc and this is something that // should be filtered. // However if the originUrl or documentUrl matches the URL to our main script-env file, it means // that the request was triggered by a fetch() request in the script (in the Worker) if (tabId === -1 && originUrl !== CORE_SCRIPT_ENV_URL && documentUrl !== CORE_SCRIPT_ENV_URL) { this.events.set(requestId, Object.freeze({filtered: true})); return; } const parentEvent = this.runResult.timeEvent('http', timeStamp, null); this.events.set(requestId, Object.seal({ parentEvent, pendingSendRequestEvent: null, pendingReceiveResponseEvent: null, })); parentEvent.longTitle = `${method} ${url}`; parentEvent.shortTitle = `${method} ${urlForShortTitle(url)}`; parentEvent.setMetaData('url', url); parentEvent.setMetaData('finalUrl', url); parentEvent.setMetaData('method', method); parentEvent.setMetaData('frameId', frameId); parentEvent.setMetaData('tabId', tabId); parentEvent.setMetaData('type', type); parentEvent.setMetaData('originUrl', filterExtensionUrl(originUrl)); } catch (err) { log.error({err, requestId, url}, 'Error during webRequest.onBeforeRequest'); } }
handleBeforeRequest({requestId, url, method, frameId, tabId, type, timeStamp, originUrl, documentUrl}) { try { if (this.events.has(requestId)) { // redirect (TODO: test) return; } // tabId = -1 means the request is from an extension / internal / etc and this is something that // should be filtered. // However if the originUrl or documentUrl matches the URL to our main script-env file, it means // that the request was triggered by a fetch() request in the script (in the Worker) if (tabId === -1 && originUrl !== CORE_SCRIPT_ENV_URL && documentUrl !== CORE_SCRIPT_ENV_URL) { this.events.set(requestId, Object.freeze({filtered: true})); return; } const parentEvent = this.runResult.timeEvent('http', timeStamp, null); this.events.set(requestId, Object.seal({ parentEvent, pendingSendRequestEvent: null, pendingReceiveResponseEvent: null, })); parentEvent.longTitle = `${method} ${url}`; parentEvent.shortTitle = `${method} ${urlForShortTitle(url)}`; parentEvent.setMetaData('url', url); parentEvent.setMetaData('finalUrl', url); parentEvent.setMetaData('method', method); parentEvent.setMetaData('frameId', frameId); parentEvent.setMetaData('tabId', tabId); parentEvent.setMetaData('type', type); parentEvent.setMetaData('originUrl', filterExtensionUrl(originUrl)); } catch (err) { log.error({err, requestId, url}, 'Error during webRequest.onBeforeRequest'); } }
JavaScript
set timing(value) { if (!TimePeriod.isTimePeriod(value)) { throw illegalArgumentError('RunResult.timing: Value must be a TimePeriod'); } this[PRIVATE].timing = value; }
set timing(value) { if (!TimePeriod.isTimePeriod(value)) { throw illegalArgumentError('RunResult.timing: Value must be a TimePeriod'); } this[PRIVATE].timing = value; }
JavaScript
async transaction(id, body = null) { // await result.transaction('id', t => async { t.title = 'Fancy title'; await doStuff(); }); const transaction = new Transaction(id); if (this[PRIVATE].transactions.has(transaction.id)) { throw illegalArgumentError( `RunResult.transaction: A transaction with id "${transaction.id}" already exists. Transaction id's must be unique.`, ); } this[PRIVATE].transactions.set(transaction.id, transaction); let bodyReturn = undefined; let bodyError = null; if (body) { transaction.beginNow(); try { bodyReturn = await body(transaction); } catch (err) { bodyError = err; // todo add this transaction id to the error data } if (transaction.isPending) { transaction.endNow(); } transaction.error = bodyError; } if (bodyError && !transaction.eatError) { throw bodyError; } return bodyReturn; }
async transaction(id, body = null) { // await result.transaction('id', t => async { t.title = 'Fancy title'; await doStuff(); }); const transaction = new Transaction(id); if (this[PRIVATE].transactions.has(transaction.id)) { throw illegalArgumentError( `RunResult.transaction: A transaction with id "${transaction.id}" already exists. Transaction id's must be unique.`, ); } this[PRIVATE].transactions.set(transaction.id, transaction); let bodyReturn = undefined; let bodyError = null; if (body) { transaction.beginNow(); try { bodyReturn = await body(transaction); } catch (err) { bodyError = err; // todo add this transaction id to the error data } if (transaction.isPending) { transaction.endNow(); } transaction.error = bodyError; } if (bodyError && !transaction.eatError) { throw bodyError; } return bodyReturn; }
JavaScript
mergeJSONObject(runResultJsonObject) { if (runResultJsonObject) { // the object is null if the script quit prematurely const {mergeResults} = this[PRIVATE]; if (mergeResults.includes(runResultJsonObject)) { // a small check to avoid typo's throw illegalArgumentError('RunResult.mergeJSONObject: This object has already been merged'); } mergeResults.push(runResultJsonObject); } }
mergeJSONObject(runResultJsonObject) { if (runResultJsonObject) { // the object is null if the script quit prematurely const {mergeResults} = this[PRIVATE]; if (mergeResults.includes(runResultJsonObject)) { // a small check to avoid typo's throw illegalArgumentError('RunResult.mergeJSONObject: This object has already been merged'); } mergeResults.push(runResultJsonObject); } }
JavaScript
get duration() { if (!this.isComplete) { return NaN; } return this.end.diff(this.begin); }
get duration() { if (!this.isComplete) { return NaN; } return this.end.diff(this.begin); }
JavaScript
async call(nameOrOptions, ...params) { if ((typeof nameOrOptions !== 'string' && typeof nameOrOptions !== 'object') || nameOrOptions === null) { throw Error('ContentRPC#call(): First argument must be a string or an object with at least a "name" property'); } const name = typeof nameOrOptions === 'object' ? nameOrOptions.name : nameOrOptions; if (typeof name !== 'string') { throw Error('ContentRPC#call(): First argument must be a string or an object with at least a "name" property'); } const timeout = typeof nameOrOptions === 'object' && 'timeout' in nameOrOptions ? nameOrOptions.timeout : DEFAULT_CALL_TIMEOUT; const message = { rpcContext: this.rpcContext, method: name, params, }; if (this.contentToken) { message.rpcContentToken = this.contentToken; } // (A nice function name which we can easily recognise in stack traces) const contentRPC$call$sendMessage = async () => { try { return await this.browserRuntime.sendMessage('[email protected]', message, {}); } catch (err) { // note: errors thrown by the RPC method itself do not end up here, instead they end up in a "rejected" property // this way we can differentiate between errors raised by WebExt and our own RPC methods if (err.message === 'Could not establish connection. Receiving end does not exist.') { // This could happen because: // 1. The content script really did not attach a listener // 2. The message was just sent to the content script, however the frame was in the process of navigating somewhere else // and our content script on the next frame has not been loaded yet const newError = Error( `TabContentRPC: Remote Call "${name}" did not receive a response from the content script ` + '(there are no listeners)', ); newError.name = 'RPCNoResponse'; newError.cause = err; throw newError; } throw err; } }; const response = await asyncTimeout( contentRPC$call$sendMessage, { timeout, timeoutErrorName: CONTENT_RPC_TIMEOUT_ERROR, timeoutMessage: `ContentRPC: Remote Call "${name}" timed out after ${timeout}ms`, }, )(); if (!response) { const err = Error(`ContentRPC: Remote Call "${name}" did not receive a response from the background script`); err.name = 'RPCNoResponse'; throw err; } if ('error' in response) { throw createRpcRequestError(response.error); } return response.result; }
async call(nameOrOptions, ...params) { if ((typeof nameOrOptions !== 'string' && typeof nameOrOptions !== 'object') || nameOrOptions === null) { throw Error('ContentRPC#call(): First argument must be a string or an object with at least a "name" property'); } const name = typeof nameOrOptions === 'object' ? nameOrOptions.name : nameOrOptions; if (typeof name !== 'string') { throw Error('ContentRPC#call(): First argument must be a string or an object with at least a "name" property'); } const timeout = typeof nameOrOptions === 'object' && 'timeout' in nameOrOptions ? nameOrOptions.timeout : DEFAULT_CALL_TIMEOUT; const message = { rpcContext: this.rpcContext, method: name, params, }; if (this.contentToken) { message.rpcContentToken = this.contentToken; } // (A nice function name which we can easily recognise in stack traces) const contentRPC$call$sendMessage = async () => { try { return await this.browserRuntime.sendMessage('[email protected]', message, {}); } catch (err) { // note: errors thrown by the RPC method itself do not end up here, instead they end up in a "rejected" property // this way we can differentiate between errors raised by WebExt and our own RPC methods if (err.message === 'Could not establish connection. Receiving end does not exist.') { // This could happen because: // 1. The content script really did not attach a listener // 2. The message was just sent to the content script, however the frame was in the process of navigating somewhere else // and our content script on the next frame has not been loaded yet const newError = Error( `TabContentRPC: Remote Call "${name}" did not receive a response from the content script ` + '(there are no listeners)', ); newError.name = 'RPCNoResponse'; newError.cause = err; throw newError; } throw err; } }; const response = await asyncTimeout( contentRPC$call$sendMessage, { timeout, timeoutErrorName: CONTENT_RPC_TIMEOUT_ERROR, timeoutMessage: `ContentRPC: Remote Call "${name}" timed out after ${timeout}ms`, }, )(); if (!response) { const err = Error(`ContentRPC: Remote Call "${name}" did not receive a response from the background script`); err.name = 'RPCNoResponse'; throw err; } if ('error' in response) { throw createRpcRequestError(response.error); } return response.result; }
JavaScript
_destroyAllContentInstances() { const destroyedContentTokens = new Set(this._contentInstancesMap.keys()); if (this.initializedContentInstance) { this.initializedContentInstance = null; ++this.initializationTransitionCounter; } for (const content of this._contentInstancesMap.values()) { content.setState(INSTANCE_STATE.DESTROYED); } this._contentInstancesMap.clear(); return destroyedContentTokens; }
_destroyAllContentInstances() { const destroyedContentTokens = new Set(this._contentInstancesMap.keys()); if (this.initializedContentInstance) { this.initializedContentInstance = null; ++this.initializationTransitionCounter; } for (const content of this._contentInstancesMap.values()) { content.setState(INSTANCE_STATE.DESTROYED); } this._contentInstancesMap.clear(); return destroyedContentTokens; }
JavaScript
tabCreated(browserTabId) { assert(!this._tabsByBrowserIdMap.get(browserTabId), 'TabContentTracker#tabCreated(): Given browserTabId has already been created'); // This id is visible to openrunner scripts, the browserTabId is not. // This ensures that we can make changes without breaking existing scripts. /** @type {string} */ const id = generateShortId(); const tab = new Tab(id, browserTabId); this._tabsByIdMap.set(id, tab); this._tabsByBrowserIdMap.set(browserTabId, tab); return tab.public; }
tabCreated(browserTabId) { assert(!this._tabsByBrowserIdMap.get(browserTabId), 'TabContentTracker#tabCreated(): Given browserTabId has already been created'); // This id is visible to openrunner scripts, the browserTabId is not. // This ensures that we can make changes without breaking existing scripts. /** @type {string} */ const id = generateShortId(); const tab = new Tab(id, browserTabId); this._tabsByIdMap.set(id, tab); this._tabsByBrowserIdMap.set(browserTabId, tab); return tab.public; }
JavaScript
tabClosed(browserTabId) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { return; } const {destroyedContentTokens} = tab.close(); const deleted0 = this._tabsByBrowserIdMap.delete(browserTabId); assert.isTrue(deleted0); const deleted1 = this._tabsByIdMap.delete(tab.id); assert.isTrue(deleted1); setAddAll(this._oldContentInstances, destroyedContentTokens); }
tabClosed(browserTabId) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { return; } const {destroyedContentTokens} = tab.close(); const deleted0 = this._tabsByBrowserIdMap.delete(browserTabId); assert.isTrue(deleted0); const deleted1 = this._tabsByIdMap.delete(tab.id); assert.isTrue(deleted1); setAddAll(this._oldContentInstances, destroyedContentTokens); }
JavaScript
frameBeforeNavigate(browserTabId, browserFrameId) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { throw Error('TabContentTracker#frameBeforeNavigate(): Unknown browserTabId'); } // frameBeforeNavigate might remove some frames, so gather the list of all frame id's before we call it const browserFrameIds = new Set(tab.allBrowserFrameIds()); const {destroyedContentTokens} = tab.frameBeforeNavigate(browserFrameId); setAddAll(this._oldContentInstances, destroyedContentTokens); this._resolveInitListeners(browserTabId, browserFrameIds); }
frameBeforeNavigate(browserTabId, browserFrameId) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { throw Error('TabContentTracker#frameBeforeNavigate(): Unknown browserTabId'); } // frameBeforeNavigate might remove some frames, so gather the list of all frame id's before we call it const browserFrameIds = new Set(tab.allBrowserFrameIds()); const {destroyedContentTokens} = tab.frameBeforeNavigate(browserFrameId); setAddAll(this._oldContentInstances, destroyedContentTokens); this._resolveInitListeners(browserTabId, browserFrameIds); }
JavaScript
frameContentHello(browserTabId, browserFrameAncestorIds, contentToken) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { throw Error('TabContentTracker#frameContentHello(): Unknown browserTabId'); } assert(browserFrameAncestorIds.length > 0, 'TabContentTracker#frameContentHello(): browserFrameAncestorIds is empty'); assert( !this._oldContentInstances.has(contentToken), 'TabContentTracker#frameContentHello(): The given contentToken belonged to a frame that was previously destroyed', ); const result = tab.frameContentHello(browserFrameAncestorIds, contentToken); this._resolveInitListeners(browserTabId, new Set(tab.allBrowserFrameIds())); return result; }
frameContentHello(browserTabId, browserFrameAncestorIds, contentToken) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { throw Error('TabContentTracker#frameContentHello(): Unknown browserTabId'); } assert(browserFrameAncestorIds.length > 0, 'TabContentTracker#frameContentHello(): browserFrameAncestorIds is empty'); assert( !this._oldContentInstances.has(contentToken), 'TabContentTracker#frameContentHello(): The given contentToken belonged to a frame that was previously destroyed', ); const result = tab.frameContentHello(browserFrameAncestorIds, contentToken); this._resolveInitListeners(browserTabId, new Set(tab.allBrowserFrameIds())); return result; }
JavaScript
frameMainInitializationComplete(browserTabId, browserFrameId, contentToken) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { throw Error('TabContentTracker#frameContentHello(): Unknown browserTabId'); } const result = tab.frameMainInitializationComplete(browserFrameId, contentToken); this._resolveInitListeners(browserTabId, new Set(tab.allBrowserFrameIds())); return result; }
frameMainInitializationComplete(browserTabId, browserFrameId, contentToken) { const tab = this._tabsByBrowserIdMap.get(browserTabId); if (!tab) { throw Error('TabContentTracker#frameContentHello(): Unknown browserTabId'); } const result = tab.frameMainInitializationComplete(browserFrameId, contentToken); this._resolveInitListeners(browserTabId, new Set(tab.allBrowserFrameIds())); return result; }
JavaScript
register(name, func) { if (typeof name !== 'string') { throw Error('MethodRegistrations#register(): First argument (name) must be a string'); } if (typeof func !== 'function') { throw Error('MethodRegistrations#register(): Second argument (func) must be a function'); } const methods = this._methods; const lastDefinition = methods[methods.length - 1]; if (lastDefinition && lastDefinition.isSingleMethodMap) { // reuse the latest definition lastDefinition.map.set(name, func); } else { methods.push(Object.freeze({ isSingleMethodMap: true, map: new Map([[name, func]]), })); } }
register(name, func) { if (typeof name !== 'string') { throw Error('MethodRegistrations#register(): First argument (name) must be a string'); } if (typeof func !== 'function') { throw Error('MethodRegistrations#register(): Second argument (func) must be a function'); } const methods = this._methods; const lastDefinition = methods[methods.length - 1]; if (lastDefinition && lastDefinition.isSingleMethodMap) { // reuse the latest definition lastDefinition.map.set(name, func); } else { methods.push(Object.freeze({ isSingleMethodMap: true, map: new Map([[name, func]]), })); } }
JavaScript
registerAll(map) { if (!map || typeof map.get !== 'function') { throw Error('MethodRegistrations#registerAll(): First argument (map) must be a Map'); } const methods = this._methods; methods.push(Object.freeze({ isSingleMethodMap: false, map: map, })); }
registerAll(map) { if (!map || typeof map.get !== 'function') { throw Error('MethodRegistrations#registerAll(): First argument (map) must be a Map'); } const methods = this._methods; methods.push(Object.freeze({ isSingleMethodMap: false, map: map, })); }
JavaScript
set timing(value) { if (!TimePeriod.isTimePeriod(value)) { throw illegalArgumentError('Transaction.timing: Value must be a TimePeriod'); } this[PRIVATE].timing = value; }
set timing(value) { if (!TimePeriod.isTimePeriod(value)) { throw illegalArgumentError('Transaction.timing: Value must be a TimePeriod'); } this[PRIVATE].timing = value; }
JavaScript
set error(err) { const tag = Object.prototype.toString.call(err); // also see Symbol.toStringTag if (err !== null && (typeof err !== 'object' || typeof err.name !== 'string' || typeof err.message !== 'string') ) { let errorToString = ''; try { errorToString = err.toString(); } catch (e) { } throw illegalArgumentError(`Transaction.error: value must be instance of Error, or null: ${tag} ${errorToString}`); } this[PRIVATE].error = err; }
set error(err) { const tag = Object.prototype.toString.call(err); // also see Symbol.toStringTag if (err !== null && (typeof err !== 'object' || typeof err.name !== 'string' || typeof err.message !== 'string') ) { let errorToString = ''; try { errorToString = err.toString(); } catch (e) { } throw illegalArgumentError(`Transaction.error: value must be instance of Error, or null: ${tag} ${errorToString}`); } this[PRIVATE].error = err; }
JavaScript
async call(nameOrOptions, ...params) { if ((typeof nameOrOptions !== 'string' && typeof nameOrOptions !== 'object') || nameOrOptions === null) { throw Error('TabContentRPCFrameInstance#call(): First argument must be a string or an object with at least a "name" property'); } const name = typeof nameOrOptions === 'object' ? nameOrOptions.name : nameOrOptions; if (typeof name !== 'string') { throw Error('TabContentRPCFrameInstance#call(): First argument must be a string or an object with at least a "name" property'); } const timeout = typeof nameOrOptions === 'object' && 'timeout' in nameOrOptions ? nameOrOptions.timeout : DEFAULT_CALL_TIMEOUT; if (this._destroyed) { throw Error('TabContentRPCFrameInstance#call(): This instance has been destroyed'); } const message = { rpcContext: this._tabContentRPC.rpcContext, method: name, params, }; if (this.contentToken) { message.rpcContentToken = this.contentToken; } // (A nice function name which we can easily recognise in stack traces) const TabContentRPCFrameInstance$call$sendMessage = async () => { try { return await this._tabContentRPC.browserTabs.sendMessage( this.browserTabId, message, {frameId: this.browserFrameId}, ); } catch (err) { // note: errors thrown by the RPC method itself do not end up here, instead they end up in a "rejected" property // this way we can differentiate between errors raised by WebExt and our own RPC methods if (err.message === 'Could not establish connection. Receiving end does not exist.') { // This could happen because: // 1. The content script really did not attach a listener // 2. The message was just sent to the content script, however the frame was in the process of navigating somewhere else // and our content script on the next frame has not been loaded yet const newError = Error( `TabContentRPC: Remote Call "${name}" did not receive a response from the content script ` + '(there are no listeners)', ); newError.name = 'RPCNoResponse'; newError.cause = err; throw newError; } throw err; } }; const response = await asyncTimeout( TabContentRPCFrameInstance$call$sendMessage, { timeout, timeoutErrorName: CONTENT_RPC_TIMEOUT_ERROR, timeoutMessage: `TabContentRPC: Remote Call "${name}" timed out after ${timeout}ms`, }, )(); if (!response) { // This could happen because: // 1. The content script really did not return anything // 2. The message was just sent to the content script, however the frame is in the process of navigating somewhere else (or // getting removed) and our content script has been unloaded. const err = Error(`TabContentRPC: Remote Call "${name}" did not receive a response from the content script`); err.name = 'RPCNoResponse'; throw err; } if ('error' in response) { throw createRpcRequestError(response.error); } return response.result; }
async call(nameOrOptions, ...params) { if ((typeof nameOrOptions !== 'string' && typeof nameOrOptions !== 'object') || nameOrOptions === null) { throw Error('TabContentRPCFrameInstance#call(): First argument must be a string or an object with at least a "name" property'); } const name = typeof nameOrOptions === 'object' ? nameOrOptions.name : nameOrOptions; if (typeof name !== 'string') { throw Error('TabContentRPCFrameInstance#call(): First argument must be a string or an object with at least a "name" property'); } const timeout = typeof nameOrOptions === 'object' && 'timeout' in nameOrOptions ? nameOrOptions.timeout : DEFAULT_CALL_TIMEOUT; if (this._destroyed) { throw Error('TabContentRPCFrameInstance#call(): This instance has been destroyed'); } const message = { rpcContext: this._tabContentRPC.rpcContext, method: name, params, }; if (this.contentToken) { message.rpcContentToken = this.contentToken; } // (A nice function name which we can easily recognise in stack traces) const TabContentRPCFrameInstance$call$sendMessage = async () => { try { return await this._tabContentRPC.browserTabs.sendMessage( this.browserTabId, message, {frameId: this.browserFrameId}, ); } catch (err) { // note: errors thrown by the RPC method itself do not end up here, instead they end up in a "rejected" property // this way we can differentiate between errors raised by WebExt and our own RPC methods if (err.message === 'Could not establish connection. Receiving end does not exist.') { // This could happen because: // 1. The content script really did not attach a listener // 2. The message was just sent to the content script, however the frame was in the process of navigating somewhere else // and our content script on the next frame has not been loaded yet const newError = Error( `TabContentRPC: Remote Call "${name}" did not receive a response from the content script ` + '(there are no listeners)', ); newError.name = 'RPCNoResponse'; newError.cause = err; throw newError; } throw err; } }; const response = await asyncTimeout( TabContentRPCFrameInstance$call$sendMessage, { timeout, timeoutErrorName: CONTENT_RPC_TIMEOUT_ERROR, timeoutMessage: `TabContentRPC: Remote Call "${name}" timed out after ${timeout}ms`, }, )(); if (!response) { // This could happen because: // 1. The content script really did not return anything // 2. The message was just sent to the content script, however the frame is in the process of navigating somewhere else (or // getting removed) and our content script has been unloaded. const err = Error(`TabContentRPC: Remote Call "${name}" did not receive a response from the content script`); err.name = 'RPCNoResponse'; throw err; } if ('error' in response) { throw createRpcRequestError(response.error); } return response.result; }
JavaScript
reinitialize(browserTabId, browserFrameId, contentToken = null) { if (!this.rpcMap.has(browserTabId)) { this.rpcMap.set(browserTabId, new Map()); } const frameMap = this.rpcMap.get(browserTabId); if (!frameMap.has(browserFrameId)) { frameMap.set(browserFrameId, new Map()); } const instanceMap = frameMap.get(browserFrameId); { const rpc = instanceMap.get(contentToken); if (rpc) { rpc._destroy(); instanceMap.delete(contentToken); } } const rpc = new TabContentRPCFrameInstance(browserTabId, browserFrameId, contentToken, this); instanceMap.set(contentToken, rpc); rpc._initializePromise = promiseTry(() => this.onRpcInitialize({browserTabId, browserFrameId, contentToken, rpc})) .catch(err => log.error({err, browserTabId, browserFrameId, contentToken}, 'Error while calling onRpcInitialize')) .then(() => undefined); return rpc; }
reinitialize(browserTabId, browserFrameId, contentToken = null) { if (!this.rpcMap.has(browserTabId)) { this.rpcMap.set(browserTabId, new Map()); } const frameMap = this.rpcMap.get(browserTabId); if (!frameMap.has(browserFrameId)) { frameMap.set(browserFrameId, new Map()); } const instanceMap = frameMap.get(browserFrameId); { const rpc = instanceMap.get(contentToken); if (rpc) { rpc._destroy(); instanceMap.delete(contentToken); } } const rpc = new TabContentRPCFrameInstance(browserTabId, browserFrameId, contentToken, this); instanceMap.set(contentToken, rpc); rpc._initializePromise = promiseTry(() => this.onRpcInitialize({browserTabId, browserFrameId, contentToken, rpc})) .catch(err => log.error({err, browserTabId, browserFrameId, contentToken}, 'Error while calling onRpcInitialize')) .then(() => undefined); return rpc; }
JavaScript
async _gatherBrowserWindowDetails(browserWindowId, firstTabId) { let sizeMinusViewport = [0, 0]; try { [sizeMinusViewport] = await this.browserTabs.executeScript(firstTabId, { code: '([window.outerWidth - window.innerWidth, window.outerHeight - window.innerHeight])', }); } catch (err) { log.debug({browserWindowId, firstTabId, err}, 'Unable to determine the window dimension'); } this._sizeMinusViewport = Object.freeze({ width: Number(sizeMinusViewport[0]), height: Number(sizeMinusViewport[1]), }); }
async _gatherBrowserWindowDetails(browserWindowId, firstTabId) { let sizeMinusViewport = [0, 0]; try { [sizeMinusViewport] = await this.browserTabs.executeScript(firstTabId, { code: '([window.outerWidth - window.innerWidth, window.outerHeight - window.innerHeight])', }); } catch (err) { log.debug({browserWindowId, firstTabId, err}, 'Unable to determine the window dimension'); } this._sizeMinusViewport = Object.freeze({ width: Number(sizeMinusViewport[0]), height: Number(sizeMinusViewport[1]), }); }
JavaScript
function hocwpThemeGenerateColorA11yPreviewStyles(context, theme_mod) { theme_mod = theme_mod || "accent_accessible_colors"; var customize = window.parent.wp.customize(theme_mod); if (customize) { // Get the accessible colors option. var a11yColors = customize.get(), stylesheedID = "hocwp-theme-custom-customizer-styles-" + context, selectorKey = "#" + stylesheedID, stylesheet = $(selectorKey), styles = ""; // If the stylesheet doesn't exist, create it and append it to <head>. if (!stylesheet.length) { $("#hocwp-theme-custom-style-inline-css").after('<style id="' + stylesheedID + '"></style>'); stylesheet = $(selectorKey); } if (!_.isUndefined(a11yColors[context])) { // Check if we have elements defined. if (hocwpThemeCustomizer.elements[context]) { _.each(hocwpThemeCustomizer.elements[context], function (items, setting) { _.each(items, function (elements, property) { if (!_.isUndefined(a11yColors[context][setting])) { styles += elements.join(",") + "{" + property + ":" + a11yColors[context][setting] + ";}"; } }); }); } } if (hocwpThemeCustomizer.inline_css) { styles += hocwpThemeCustomizer.inline_css; } // Add styles. stylesheet.html(styles); } }
function hocwpThemeGenerateColorA11yPreviewStyles(context, theme_mod) { theme_mod = theme_mod || "accent_accessible_colors"; var customize = window.parent.wp.customize(theme_mod); if (customize) { // Get the accessible colors option. var a11yColors = customize.get(), stylesheedID = "hocwp-theme-custom-customizer-styles-" + context, selectorKey = "#" + stylesheedID, stylesheet = $(selectorKey), styles = ""; // If the stylesheet doesn't exist, create it and append it to <head>. if (!stylesheet.length) { $("#hocwp-theme-custom-style-inline-css").after('<style id="' + stylesheedID + '"></style>'); stylesheet = $(selectorKey); } if (!_.isUndefined(a11yColors[context])) { // Check if we have elements defined. if (hocwpThemeCustomizer.elements[context]) { _.each(hocwpThemeCustomizer.elements[context], function (items, setting) { _.each(items, function (elements, property) { if (!_.isUndefined(a11yColors[context][setting])) { styles += elements.join(",") + "{" + property + ":" + a11yColors[context][setting] + ";}"; } }); }); } } if (hocwpThemeCustomizer.inline_css) { styles += hocwpThemeCustomizer.inline_css; } // Add styles. stylesheet.html(styles); } }
JavaScript
function clickMenuItemHasChildren(e) { e.preventDefault(); e.stopPropagation(); var link = this.parentNode; subMenu = link.parentNode.getElementsByTagName("ul")[0]; if ("undefined" !== typeof subMenu) { link.parentNode.className = link.parentNode.className.replace(" focus", ""); if (-1 !== link.className.indexOf("toggled")) { link.className = link.className.replace(" toggled", ""); link.setAttribute("aria-expanded", "false"); subMenu.setAttribute("aria-expanded", "false"); } else { link.className += " toggled"; link.setAttribute("aria-expanded", "true"); subMenu.setAttribute("aria-expanded", "true"); } } }
function clickMenuItemHasChildren(e) { e.preventDefault(); e.stopPropagation(); var link = this.parentNode; subMenu = link.parentNode.getElementsByTagName("ul")[0]; if ("undefined" !== typeof subMenu) { link.parentNode.className = link.parentNode.className.replace(" focus", ""); if (-1 !== link.className.indexOf("toggled")) { link.className = link.className.replace(" toggled", ""); link.setAttribute("aria-expanded", "false"); subMenu.setAttribute("aria-expanded", "false"); } else { link.className += " toggled"; link.setAttribute("aria-expanded", "true"); subMenu.setAttribute("aria-expanded", "true"); } } }
JavaScript
function parseTemplate(template, tags) { if (!template) return []; var sections = []; // Stack to hold section tokens var tokens = []; // Buffer to hold the tokens var spaces = []; // Indices of whitespace tokens on the current line var hasTag = false; // Is there a {{tag}} on the current line? var nonSpace = false; // Is there a non-space char on the current line? // Strips all whitespace tokens array for the current line // if there was a {{#tag}} on it and otherwise only space. function stripSpace() { if (hasTag && !nonSpace) { while (spaces.length) { delete tokens[spaces.pop()]; } } else { spaces = []; } hasTag = false; nonSpace = false; } var openingTagRe, closingTagRe, closingCurlyRe; function compileTags(tagsToCompile) { if (typeof tagsToCompile === 'string') tagsToCompile = tagsToCompile.split(spaceRe, 2); if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) throw new Error('Invalid tags: ' + tagsToCompile); openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*'); closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1])); closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1])); } compileTags(tags || mustache.tags); var scanner = new Scanner(template); var start, type, value, chr, token, openSection; while (!scanner.eos()) { start = scanner.pos; // Match any text between tags. value = scanner.scanUntil(openingTagRe); if (value) { for (var i = 0, valueLength = value.length; i < valueLength; ++i) { chr = value.charAt(i); if (isWhitespace(chr)) { spaces.push(tokens.length); } else { nonSpace = true; } tokens.push(['text', chr, start, start + 1]); start += 1; // Check for whitespace on the current line. if (chr === '\n') stripSpace(); } } // Match the opening tag. if (!scanner.scan(openingTagRe)) break; hasTag = true; // Get the tag type. type = scanner.scan(tagRe) || 'name'; scanner.scan(whiteRe); // Get the tag value. if (type === '=') { value = scanner.scanUntil(equalsRe); scanner.scan(equalsRe); scanner.scanUntil(closingTagRe); } else if (type === '{') { value = scanner.scanUntil(closingCurlyRe); scanner.scan(curlyRe); scanner.scanUntil(closingTagRe); type = '&'; } else { value = scanner.scanUntil(closingTagRe); } // Match the closing tag. if (!scanner.scan(closingTagRe)) throw new Error('Unclosed tag at ' + scanner.pos); token = [type, value, start, scanner.pos]; tokens.push(token); if (type === '#' || type === '^') { sections.push(token); } else if (type === '/') { // Check section nesting. openSection = sections.pop(); if (!openSection) throw new Error('Unopened section "' + value + '" at ' + start); if (openSection[1] !== value) throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); } else if (type === 'name' || type === '{' || type === '&') { nonSpace = true; } else if (type === '=') { // Set the tags for the next time around. compileTags(value); } } // Make sure there are no open sections when we're done. openSection = sections.pop(); if (openSection) throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); return nestTokens(squashTokens(tokens)); }
function parseTemplate(template, tags) { if (!template) return []; var sections = []; // Stack to hold section tokens var tokens = []; // Buffer to hold the tokens var spaces = []; // Indices of whitespace tokens on the current line var hasTag = false; // Is there a {{tag}} on the current line? var nonSpace = false; // Is there a non-space char on the current line? // Strips all whitespace tokens array for the current line // if there was a {{#tag}} on it and otherwise only space. function stripSpace() { if (hasTag && !nonSpace) { while (spaces.length) { delete tokens[spaces.pop()]; } } else { spaces = []; } hasTag = false; nonSpace = false; } var openingTagRe, closingTagRe, closingCurlyRe; function compileTags(tagsToCompile) { if (typeof tagsToCompile === 'string') tagsToCompile = tagsToCompile.split(spaceRe, 2); if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) throw new Error('Invalid tags: ' + tagsToCompile); openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*'); closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1])); closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1])); } compileTags(tags || mustache.tags); var scanner = new Scanner(template); var start, type, value, chr, token, openSection; while (!scanner.eos()) { start = scanner.pos; // Match any text between tags. value = scanner.scanUntil(openingTagRe); if (value) { for (var i = 0, valueLength = value.length; i < valueLength; ++i) { chr = value.charAt(i); if (isWhitespace(chr)) { spaces.push(tokens.length); } else { nonSpace = true; } tokens.push(['text', chr, start, start + 1]); start += 1; // Check for whitespace on the current line. if (chr === '\n') stripSpace(); } } // Match the opening tag. if (!scanner.scan(openingTagRe)) break; hasTag = true; // Get the tag type. type = scanner.scan(tagRe) || 'name'; scanner.scan(whiteRe); // Get the tag value. if (type === '=') { value = scanner.scanUntil(equalsRe); scanner.scan(equalsRe); scanner.scanUntil(closingTagRe); } else if (type === '{') { value = scanner.scanUntil(closingCurlyRe); scanner.scan(curlyRe); scanner.scanUntil(closingTagRe); type = '&'; } else { value = scanner.scanUntil(closingTagRe); } // Match the closing tag. if (!scanner.scan(closingTagRe)) throw new Error('Unclosed tag at ' + scanner.pos); token = [type, value, start, scanner.pos]; tokens.push(token); if (type === '#' || type === '^') { sections.push(token); } else if (type === '/') { // Check section nesting. openSection = sections.pop(); if (!openSection) throw new Error('Unopened section "' + value + '" at ' + start); if (openSection[1] !== value) throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); } else if (type === 'name' || type === '{' || type === '&') { nonSpace = true; } else if (type === '=') { // Set the tags for the next time around. compileTags(value); } } // Make sure there are no open sections when we're done. openSection = sections.pop(); if (openSection) throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); return nestTokens(squashTokens(tokens)); }
JavaScript
function squashTokens(tokens) { var squashedTokens = []; var token, lastToken; for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { token = tokens[i]; if (token) { if (token[0] === 'text' && lastToken && lastToken[0] === 'text') { lastToken[1] += token[1]; lastToken[3] = token[3]; } else { squashedTokens.push(token); lastToken = token; } } } return squashedTokens; }
function squashTokens(tokens) { var squashedTokens = []; var token, lastToken; for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { token = tokens[i]; if (token) { if (token[0] === 'text' && lastToken && lastToken[0] === 'text') { lastToken[1] += token[1]; lastToken[3] = token[3]; } else { squashedTokens.push(token); lastToken = token; } } } return squashedTokens; }
JavaScript
function nestTokens(tokens) { var nestedTokens = []; var collector = nestedTokens; var sections = []; var token, section; for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { token = tokens[i]; switch (token[0]) { case '#': case '^': collector.push(token); sections.push(token); collector = token[4] = []; break; case '/': section = sections.pop(); section[5] = token[2]; collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; break; default: collector.push(token); } } return nestedTokens; }
function nestTokens(tokens) { var nestedTokens = []; var collector = nestedTokens; var sections = []; var token, section; for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { token = tokens[i]; switch (token[0]) { case '#': case '^': collector.push(token); sections.push(token); collector = token[4] = []; break; case '/': section = sections.pop(); section[5] = token[2]; collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; break; default: collector.push(token); } } return nestedTokens; }
JavaScript
function Scanner(string) { this.string = string; this.tail = string; this.pos = 0; }
function Scanner(string) { this.string = string; this.tail = string; this.pos = 0; }
JavaScript
function Context(view, parentContext) { this.view = view; this.cache = { '.': this.view, '@each': function each() { var returns = []; for (var k in this) { returns.push({ '@key': k, '@value': this[k] }); } return returns; } }; this.parent = parentContext; }
function Context(view, parentContext) { this.view = view; this.cache = { '.': this.view, '@each': function each() { var returns = []; for (var k in this) { returns.push({ '@key': k, '@value': this[k] }); } return returns; } }; this.parent = parentContext; }
JavaScript
function showVersionHelp(version) { if (!semver.validRange(version)) { console.log(`Invalid version: ${version}`); return; } const ranges = migrations.map((migration) => migration.range); if (!ranges.some((range) => semver.intersects(range, version))) { console.log(`No migrations found for version ${version}`); return; } console.log(`Migrations for version ${version}:`); for (const migration of migrations) { if (!semver.intersects(migration.range, version)) continue; console.log(` ${chalk.blue(migration.name)}, ${migration.description}`); } }
function showVersionHelp(version) { if (!semver.validRange(version)) { console.log(`Invalid version: ${version}`); return; } const ranges = migrations.map((migration) => migration.range); if (!ranges.some((range) => semver.intersects(range, version))) { console.log(`No migrations found for version ${version}`); return; } console.log(`Migrations for version ${version}:`); for (const migration of migrations) { if (!semver.intersects(migration.range, version)) continue; console.log(` ${chalk.blue(migration.name)}, ${migration.description}`); } }
JavaScript
function createSubCommand(name, targetVersionRange, description) { const migration = { name: name, description: description, range: targetVersionRange, }; migrations.push(migration); return new Command(name) .description(description) .requiredOption( '--from <from-version>', 'Blockly version to migrate from') .option('--to <to-version>', 'Blockly version to migrate to') .argument('<file...>', 'Files to migrate'); }
function createSubCommand(name, targetVersionRange, description) { const migration = { name: name, description: description, range: targetVersionRange, }; migrations.push(migration); return new Command(name) .description(description) .requiredOption( '--from <from-version>', 'Blockly version to migrate from') .option('--to <to-version>', 'Blockly version to migrate to') .argument('<file...>', 'Files to migrate'); }
JavaScript
function initTooltips() { // Create a custom rendering function. This function will be called whenever // a tooltip is shown in Blockly. The first argument is the div to render // the content into. The second argument is the element to show the tooltip // for. const customTooltip = function(div, element) { if (element instanceof Blockly.BlockSvg) { // You can access the block being moused over. // Here we get the color of the block to set the background color. div.style.backgroundColor = element.getColour(); } const tip = Blockly.Tooltip.getTooltipOfObject(element); const text = document.createElement('div'); text.textContent = tip; const container = document.createElement('div'); container.style.display = 'flex'; // Check to see if the custom property we added in the block definition is // present. if (element.tooltipImg) { const img = document.createElement('img'); img.setAttribute('src', element.tooltipImg); container.appendChild(img); } container.appendChild(text); div.appendChild(container); }; // Register the function in the Blockly.Tooltip so that Blockly calls it // when needed. Blockly.Tooltip.setCustomTooltip(customTooltip); }
function initTooltips() { // Create a custom rendering function. This function will be called whenever // a tooltip is shown in Blockly. The first argument is the div to render // the content into. The second argument is the element to show the tooltip // for. const customTooltip = function(div, element) { if (element instanceof Blockly.BlockSvg) { // You can access the block being moused over. // Here we get the color of the block to set the background color. div.style.backgroundColor = element.getColour(); } const tip = Blockly.Tooltip.getTooltipOfObject(element); const text = document.createElement('div'); text.textContent = tip; const container = document.createElement('div'); container.style.display = 'flex'; // Check to see if the custom property we added in the block definition is // present. if (element.tooltipImg) { const img = document.createElement('img'); img.setAttribute('src', element.tooltipImg); container.appendChild(img); } container.appendChild(text); div.appendChild(container); }; // Register the function in the Blockly.Tooltip so that Blockly calls it // when needed. Blockly.Tooltip.setCustomTooltip(customTooltip); }
JavaScript
function preparePluginsForLocal(isBeta) { return (done) => { if (isBeta) { execSync(`lerna add blockly@beta --dev`, {stdio: 'inherit'}); } execSync(`npm run boot`, {stdio: 'inherit'}); // Bundles all the plugins. execSync(`npm run deploy:prepare:plugins`, {stdio: 'inherit'}); done(); }; }
function preparePluginsForLocal(isBeta) { return (done) => { if (isBeta) { execSync(`lerna add blockly@beta --dev`, {stdio: 'inherit'}); } execSync(`npm run boot`, {stdio: 'inherit'}); // Bundles all the plugins. execSync(`npm run deploy:prepare:plugins`, {stdio: 'inherit'}); done(); }; }
JavaScript
function prepareExamplesForLocal(isBeta) { return (done) => { const examplesDirectory = 'examples'; if (isBeta) { execSync( `lerna add blockly@beta`, {cwd: examplesDirectory, stdio: 'inherit'}); } execSync(`npm run boot`, {cwd: examplesDirectory, stdio: 'inherit'}); // Bundles any examples that define a predeploy script (ex. blockly-react). execSync(`npm run deploy:prepare:examples`, {stdio: 'inherit'}); done(); }; }
function prepareExamplesForLocal(isBeta) { return (done) => { const examplesDirectory = 'examples'; if (isBeta) { execSync( `lerna add blockly@beta`, {cwd: examplesDirectory, stdio: 'inherit'}); } execSync(`npm run boot`, {cwd: examplesDirectory, stdio: 'inherit'}); // Bundles any examples that define a predeploy script (ex. blockly-react). execSync(`npm run deploy:prepare:examples`, {stdio: 'inherit'}); done(); }; }
JavaScript
static calculateRenamings(database, currVersion, newVersion) { currVersion = versionUtils.coerce(currVersion); newVersion = versionUtils.coerce(newVersion); const versions = Object.keys(database).sort(versionUtils.compare); const renamers /** !Array<!VersionRenamer> */ = []; for (const version of versions) { // Only process versions in the range (currVersion, ^newVersion]. if (versionUtils.lte(version, currVersion)) continue; if (versionUtils.gt(version, newVersion)) break; renamers.push(new VersionRenamer(database[version])); } return renamers; }
static calculateRenamings(database, currVersion, newVersion) { currVersion = versionUtils.coerce(currVersion); newVersion = versionUtils.coerce(newVersion); const versions = Object.keys(database).sort(versionUtils.compare); const renamers /** !Array<!VersionRenamer> */ = []; for (const version of versions) { // Only process versions in the range (currVersion, ^newVersion]. if (versionUtils.lte(version, currVersion)) continue; if (versionUtils.gt(version, newVersion)) break; renamers.push(new VersionRenamer(database[version])); } return renamers; }
JavaScript
rename(str) { return str.replace(dottedIdentifier, (match) => { for (const versionRenamer of this.versionRenamers_) { match = versionRenamer.rename(match); } return match; }); }
rename(str) { return str.replace(dottedIdentifier, (match) => { for (const versionRenamer of this.versionRenamers_) { match = versionRenamer.rename(match); } return match; }); }
JavaScript
rename(str) { for (const entry of this.renamings_) { if (str.startsWith(entry.old)) { if (entry.get || entry.set) { process.stderr.write(`NOTE: ${entry.old} has been removed.\n`); if (entry.get) { process.stderr.write(` - Call ${entry.get}() instead of ` + 'reading it.\n'); } if (entry.set) { process.stderr.write(` - Call ${entry.set}(/* new value */) ` + 'instead of setting it.\n'); } process.stderr.write( 'You will need to manually verify this update.\n'); return (entry.get || entry.set) + '()' + str.slice(entry.old.length); } return entry.new + str.slice(entry.old.length); } } return str; }
rename(str) { for (const entry of this.renamings_) { if (str.startsWith(entry.old)) { if (entry.get || entry.set) { process.stderr.write(`NOTE: ${entry.old} has been removed.\n`); if (entry.get) { process.stderr.write(` - Call ${entry.get}() instead of ` + 'reading it.\n'); } if (entry.set) { process.stderr.write(` - Call ${entry.set}(/* new value */) ` + 'instead of setting it.\n'); } process.stderr.write( 'You will need to manually verify this update.\n'); return (entry.get || entry.set) + '()' + str.slice(entry.old.length); } return entry.new + str.slice(entry.old.length); } } return str; }
JavaScript
function gt(v1, v2) { if (v2 === DEV_VERSION) return false; if (v1 === DEV_VERSION) return true; if (v2 === LATEST) return false; if (v1 === LATEST) return true; return semver.gtr(v1, `^${v2}`); }
function gt(v1, v2) { if (v2 === DEV_VERSION) return false; if (v1 === DEV_VERSION) return true; if (v2 === LATEST) return false; if (v1 === LATEST) return true; return semver.gtr(v1, `^${v2}`); }
JavaScript
function keepIndexWithinBounds(length, index) { // Handle possibility of negative mod. // See http://stackoverflow.com/a/18618250/76472 return ((index % length) + length) % length; }
function keepIndexWithinBounds(length, index) { // Handle possibility of negative mod. // See http://stackoverflow.com/a/18618250/76472 return ((index % length) + length) % length; }
JavaScript
function indexOfContainingItem(element, target) { const items = element.items; const itemCount = items ? items.length : 0; for (let i = 0; i < itemCount; i++) { let item = items[i]; if (item === target || item.contains(target)) { return i; } } return -1; }
function indexOfContainingItem(element, target) { const items = element.items; const itemCount = items ? items.length : 0; for (let i = 0; i < itemCount; i++) { let item = items[i]; if (item === target || item.contains(target)) { return i; } } return -1; }
JavaScript
contentChanged() { if (super.contentChanged) { super.contentChanged(); } const event = new CustomEvent('content-changed'); this.dispatchEvent(event); }
contentChanged() { if (super.contentChanged) { super.contentChanged(); } const event = new CustomEvent('content-changed'); this.dispatchEvent(event); }
JavaScript
get content() { const distributedChildren = this.distributedChildren; if (typeof distributedChildren === 'undefined') { console.warn(`DistributedChildrenContentMixin expects the component to define a "distributedChildren" property.`); } return distributedChildren; }
get content() { const distributedChildren = this.distributedChildren; if (typeof distributedChildren === 'undefined') { console.warn(`DistributedChildrenContentMixin expects the component to define a "distributedChildren" property.`); } return distributedChildren; }
JavaScript
function assumeButtonFocus(element, button) { button.addEventListener('mousedown', event => { // Given the main element the focus if it doesn't already have it. element.focus(); // Prevent the default focus-on-mousedown behavior. event.preventDefault(); }); }
function assumeButtonFocus(element, button) { button.addEventListener('mousedown', event => { // Given the main element the focus if it doesn't already have it. element.focus(); // Prevent the default focus-on-mousedown behavior. event.preventDefault(); }); }
JavaScript
render(closing) { if (super.render) { super.render(); } safeAttributes.toggleClass(this, 'basic-closed', closing); safeAttributes.toggleClass(this, 'basic-opened', !closing); safeAttributes.setAttribute(this, 'aria-expanded', !closing); }
render(closing) { if (super.render) { super.render(); } safeAttributes.toggleClass(this, 'basic-closed', closing); safeAttributes.toggleClass(this, 'basic-opened', !closing); safeAttributes.setAttribute(this, 'aria-expanded', !closing); }
JavaScript
function refresh(element) { const url = window.location.href; let match; if (element.areaLink) { // Match prefix let prefix = element.href; // If prefix doesn't end in slash, add a slash. // We want to avoid matching in the middle of a folder name. if (prefix.length < url.length && prefix.substr(-1) !== '/') { prefix += '/'; } match = (url.substr(0, prefix.length) === prefix); } else { // Match whole path match = (url === element.href); } element.current = match; }
function refresh(element) { const url = window.location.href; let match; if (element.areaLink) { // Match prefix let prefix = element.href; // If prefix doesn't end in slash, add a slash. // We want to avoid matching in the middle of a folder name. if (prefix.length < url.length && prefix.substr(-1) !== '/') { prefix += '/'; } match = (url.substr(0, prefix.length) === prefix); } else { // Match whole path match = (url === element.href); } element.current = match; }
JavaScript
play() { if (super.play) { super.play(); } startTimer(this); this[playingSymbol] = true; }
play() { if (super.play) { super.play(); } startTimer(this); this[playingSymbol] = true; }
JavaScript
pause() { if (super.pause) { super.pause(); } clearTimer(this); this[playingSymbol] = false; }
pause() { if (super.pause) { super.pause(); } clearTimer(this); this[playingSymbol] = false; }
JavaScript
function selectNextWithWrap(element) { const items = element.items; if (items && items.length > 0) { if (element.selectedIndex == null || element.selectedIndex === items.length - 1) { element.selectFirst(); } else { element.selectNext(); } } }
function selectNextWithWrap(element) { const items = element.items; if (items && items.length > 0) { if (element.selectedIndex == null || element.selectedIndex === items.length - 1) { element.selectFirst(); } else { element.selectNext(); } } }
JavaScript
function toggleClass(element, className, force) { const classList = element.classList; const addClass = (typeof force === 'undefined') ? !classList.contains(className) : force; if (addClass) { classList.add(className); } else { classList.remove(className); } return addClass; }
function toggleClass(element, className, force) { const classList = element.classList; const addClass = (typeof force === 'undefined') ? !classList.contains(className) : force; if (addClass) { classList.add(className); } else { classList.remove(className); } return addClass; }
JavaScript
_findDistributionRoot(element) { let root = element.shadyRoot; while (element && this._elementNeedsDistribution(element)) { root = element.getRootNode(); element = root && root.host; } return root; }
_findDistributionRoot(element) { let root = element.shadyRoot; while (element && this._elementNeedsDistribution(element)) { root = element.getRootNode(); element = root && root.host; } return root; }
JavaScript
_elementNeedsDistribution(element) { let c$ = tree.Logical.getChildNodes(element); for (let i=0, c; i < c$.length; i++) { c = c$[i]; if (this._distributor.isInsertionPoint(c)) { return element.getRootNode(); } } }
_elementNeedsDistribution(element) { let c$ = tree.Logical.getChildNodes(element); for (let i=0, c; i < c$.length; i++) { c = c$[i]; if (this._distributor.isInsertionPoint(c)) { return element.getRootNode(); } } }
JavaScript
_composeNode(node) { let children = []; let c$ = tree.Logical.getChildNodes(node.shadyRoot || node); for (let i = 0; i < c$.length; i++) { let child = c$[i]; if (this._distributor.isInsertionPoint(child)) { let distributedNodes = child._distributedNodes || (child._distributedNodes = []); for (let j = 0; j < distributedNodes.length; j++) { let distributedNode = distributedNodes[j]; if (this.isFinalDestination(child, distributedNode)) { children.push(distributedNode); } } } else { children.push(child); } } return children; }
_composeNode(node) { let children = []; let c$ = tree.Logical.getChildNodes(node.shadyRoot || node); for (let i = 0; i < c$.length; i++) { let child = c$[i]; if (this._distributor.isInsertionPoint(child)) { let distributedNodes = child._distributedNodes || (child._distributedNodes = []); for (let j = 0; j < distributedNodes.length; j++) { let distributedNode = distributedNodes[j]; if (this.isFinalDestination(child, distributedNode)) { children.push(distributedNode); } } } else { children.push(child); } } return children; }
JavaScript
_updateChildNodes(container, children) { let composed = tree.Composed.getChildNodes(container); let splices = calculateSplices(children, composed); // process removals for (let i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) { for (let j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) { // check if the node is still where we expect it is before trying // to remove it; this can happen if we move a node and // then schedule its previous host for distribution resulting in // the node being removed here. if (tree.Composed.getParentNode(n) === container) { tree.Composed.removeChild(container, n); } composed.splice(s.index + d, 1); } d -= s.addedCount; } // process adds for (let i=0, s, next; (i<splices.length) && (s=splices[i]); i++) { //eslint-disable-line no-redeclare next = composed[s.index]; for (let j=s.index, n; j < s.index + s.addedCount; j++) { n = children[j]; tree.Composed.insertBefore(container, n, next); // TODO(sorvell): is this splice strictly needed? composed.splice(j, 0, n); } } }
_updateChildNodes(container, children) { let composed = tree.Composed.getChildNodes(container); let splices = calculateSplices(children, composed); // process removals for (let i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) { for (let j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) { // check if the node is still where we expect it is before trying // to remove it; this can happen if we move a node and // then schedule its previous host for distribution resulting in // the node being removed here. if (tree.Composed.getParentNode(n) === container) { tree.Composed.removeChild(container, n); } composed.splice(s.index + d, 1); } d -= s.addedCount; } // process adds for (let i=0, s, next; (i<splices.length) && (s=splices[i]); i++) { //eslint-disable-line no-redeclare next = composed[s.index]; for (let j=s.index, n; j < s.index + s.addedCount; j++) { n = children[j]; tree.Composed.insertBefore(container, n, next); // TODO(sorvell): is this splice strictly needed? composed.splice(j, 0, n); } } }