language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function binl2str(bin) { var str = ''; var mask = (1 << chrsz) - 1; for (var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask); return str; }
function binl2str(bin) { var str = ''; var mask = (1 << chrsz) - 1; for (var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask); return str; }
JavaScript
function fetchPokemon() { var url = "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all"; var iconsPromise = new AjaxGetPromise(url); iconsPromise .then(appendIcons) .catch(function (errorMsg) { alert("ERROR: " + errorMsg); }); }
function fetchPokemon() { var url = "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all"; var iconsPromise = new AjaxGetPromise(url); iconsPromise .then(appendIcons) .catch(function (errorMsg) { alert("ERROR: " + errorMsg); }); }
JavaScript
function initializeOpponentCard() { $("title").innerHTML = "Pokemon Battle Mode!"; var messages = {}; messages.startgame = "true"; messages.mypokemon = CURRENT_USER_POKEMON.toLowerCase(); var url = "https://webster.cs.washington.edu/pokedex/game.php"; var p2 = new AjaxPostPromise(url, messages); p2 .then(JSON.parse) .then(fillOpponentCard) .catch(function (errorMsg) { alert("opponentData ERROR: " + errorMsg); }); $("pokedex-view").classList.add("hidden"); $("start-btn").classList.add("hidden"); $("p1-turn-results").classList.add("hidden"); $("p2-turn-results").classList.add("hidden"); $("their-card").classList.remove("hidden"); $("results-container").classList.remove("hidden"); $("flee-btn").style.display = "block"; $("flee-btn").onclick = performFlee; }
function initializeOpponentCard() { $("title").innerHTML = "Pokemon Battle Mode!"; var messages = {}; messages.startgame = "true"; messages.mypokemon = CURRENT_USER_POKEMON.toLowerCase(); var url = "https://webster.cs.washington.edu/pokedex/game.php"; var p2 = new AjaxPostPromise(url, messages); p2 .then(JSON.parse) .then(fillOpponentCard) .catch(function (errorMsg) { alert("opponentData ERROR: " + errorMsg); }); $("pokedex-view").classList.add("hidden"); $("start-btn").classList.add("hidden"); $("p1-turn-results").classList.add("hidden"); $("p2-turn-results").classList.add("hidden"); $("their-card").classList.remove("hidden"); $("results-container").classList.remove("hidden"); $("flee-btn").style.display = "block"; $("flee-btn").onclick = performFlee; }
JavaScript
function playMove() { $("loading").classList.remove("hidden"); $("p1-turn-results").classList.add("hidden"); $("p2-turn-results").classList.add("hidden"); $("my-card").getElementsByClassName("buffs")[0].innerHTML = ""; $("their-card").getElementsByClassName("buffs")[0].innerHTML = ""; var messages = {}; messages.guid = GUID; messages.pid = PID; messages.move = this.id; var url = "https://webster.cs.washington.edu/pokedex/game.php"; var makeMovePromise = new AjaxPostPromise(url, messages); makeMovePromise .then(JSON.parse) .then(updateBothCards) .then(function (response) { $("loading").classList.add("hidden"); }) .catch(function (errorMsg) { alert("playMove ERROR: " + errorMsg); }); }
function playMove() { $("loading").classList.remove("hidden"); $("p1-turn-results").classList.add("hidden"); $("p2-turn-results").classList.add("hidden"); $("my-card").getElementsByClassName("buffs")[0].innerHTML = ""; $("their-card").getElementsByClassName("buffs")[0].innerHTML = ""; var messages = {}; messages.guid = GUID; messages.pid = PID; messages.move = this.id; var url = "https://webster.cs.washington.edu/pokedex/game.php"; var makeMovePromise = new AjaxPostPromise(url, messages); makeMovePromise .then(JSON.parse) .then(updateBothCards) .then(function (response) { $("loading").classList.add("hidden"); }) .catch(function (errorMsg) { alert("playMove ERROR: " + errorMsg); }); }
JavaScript
function performFlee() { $("loading").classList.add("hidden"); $("endgame").classList.add("hidden"); var messages = {}; messages.move = "flee"; messages.guid = GUID; messages.pid = PID; var url = "https://webster.cs.washington.edu/pokedex/game.php"; var opponentDataPromise = new AjaxPostPromise(url, messages); opponentDataPromise .then(JSON.parse) .then(fleeOperation) .catch(function (errorMsg) { alert("flee ERROR: " + errorMsg); }); }
function performFlee() { $("loading").classList.add("hidden"); $("endgame").classList.add("hidden"); var messages = {}; messages.move = "flee"; messages.guid = GUID; messages.pid = PID; var url = "https://webster.cs.washington.edu/pokedex/game.php"; var opponentDataPromise = new AjaxPostPromise(url, messages); opponentDataPromise .then(JSON.parse) .then(fleeOperation) .catch(function (errorMsg) { alert("flee ERROR: " + errorMsg); }); }
JavaScript
function start() { // Disables the text area (place where the user provides input) $("txtarea_input").disabled = true; // Enables the Stop button & disables the Start button disableBtn($("stop"), false); disableBtn($("start"), true); // Processes user input wordsList = processInput($("txtarea_input").value); // Sets the timer (frame speed) var speed = changeSpeed(); // let the timer tick once timer = setInterval(readWordFramePerFrame, speed); }
function start() { // Disables the text area (place where the user provides input) $("txtarea_input").disabled = true; // Enables the Stop button & disables the Start button disableBtn($("stop"), false); disableBtn($("start"), true); // Processes user input wordsList = processInput($("txtarea_input").value); // Sets the timer (frame speed) var speed = changeSpeed(); // let the timer tick once timer = setInterval(readWordFramePerFrame, speed); }
JavaScript
function changeSpeed() { var speed = parseInt($("speed").value); // If timer is still being run, reset cache value and update speed if (timer) { clearInterval(timer); timer = null; timer = setInterval(readWordFramePerFrame, speed); } return speed; }
function changeSpeed() { var speed = parseInt($("speed").value); // If timer is still being run, reset cache value and update speed if (timer) { clearInterval(timer); timer = null; timer = setInterval(readWordFramePerFrame, speed); } return speed; }
JavaScript
function readWordFramePerFrame() { outputDisplay(true); counter++; // Increases index position in the list of words if (counter > wordsList.length) { counter = 0; stop(); } }
function readWordFramePerFrame() { outputDisplay(true); counter++; // Increases index position in the list of words if (counter > wordsList.length) { counter = 0; stop(); } }
JavaScript
function processInput(input) { var result = input.split(/[ \t\n]+/); var finalList = []; for (var i = 0; i < result.length; i++) { var currentWord = result[i]; if (currentWord.endsWith(",") || currentWord.endsWith(".") || currentWord.endsWith("!") || currentWord.endsWith("?") || currentWord.endsWith(";") || currentWord.endsWith(":")) { var newWord = currentWord.replace(/[,.!?;:/]/, ""); finalList.push(newWord); finalList.push(newWord); } else { finalList.push(currentWord); } } return finalList; }
function processInput(input) { var result = input.split(/[ \t\n]+/); var finalList = []; for (var i = 0; i < result.length; i++) { var currentWord = result[i]; if (currentWord.endsWith(",") || currentWord.endsWith(".") || currentWord.endsWith("!") || currentWord.endsWith("?") || currentWord.endsWith(";") || currentWord.endsWith(":")) { var newWord = currentWord.replace(/[,.!?;:/]/, ""); finalList.push(newWord); finalList.push(newWord); } else { finalList.push(currentWord); } } return finalList; }
JavaScript
function outputDisplay(boolean) { var outputPanel = document.getElementById("output"); if (boolean) { outputPanel.innerHTML = wordsList[counter]; } else { outputPanel.innerHTML = ""; } }
function outputDisplay(boolean) { var outputPanel = document.getElementById("output"); if (boolean) { outputPanel.innerHTML = wordsList[counter]; } else { outputPanel.innerHTML = ""; } }
JavaScript
function disableBtn(button, boolean) { button.disabled = boolean; if (boolean) { button.className = "disabled"; } else { button.classList.remove("disabled"); } }
function disableBtn(button, boolean) { button.disabled = boolean; if (boolean) { button.className = "disabled"; } else { button.classList.remove("disabled"); } }
JavaScript
function fetchBooksFrontPage() { var url = "bestreads.php?mode=books"; var booksPromise = new AjaxGetPromise(url); booksPromise .then(JSON.parse) .then(appendBooks) .catch(function (errorMsg) { alert("fetch ERROR: " + errorMsg); }); }
function fetchBooksFrontPage() { var url = "bestreads.php?mode=books"; var booksPromise = new AjaxGetPromise(url); booksPromise .then(JSON.parse) .then(appendBooks) .catch(function (errorMsg) { alert("fetch ERROR: " + errorMsg); }); }
JavaScript
function appendBooks(data) { var entries = data.books; for (var i = 0; i < entries.length; i++) { var div = document.createElement("div"); var img = document.createElement("img"); img.src = "books/" + entries[i].folder + "/cover.jpg"; var title = document.createElement("p"); title.innerHTML = entries[i].title; img.id = entries[i].folder; // id attributes title.id = entries[i].folder; div.id = entries[i].folder; div.onclick = fetchSingleBookData; // onClick function div.appendChild(img); div.appendChild(title); $("allbooks").appendChild(div); } }
function appendBooks(data) { var entries = data.books; for (var i = 0; i < entries.length; i++) { var div = document.createElement("div"); var img = document.createElement("img"); img.src = "books/" + entries[i].folder + "/cover.jpg"; var title = document.createElement("p"); title.innerHTML = entries[i].title; img.id = entries[i].folder; // id attributes title.id = entries[i].folder; div.id = entries[i].folder; div.onclick = fetchSingleBookData; // onClick function div.appendChild(img); div.appendChild(title); $("allbooks").appendChild(div); } }
JavaScript
function fetchSingleBookData() { $("allbooks").classList.add("hidden"); $("singlebook").classList.remove("hidden"); var bookTitle = this.id; // Get Description var singleBookDescription = createNewAjaxGetPromise(bookTitle, "description"); singleBookDescription .then(function (data) { $("description").innerHTML = data; }) .catch(function (errorMsg) { alert("single desc ERROR: " + errorMsg); }); // Get Info var singleBookInfo = createNewAjaxGetPromise(bookTitle, "info"); singleBookInfo .then(JSON.parse) .then(function (data) { $("title").innerHTML = data.title; $("author").innerHTML = data.author; $("stars").innerHTML = data.stars; }) .catch(function (errorMsg) { alert("single info ERROR: " + errorMsg); }); // Get Reviews var singleBookReviews = createNewAjaxGetPromise(bookTitle, "reviews"); singleBookReviews .then(JSON.parse) .then(appendReviews) .then(function () { $("cover").src = "books/" + bookTitle + "/cover.jpg"; }) .catch(function (errorMsg) { alert("single review ERROR: " + errorMsg); }); }
function fetchSingleBookData() { $("allbooks").classList.add("hidden"); $("singlebook").classList.remove("hidden"); var bookTitle = this.id; // Get Description var singleBookDescription = createNewAjaxGetPromise(bookTitle, "description"); singleBookDescription .then(function (data) { $("description").innerHTML = data; }) .catch(function (errorMsg) { alert("single desc ERROR: " + errorMsg); }); // Get Info var singleBookInfo = createNewAjaxGetPromise(bookTitle, "info"); singleBookInfo .then(JSON.parse) .then(function (data) { $("title").innerHTML = data.title; $("author").innerHTML = data.author; $("stars").innerHTML = data.stars; }) .catch(function (errorMsg) { alert("single info ERROR: " + errorMsg); }); // Get Reviews var singleBookReviews = createNewAjaxGetPromise(bookTitle, "reviews"); singleBookReviews .then(JSON.parse) .then(appendReviews) .then(function () { $("cover").src = "books/" + bookTitle + "/cover.jpg"; }) .catch(function (errorMsg) { alert("single review ERROR: " + errorMsg); }); }
JavaScript
function appendReviews(data) { for (var i = 0; i < data.length; i++) { var section = document.createElement("section"); var h3 = document.createElement("h3"); h3.innerHTML = data[i].name + " "; var span = document.createElement("span"); span.innerHTML = data[i].score; h3.appendChild(span); var p = document.createElement("p"); p.innerHTML = data[i].text; section.appendChild(h3); section.appendChild(p); $("reviews").appendChild(section); } }
function appendReviews(data) { for (var i = 0; i < data.length; i++) { var section = document.createElement("section"); var h3 = document.createElement("h3"); h3.innerHTML = data[i].name + " "; var span = document.createElement("span"); span.innerHTML = data[i].score; h3.appendChild(span); var p = document.createElement("p"); p.innerHTML = data[i].text; section.appendChild(h3); section.appendChild(p); $("reviews").appendChild(section); } }
JavaScript
static initShaders(gl, vs_script, fs_script) { let v_shader = WebGLHelper.getShader(gl, gl.VERTEX_SHADER, vs_script); let f_shader = WebGLHelper.getShader(gl, gl.FRAGMENT_SHADER, fs_script); let program = gl.createProgram(); gl.attachShader(program, v_shader); gl.attachShader(program, f_shader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw ("Linking error: " + gl.getProgramInfoLog(program)); } return program; }
static initShaders(gl, vs_script, fs_script) { let v_shader = WebGLHelper.getShader(gl, gl.VERTEX_SHADER, vs_script); let f_shader = WebGLHelper.getShader(gl, gl.FRAGMENT_SHADER, fs_script); let program = gl.createProgram(); gl.attachShader(program, v_shader); gl.attachShader(program, f_shader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw ("Linking error: " + gl.getProgramInfoLog(program)); } return program; }
JavaScript
static initBuffers(gl, program, data) { let buffers = {} let indexBuffers = {} let fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { // Create the buffer let buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); buffers[item.name] = buffer; if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { let indexBuffer = gl.createBuffer(); indexBuffers[item.name] = indexBuffer; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute let attribute = gl.getAttribLocation(program, item.name); let stride = fSize * (item.stride || 0); let offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); program["buffers"] = buffers; program["indexBuffers"] = indexBuffers; return buffers; }
static initBuffers(gl, program, data) { let buffers = {} let indexBuffers = {} let fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { // Create the buffer let buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); buffers[item.name] = buffer; if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { let indexBuffer = gl.createBuffer(); indexBuffers[item.name] = indexBuffer; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute let attribute = gl.getAttribLocation(program, item.name); let stride = fSize * (item.stride || 0); let offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); program["buffers"] = buffers; program["indexBuffers"] = indexBuffers; return buffers; }
JavaScript
static resetBuffers(gl, program, data) { let fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { gl.bindBuffer(gl.ARRAY_BUFFER, program.buffers[item.name]); if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, program.indexBuffers[item.name]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute let attribute = gl.getAttribLocation(program, item.name); let stride = fSize * (item.stride || 0); let offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); }
static resetBuffers(gl, program, data) { let fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { gl.bindBuffer(gl.ARRAY_BUFFER, program.buffers[item.name]); if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, program.indexBuffers[item.name]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute let attribute = gl.getAttribLocation(program, item.name); let stride = fSize * (item.stride || 0); let offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); }
JavaScript
static clear(gl, color) { gl.clearColor(...color); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }
static clear(gl, color) { gl.clearColor(...color); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }
JavaScript
static toWebGlCoordinates(e) { let rect = e.target.getBoundingClientRect(); // x = (2u - w) / w let x = (2 * (e.clientX - rect.left) - rect.width) / rect.width; // y = (h - 2v) / h let y = (rect.height - 2 * (e.clientY - rect.top)) / rect.height; return [x, y]; }
static toWebGlCoordinates(e) { let rect = e.target.getBoundingClientRect(); // x = (2u - w) / w let x = (2 * (e.clientX - rect.left) - rect.width) / rect.width; // y = (h - 2v) / h let y = (rect.height - 2 * (e.clientY - rect.top)) / rect.height; return [x, y]; }
JavaScript
function initShaders(gl, vs_script, fs_script) { var v_shader = getShader(gl, gl.VERTEX_SHADER, vs_script); var f_shader = getShader(gl, gl.FRAGMENT_SHADER, fs_script); var program = gl.createProgram(); gl.attachShader(program, v_shader); gl.attachShader(program, f_shader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw ("Linking error: " + gl.getProgramInfoLog(program)); } return program; }
function initShaders(gl, vs_script, fs_script) { var v_shader = getShader(gl, gl.VERTEX_SHADER, vs_script); var f_shader = getShader(gl, gl.FRAGMENT_SHADER, fs_script); var program = gl.createProgram(); gl.attachShader(program, v_shader); gl.attachShader(program, f_shader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw ("Linking error: " + gl.getProgramInfoLog(program)); } return program; }
JavaScript
function initBuffers(gl, program, data) { var buffers = {} var fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { // Create the buffer var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); buffers[item.name] = buffer; if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { var indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute var attribute = gl.getAttribLocation(program, item.name); var stride = fSize * (item.stride || 0); var offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); program["buffers"] = buffers; return buffers; }
function initBuffers(gl, program, data) { var buffers = {} var fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { // Create the buffer var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); buffers[item.name] = buffer; if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { var indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute var attribute = gl.getAttribLocation(program, item.name); var stride = fSize * (item.stride || 0); var offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); program["buffers"] = buffers; return buffers; }
JavaScript
function resetBuffers(gl, program, data) { var fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { gl.bindBuffer(gl.ARRAY_BUFFER, program.buffers[item.name]); if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { var indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute var attribute = gl.getAttribLocation(program, item.name); var stride = fSize * (item.stride || 0); var offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); }
function resetBuffers(gl, program, data) { var fSize = Float32Array.BYTES_PER_ELEMENT; data.forEach(function (item) { if (item.data !== undefined) { gl.bindBuffer(gl.ARRAY_BUFFER, program.buffers[item.name]); if (typeof (item.data) !== 'number') { gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(item.data), gl.STATIC_DRAW); } else { gl.bufferData(gl.ARRAY_BUFFER, fSize * item.size * item.data, gl.STATIC_DRAW); } if (item.indices !== undefined) { var indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(item.indices), gl.STATIC_DRAW); } } // Get the location of and enable the attribute var attribute = gl.getAttribLocation(program, item.name); var stride = fSize * (item.stride || 0); var offset = fSize * (item.offset || 0); gl.vertexAttribPointer(attribute, item.size, gl.FLOAT, false, stride, offset); gl.enableVertexAttribArray(attribute); }); }
JavaScript
function loadTextures(gl, program, images) { var textures = []; images.forEach(function (image) { var texture = gl.createTexture(); gl.activeTexture(image.sampler2D[0]); gl.bindTexture(gl.TEXTURE_2D, texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, image.size, image.size, 0, gl.RGBA, gl.UNSIGNED_BYTE, image.data); gl.generateMipmap(gl.TEXTURE_2D); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.uniform1i(gl.getUniformLocation(program, image.sampler2D[1]), image.sampler2D[2]); textures.push(texture); }); return textures; }
function loadTextures(gl, program, images) { var textures = []; images.forEach(function (image) { var texture = gl.createTexture(); gl.activeTexture(image.sampler2D[0]); gl.bindTexture(gl.TEXTURE_2D, texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, image.size, image.size, 0, gl.RGBA, gl.UNSIGNED_BYTE, image.data); gl.generateMipmap(gl.TEXTURE_2D); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.uniform1i(gl.getUniformLocation(program, image.sampler2D[1]), image.sampler2D[2]); textures.push(texture); }); return textures; }
JavaScript
function loadTexturesFromUrls(gl, program, images) { var textures = []; images.forEach(function (image) { var texture = gl.createTexture(); gl.activeTexture(image.sampler2D[0]); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 255, 255])); var img = new Image(); img.onload = function () { gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img); if (isPowerOfTwo(img.width) && isPowerOfTwo(img.height)) { gl.generateMipmap(gl.TEXTURE_2D); } else { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); } gl.uniform1i(gl.getUniformLocation(program, image.sampler2D[1]), image.sampler2D[2]); }; img.src = image.url; textures.push(texture); }); return textures; }
function loadTexturesFromUrls(gl, program, images) { var textures = []; images.forEach(function (image) { var texture = gl.createTexture(); gl.activeTexture(image.sampler2D[0]); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 255, 255])); var img = new Image(); img.onload = function () { gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img); if (isPowerOfTwo(img.width) && isPowerOfTwo(img.height)) { gl.generateMipmap(gl.TEXTURE_2D); } else { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); } gl.uniform1i(gl.getUniformLocation(program, image.sampler2D[1]), image.sampler2D[2]); }; img.src = image.url; textures.push(texture); }); return textures; }
JavaScript
function clear(gl, color) { gl.clearColor(...color); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }
function clear(gl, color) { gl.clearColor(...color); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }
JavaScript
function triangleNormals(a, b, c, negated) { var ab = vec3.sub(vec3.create(), b, a); var bc = vec3.sub(vec3.create(), c, b); var cross = vec3.cross(vec3.create(), ab, bc); if (negated) cross = vec3.negate(cross, cross); var n1 = [cross[0], cross[1], cross[2]]; return [].concat(n1).concat(n1).concat(n1); }
function triangleNormals(a, b, c, negated) { var ab = vec3.sub(vec3.create(), b, a); var bc = vec3.sub(vec3.create(), c, b); var cross = vec3.cross(vec3.create(), ab, bc); if (negated) cross = vec3.negate(cross, cross); var n1 = [cross[0], cross[1], cross[2]]; return [].concat(n1).concat(n1).concat(n1); }
JavaScript
function rectangleNormals(a, b, c, d, negated) { var n1 = triangleNormals(a, b, c, negated); var n2 = triangleNormals(a, c, d, negated); return [].concat(n1).concat(n2); }
function rectangleNormals(a, b, c, d, negated) { var n1 = triangleNormals(a, b, c, negated); var n2 = triangleNormals(a, c, d, negated); return [].concat(n1).concat(n2); }
JavaScript
function forceLength(str, len) { str = str.toString(); var diff = len - str.length; for (var i = 0; i < diff; i++) str = '0' + str; return str; }
function forceLength(str, len) { str = str.toString(); var diff = len - str.length; for (var i = 0; i < diff; i++) str = '0' + str; return str; }
JavaScript
function elem (tagName, className, kids) { var result = document.createElement(tagName); result.className = className || ""; if (kids) { kids.forEach(function (kid) {result.appendChild(kid);}) } return result; }
function elem (tagName, className, kids) { var result = document.createElement(tagName); result.className = className || ""; if (kids) { kids.forEach(function (kid) {result.appendChild(kid);}) } return result; }
JavaScript
function splitLongWord (word) { var result = _maybeSplitLongWord(word); if (result.length > 1) { for (var i=0; i<result.length-1; i++) { result[i] += "-"; } } return result; }
function splitLongWord (word) { var result = _maybeSplitLongWord(word); if (result.length > 1) { for (var i=0; i<result.length-1; i++) { result[i] += "-"; } } return result; }
JavaScript
function Instructionator () { // state var instructions = [] , modifier = "normal" , wraps = [] , spacerInstruction = null , done = false; // add a modifier to the next token this.modNext = function (mod) { modifier = maxModifier(modifier, mod); }; // add a modifier to the previous token this.modPrev = function (mod) { if (instructions.length > 0) { var current = instructions[instructions.length-1].modifier; instructions[instructions.length-1].modifier = maxModifier(current, mod); } }; // start a wrap on the next token this.pushWrap = function (wrap) { wraps.push(wrap); }; // stop the specified wrap before the next token. // Pops off any wraps in the way this.popWrap = function (wrap) { var idx = wraps.lastIndexOf(wrap); if (idx > -1) wraps.splice(wraps.lastIndexOf(wrap), wraps.length); }; // pop all wraps this.clearWrap = function (wrap) { wraps = []; }; var _addWraps = function (instr) { instr.leftWrap = wraps.map(function (w) { return w.left; }).join(""); instr.rightWrap = wraps.map(function (w) { return w.right; }).reverse().join(""); return instr; } // put a spacer before the next token this.spacer = function () { if (spacerInstruction) { spacerInstruction.modifier = "long_space"; } else { spacerInstruction = _addWraps({ token: " ", modifier: "short_space" }); } }; var _emit = function (token) { if (spacerInstruction) { instructions.push(spacerInstruction); } instructions.push(_addWraps({ token: token, modifier: modifier })); modifier = "normal"; spacerInstruction = null; }; // add the token this.token = function (tkn) { if (wordShouldBeSplitUp(tkn)) { splitLongWord(tkn).forEach(_emit); } else { _emit(tkn); } }; this.getInstructions = function () { return instructions; }; }
function Instructionator () { // state var instructions = [] , modifier = "normal" , wraps = [] , spacerInstruction = null , done = false; // add a modifier to the next token this.modNext = function (mod) { modifier = maxModifier(modifier, mod); }; // add a modifier to the previous token this.modPrev = function (mod) { if (instructions.length > 0) { var current = instructions[instructions.length-1].modifier; instructions[instructions.length-1].modifier = maxModifier(current, mod); } }; // start a wrap on the next token this.pushWrap = function (wrap) { wraps.push(wrap); }; // stop the specified wrap before the next token. // Pops off any wraps in the way this.popWrap = function (wrap) { var idx = wraps.lastIndexOf(wrap); if (idx > -1) wraps.splice(wraps.lastIndexOf(wrap), wraps.length); }; // pop all wraps this.clearWrap = function (wrap) { wraps = []; }; var _addWraps = function (instr) { instr.leftWrap = wraps.map(function (w) { return w.left; }).join(""); instr.rightWrap = wraps.map(function (w) { return w.right; }).reverse().join(""); return instr; } // put a spacer before the next token this.spacer = function () { if (spacerInstruction) { spacerInstruction.modifier = "long_space"; } else { spacerInstruction = _addWraps({ token: " ", modifier: "short_space" }); } }; var _emit = function (token) { if (spacerInstruction) { instructions.push(spacerInstruction); } instructions.push(_addWraps({ token: token, modifier: modifier })); modifier = "normal"; spacerInstruction = null; }; // add the token this.token = function (tkn) { if (wordShouldBeSplitUp(tkn)) { splitLongWord(tkn).forEach(_emit); } else { _emit(tkn); } }; this.getInstructions = function () { return instructions; }; }
JavaScript
function prevSentence () { index = Math.max(0, index - 5); while (index > 0 && !startModifiers[instructions[index].modifier]) { index--; } if (!running) updateReader(); }
function prevSentence () { index = Math.max(0, index - 5); while (index > 0 && !startModifiers[instructions[index].modifier]) { index--; } if (!running) updateReader(); }
JavaScript
function nextSentence () { index = Math.min(index+1, instructions.length - 1); while (index < instructions.length - 1 && !startModifiers[instructions[index].modifier]) { index++; } if (!running) updateReader(); }
function nextSentence () { index = Math.min(index+1, instructions.length - 1); while (index < instructions.length - 1 && !startModifiers[instructions[index].modifier]) { index++; } if (!running) updateReader(); }
JavaScript
function prevParagraph () { index = Math.max(0, index - 5); while (index > 0 && instructions[index].modifier != "start_paragraph") { index--; } if (!running) updateReader(); }
function prevParagraph () { index = Math.max(0, index - 5); while (index > 0 && instructions[index].modifier != "start_paragraph") { index--; } if (!running) updateReader(); }
JavaScript
function nextParagraph () { index = Math.min(index+1, instructions.length - 1); while (index < instructions.length - 1 && instructions[index].modifier != "start_paragraph") { index++; } if (!running) updateReader(); }
function nextParagraph () { index = Math.min(index+1, instructions.length - 1); while (index < instructions.length - 1 && instructions[index].modifier != "start_paragraph") { index++; } if (!running) updateReader(); }
JavaScript
function adjustScale (diff) { var current = config("scale"); var adjusted = clamp(0.1, current + diff, 10); config("scale", adjusted); reader && reader.setScale(adjusted); }
function adjustScale (diff) { var current = config("scale"); var adjusted = clamp(0.1, current + diff, 10); config("scale", adjusted); reader && reader.setScale(adjusted); }
JavaScript
function adjustWPM (diff) { var current = config("target_wpm"); var adjusted = clamp(100, current + diff, 1500); config("target_wpm", adjusted); reader && reader.setWPM(adjusted); }
function adjustWPM (diff) { var current = config("target_wpm"); var adjusted = clamp(100, current + diff, 1500); config("target_wpm", adjusted); reader && reader.setWPM(adjusted); }
JavaScript
function toggleTheme () { var current = config("dark"); config("dark", !current); reader && reader.setTheme(config("dark")); }
function toggleTheme () { var current = config("dark"); config("dark", !current); reader && reader.setTheme(config("dark")); }
JavaScript
function init (content) { if (!instructions) { // plain string if (typeof content === 'string' && content.trim().length > 0) { instructions = parseText(content.trim()); // dom node } else if (content.textContent && content.textContent.trim().length > 0) { // TODO: write proper dom parsing function //instructions = parseText(content.textContent.trim()); instructions = parseDom(content); } else if (realTypeOf(content) === "Array") { instructions = content; } else { throw new Error("jetzt doesn't know how to deal with this object:", content); } reader = new Reader(); reader.onBackdropClick(close); reader.onKeyDown(handleKeydown) reader.show(); index = 0; setTimeout(toggleRunning, 500); } else { throw new Error("jetzt already initialized"); } }
function init (content) { if (!instructions) { // plain string if (typeof content === 'string' && content.trim().length > 0) { instructions = parseText(content.trim()); // dom node } else if (content.textContent && content.textContent.trim().length > 0) { // TODO: write proper dom parsing function //instructions = parseText(content.textContent.trim()); instructions = parseDom(content); } else if (realTypeOf(content) === "Array") { instructions = content; } else { throw new Error("jetzt doesn't know how to deal with this object:", content); } reader = new Reader(); reader.onBackdropClick(close); reader.onKeyDown(handleKeydown) reader.show(); index = 0; setTimeout(toggleRunning, 500); } else { throw new Error("jetzt already initialized"); } }
JavaScript
function selectMode () { var highlight = "sr-highlight"; var previousElement; var mouseoverHandler = function (ev) { if (previousElement && previousElement === ev.target) { // same element return; } if (previousElement) { removeClass(previousElement, highlight); } addClass(ev.target, highlight); previousElement = ev.target; }; var stop = function () { window.removeEventListener("mouseover", mouseoverHandler); window.removeEventListener("click", clickHandler); previousElement && removeClass(previousElement, highlight); }; var clickHandler = function (ev) { stop(); init(ev.target); }; var moveHandler = function (ev) { mouseoverHandler(ev); window.removeEventListener("mousemove", moveHandler); }; var escHandler = function (ev) { if (ev.keyCode === 27) { stop(); } window.removeEventListener("keydown", escHandler); }; window.addEventListener("mouseover", mouseoverHandler); window.addEventListener("click", clickHandler); window.addEventListener("mousemove", moveHandler); window.addEventListener("keydown", escHandler); }
function selectMode () { var highlight = "sr-highlight"; var previousElement; var mouseoverHandler = function (ev) { if (previousElement && previousElement === ev.target) { // same element return; } if (previousElement) { removeClass(previousElement, highlight); } addClass(ev.target, highlight); previousElement = ev.target; }; var stop = function () { window.removeEventListener("mouseover", mouseoverHandler); window.removeEventListener("click", clickHandler); previousElement && removeClass(previousElement, highlight); }; var clickHandler = function (ev) { stop(); init(ev.target); }; var moveHandler = function (ev) { mouseoverHandler(ev); window.removeEventListener("mousemove", moveHandler); }; var escHandler = function (ev) { if (ev.keyCode === 27) { stop(); } window.removeEventListener("keydown", escHandler); }; window.addEventListener("mouseover", mouseoverHandler); window.addEventListener("click", clickHandler); window.addEventListener("mousemove", moveHandler); window.addEventListener("keydown", escHandler); }
JavaScript
function buildMarkovModel(examples, markovChainOrder) { var letterCounts = {}; var existingWords = {}; for (var i = 0; i < examples.length; i++) { var word = examples[i]; existingWords[word] = true; for (var j = 0; j < word.length + 1; j++) { var previousLetters = word.substring(j - markovChainOrder, j); var currentLetter = word[j] || ""; if (letterCounts[previousLetters] === undefined) { letterCounts[previousLetters] = { total: 0 }; } letterCounts[previousLetters].total += 1; if (letterCounts[previousLetters][currentLetter] == undefined) { letterCounts[previousLetters][currentLetter] = 1; } else { letterCounts[previousLetters][currentLetter] += 1; } } } function generateNextLetter(previousLetters) { var rand = getRandomInt(0, letterCounts[previousLetters]["total"]); for (var y in letterCounts[previousLetters]) { if (y != "total") { if (rand < letterCounts[previousLetters][y]) { return y; } else { rand -= letterCounts[previousLetters][y]; } } } return undefined; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; }; } function generateAnyWord() { var word = ""; var nextLetter = undefined; while (nextLetter != "") { // generating a blank string means end of word! nextLetter = generateNextLetter(word.substring(word.length - markovChainOrder)); word += nextLetter; } return word; } /** * Probably not the best method name but that's what comments are for. * * A word is qualifying if it is * (a) Not already in the list of words that we pasted in * (b) Matches our filter criteria */ function generateQualifyingWord(minLength, maxLength, matchingRegex) { while (true) { var word = generateAnyWord(); if (existingWords[word] == undefined && (isNaN(minLength) || word.length >= minLength) && (isNaN(maxLength) || word.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(word)) ) { return word; } } } return { generateWord: generateQualifyingWord } }
function buildMarkovModel(examples, markovChainOrder) { var letterCounts = {}; var existingWords = {}; for (var i = 0; i < examples.length; i++) { var word = examples[i]; existingWords[word] = true; for (var j = 0; j < word.length + 1; j++) { var previousLetters = word.substring(j - markovChainOrder, j); var currentLetter = word[j] || ""; if (letterCounts[previousLetters] === undefined) { letterCounts[previousLetters] = { total: 0 }; } letterCounts[previousLetters].total += 1; if (letterCounts[previousLetters][currentLetter] == undefined) { letterCounts[previousLetters][currentLetter] = 1; } else { letterCounts[previousLetters][currentLetter] += 1; } } } function generateNextLetter(previousLetters) { var rand = getRandomInt(0, letterCounts[previousLetters]["total"]); for (var y in letterCounts[previousLetters]) { if (y != "total") { if (rand < letterCounts[previousLetters][y]) { return y; } else { rand -= letterCounts[previousLetters][y]; } } } return undefined; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; }; } function generateAnyWord() { var word = ""; var nextLetter = undefined; while (nextLetter != "") { // generating a blank string means end of word! nextLetter = generateNextLetter(word.substring(word.length - markovChainOrder)); word += nextLetter; } return word; } /** * Probably not the best method name but that's what comments are for. * * A word is qualifying if it is * (a) Not already in the list of words that we pasted in * (b) Matches our filter criteria */ function generateQualifyingWord(minLength, maxLength, matchingRegex) { while (true) { var word = generateAnyWord(); if (existingWords[word] == undefined && (isNaN(minLength) || word.length >= minLength) && (isNaN(maxLength) || word.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(word)) ) { return word; } } } return { generateWord: generateQualifyingWord } }
JavaScript
function generateQualifyingWord(minLength, maxLength, matchingRegex) { while (true) { var word = generateAnyWord(); if (existingWords[word] == undefined && (isNaN(minLength) || word.length >= minLength) && (isNaN(maxLength) || word.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(word)) ) { return word; } } }
function generateQualifyingWord(minLength, maxLength, matchingRegex) { while (true) { var word = generateAnyWord(); if (existingWords[word] == undefined && (isNaN(minLength) || word.length >= minLength) && (isNaN(maxLength) || word.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(word)) ) { return word; } } }
JavaScript
function buildMarkovModelGeneralPurpose(examples, markovChainOrder) { var tokenCounts = {}; // A place to hold our counts var existingSequences = {}; // A list of sequences we've seen while building the model for (var i = 0; i < examples.length; i++) { existingSequences[examples[i]] = true; for (var j = 0; j < examples[i].length; j++) { // We want to count the occurrence of this token, but we must look at the past tokens to know what to increment var previousTokens = examples[i].slice(Math.max(j - markovChainOrder, 0), j); if (tokenCounts[previousTokens] === undefined) { tokenCounts[previousTokens] = wordCounter(); } var token = examples[i][j]; tokenCounts[previousTokens].addNextToken(token); } var previousTokens = examples[i].slice(Math.max(j - markovChainOrder, 0), j); if (tokenCounts[previousTokens] === undefined) { tokenCounts[previousTokens] = wordCounter(); } tokenCounts[previousTokens].addNextToken(''); // use an empty string to denote end-of-sequence } /** * Returns 2 functions related to counting tokens * * addNextToken is used to count what tokens we are counting * * generateNextToken randomly chooses between tokens that we've seen, where potential options are weighted by how * many times they have been seen in examples. * * @returns {{addNextToken: addNextToken, generateNextToken: generateNextToken}} */ function wordCounter() { var nextTokenCounts = {}; var total = 0; function addNextToken(nextToken) { if (nextTokenCounts[nextToken] === undefined) { nextTokenCounts[nextToken] = 0; } nextTokenCounts[nextToken]++; total++; } function generateNextToken(previousTokens) { var rand = getRandomInt(0, total); for (var potentialNext in nextTokenCounts) { rand -= nextTokenCounts[potentialNext]; if (rand < 0) { return potentialNext; } } return "ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR!"; } return { addNextToken: addNextToken, generateNextToken: generateNextToken }; } function generateNextToken(previousTokens) { return tokenCounts[previousTokens].generateNextToken(); } function generateAnySequence() { var previousTokens = []; var nextToken = generateNextToken(previousTokens); var sequence = []; while (nextToken !== '') { sequence.push(nextToken); if (previousTokens.length == markovChainOrder) { previousTokens.shift(); // remove the first element } previousTokens.push(nextToken); nextToken = generateNextToken(previousTokens); } return sequence; } /** * Probably not the best method name but that's what comments are for. * * A sequence is qualifying if it is * (a) Not already in the list of sequences that we pasted in * (b) Matches our filter criteria */ function generateQualifyingSequence(minLength, maxLength, matchingRegex) { while (true) { var sequence = generateAnySequence(); if (existingSequences[sequence] == undefined && (isNaN(minLength) || sequence.length >= minLength) && (isNaN(maxLength) || sequence.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(sequence.join())) ) { return sequence; } } } var getRandomInt = function (min, max) { return Math.floor(Math.random() * (max - min)) + min; }; return { generateWord: generateQualifyingSequence }; }
function buildMarkovModelGeneralPurpose(examples, markovChainOrder) { var tokenCounts = {}; // A place to hold our counts var existingSequences = {}; // A list of sequences we've seen while building the model for (var i = 0; i < examples.length; i++) { existingSequences[examples[i]] = true; for (var j = 0; j < examples[i].length; j++) { // We want to count the occurrence of this token, but we must look at the past tokens to know what to increment var previousTokens = examples[i].slice(Math.max(j - markovChainOrder, 0), j); if (tokenCounts[previousTokens] === undefined) { tokenCounts[previousTokens] = wordCounter(); } var token = examples[i][j]; tokenCounts[previousTokens].addNextToken(token); } var previousTokens = examples[i].slice(Math.max(j - markovChainOrder, 0), j); if (tokenCounts[previousTokens] === undefined) { tokenCounts[previousTokens] = wordCounter(); } tokenCounts[previousTokens].addNextToken(''); // use an empty string to denote end-of-sequence } /** * Returns 2 functions related to counting tokens * * addNextToken is used to count what tokens we are counting * * generateNextToken randomly chooses between tokens that we've seen, where potential options are weighted by how * many times they have been seen in examples. * * @returns {{addNextToken: addNextToken, generateNextToken: generateNextToken}} */ function wordCounter() { var nextTokenCounts = {}; var total = 0; function addNextToken(nextToken) { if (nextTokenCounts[nextToken] === undefined) { nextTokenCounts[nextToken] = 0; } nextTokenCounts[nextToken]++; total++; } function generateNextToken(previousTokens) { var rand = getRandomInt(0, total); for (var potentialNext in nextTokenCounts) { rand -= nextTokenCounts[potentialNext]; if (rand < 0) { return potentialNext; } } return "ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR!"; } return { addNextToken: addNextToken, generateNextToken: generateNextToken }; } function generateNextToken(previousTokens) { return tokenCounts[previousTokens].generateNextToken(); } function generateAnySequence() { var previousTokens = []; var nextToken = generateNextToken(previousTokens); var sequence = []; while (nextToken !== '') { sequence.push(nextToken); if (previousTokens.length == markovChainOrder) { previousTokens.shift(); // remove the first element } previousTokens.push(nextToken); nextToken = generateNextToken(previousTokens); } return sequence; } /** * Probably not the best method name but that's what comments are for. * * A sequence is qualifying if it is * (a) Not already in the list of sequences that we pasted in * (b) Matches our filter criteria */ function generateQualifyingSequence(minLength, maxLength, matchingRegex) { while (true) { var sequence = generateAnySequence(); if (existingSequences[sequence] == undefined && (isNaN(minLength) || sequence.length >= minLength) && (isNaN(maxLength) || sequence.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(sequence.join())) ) { return sequence; } } } var getRandomInt = function (min, max) { return Math.floor(Math.random() * (max - min)) + min; }; return { generateWord: generateQualifyingSequence }; }
JavaScript
function wordCounter() { var nextTokenCounts = {}; var total = 0; function addNextToken(nextToken) { if (nextTokenCounts[nextToken] === undefined) { nextTokenCounts[nextToken] = 0; } nextTokenCounts[nextToken]++; total++; } function generateNextToken(previousTokens) { var rand = getRandomInt(0, total); for (var potentialNext in nextTokenCounts) { rand -= nextTokenCounts[potentialNext]; if (rand < 0) { return potentialNext; } } return "ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR!"; } return { addNextToken: addNextToken, generateNextToken: generateNextToken }; }
function wordCounter() { var nextTokenCounts = {}; var total = 0; function addNextToken(nextToken) { if (nextTokenCounts[nextToken] === undefined) { nextTokenCounts[nextToken] = 0; } nextTokenCounts[nextToken]++; total++; } function generateNextToken(previousTokens) { var rand = getRandomInt(0, total); for (var potentialNext in nextTokenCounts) { rand -= nextTokenCounts[potentialNext]; if (rand < 0) { return potentialNext; } } return "ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR!"; } return { addNextToken: addNextToken, generateNextToken: generateNextToken }; }
JavaScript
function generateQualifyingSequence(minLength, maxLength, matchingRegex) { while (true) { var sequence = generateAnySequence(); if (existingSequences[sequence] == undefined && (isNaN(minLength) || sequence.length >= minLength) && (isNaN(maxLength) || sequence.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(sequence.join())) ) { return sequence; } } }
function generateQualifyingSequence(minLength, maxLength, matchingRegex) { while (true) { var sequence = generateAnySequence(); if (existingSequences[sequence] == undefined && (isNaN(minLength) || sequence.length >= minLength) && (isNaN(maxLength) || sequence.length <= maxLength) && (matchingRegex === undefined || matchingRegex.test(sequence.join())) ) { return sequence; } } }
JavaScript
item(schemaOrSugar) { const schema = require('../../sugar').resolve(schemaOrSugar); this._current.set('items', schema.normalize()); return this; }
item(schemaOrSugar) { const schema = require('../../sugar').resolve(schemaOrSugar); this._current.set('items', schema.normalize()); return this; }
JavaScript
contains(schemaOrSugar) { const schema = require('../../sugar').resolve(schemaOrSugar); this._current.set('contains', schema.normalize()); return this; }
contains(schemaOrSugar) { const schema = require('../../sugar').resolve(schemaOrSugar); this._current.set('contains', schema.normalize()); return this; }
JavaScript
function insertChat(who, text, time){ if (time === undefined){ time = 0; } var control = ""; var date = formatAMPM(new Date()); //console.log(new Date(Number(time))); if (who != "admin"){ control = '<li style="width:100%">' + '<div class="msj macro">' + '<div class="avatar"><img class="img-circle" src="'+ me.avatar +'" /></div>' + '<div class="text text-l">' + '<p>'+ text +'</p>' + '<p><small>'+date+'</small></p>' + '</div>' + '</div>' + '</li>'; } else{ control = '<li style="width:100%;">' + '<div class="msj-rta macro">' + '<div class="text text-r">' + '<p>'+text+'</p>' + '<p><small>'+date+'</small></p>' + '</div>' + '<div class="avatar" style="padding:0px 0px 0px 10px !important"><img class="img-circle" src="'+you.avatar+'" /></div>' + '</li>'; } $("#chat-container ul").append(control); }
function insertChat(who, text, time){ if (time === undefined){ time = 0; } var control = ""; var date = formatAMPM(new Date()); //console.log(new Date(Number(time))); if (who != "admin"){ control = '<li style="width:100%">' + '<div class="msj macro">' + '<div class="avatar"><img class="img-circle" src="'+ me.avatar +'" /></div>' + '<div class="text text-l">' + '<p>'+ text +'</p>' + '<p><small>'+date+'</small></p>' + '</div>' + '</div>' + '</li>'; } else{ control = '<li style="width:100%;">' + '<div class="msj-rta macro">' + '<div class="text text-r">' + '<p>'+text+'</p>' + '<p><small>'+date+'</small></p>' + '</div>' + '<div class="avatar" style="padding:0px 0px 0px 10px !important"><img class="img-circle" src="'+you.avatar+'" /></div>' + '</li>'; } $("#chat-container ul").append(control); }
JavaScript
function listener1 () { equal(flag1, true); equal(flag2, true); listenerCallCount++; }
function listener1 () { equal(flag1, true); equal(flag2, true); listenerCallCount++; }
JavaScript
update (source) { this.transaction(() => { for (let key in source) { let val = this[key]; if (val && isFunction(val.update)) { val.update(source[key]); // Let object update itself. } else { if (VALUES in this && key in this[VALUES]) { this[key] = source[key]; // Model attribute handles updates. } else { if (Object.is(val, source[key])) { continue; // No changes of regular property. } this[key] = source[key]; this.dispatchEvent(new ChangeEvent(key)); } } } }); return this; }
update (source) { this.transaction(() => { for (let key in source) { let val = this[key]; if (val && isFunction(val.update)) { val.update(source[key]); // Let object update itself. } else { if (VALUES in this && key in this[VALUES]) { this[key] = source[key]; // Model attribute handles updates. } else { if (Object.is(val, source[key])) { continue; // No changes of regular property. } this[key] = source[key]; this.dispatchEvent(new ChangeEvent(key)); } } } }); return this; }
JavaScript
function userUpdatePassRules(req, res, next) { if ((req.user.sub_type === UserType.ADMIN || req.user.sub_type === UserType.FAMILY || req.user.sub_type === UserType.EDUCATOR || req.user.sub_type === UserType.HEALTH_PROFESSIONAL) && equalUserIds(req)) { next() return } errorHandler(403, res) }
function userUpdatePassRules(req, res, next) { if ((req.user.sub_type === UserType.ADMIN || req.user.sub_type === UserType.FAMILY || req.user.sub_type === UserType.EDUCATOR || req.user.sub_type === UserType.HEALTH_PROFESSIONAL) && equalUserIds(req)) { next() return } errorHandler(403, res) }
JavaScript
async function requestResourceByUserIdRules(urlBase, req, res, next) { if (req.user.sub_type === UserType.CHILD && req.params.user_id !== req.user.sub) errorHandler(403, res, req) else { resultSearch = await searchChildById(urlBase, req) if (resultSearch === true) { if (req.user.sub_type === UserType.APPLICATION || req.user.sub_type === UserType.CHILD) next() else if ((req.user.sub_type === UserType.EDUCATOR || req.user.sub_type === UserType.HEALTH_PROFESSIONAL) && await isAssociatedChild(urlBase, req)) next() else if (req.user.sub_type === UserType.FAMILY && await isAssociatedChild(urlBase, req)) next() else errorHandler(403, res, req) } else errorHandler(-1, res, req, resultSearch) } }
async function requestResourceByUserIdRules(urlBase, req, res, next) { if (req.user.sub_type === UserType.CHILD && req.params.user_id !== req.user.sub) errorHandler(403, res, req) else { resultSearch = await searchChildById(urlBase, req) if (resultSearch === true) { if (req.user.sub_type === UserType.APPLICATION || req.user.sub_type === UserType.CHILD) next() else if ((req.user.sub_type === UserType.EDUCATOR || req.user.sub_type === UserType.HEALTH_PROFESSIONAL) && await isAssociatedChild(urlBase, req)) next() else if (req.user.sub_type === UserType.FAMILY && await isAssociatedChild(urlBase, req)) next() else errorHandler(403, res, req) } else errorHandler(-1, res, req, resultSearch) } }
JavaScript
function createWasm() { // prepare imports var info = { 'env': asmLibraryArg, 'wasi_snapshot_preview1': asmLibraryArg }; // Load the wasm module and create an instance of using native support in the JS engine. // handle a generated wasm instance, receiving its exports and // performing other necessary setup function receiveInstance(instance, module) { var exports = instance.exports; Module['asm'] = exports; removeRunDependency('wasm-instantiate'); } // we can't run yet (except in a pthread, where we have a custom sync instantiator) addRunDependency('wasm-instantiate'); function receiveInstantiatedSource(output) { // 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance. // receiveInstance() will swap in the exports (to Module.asm) so they can be called // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line. // When the regression is fixed, can restore the above USE_PTHREADS-enabled path. receiveInstance(output['instance']); } function instantiateArrayBuffer(receiver) { return getBinaryPromise().then(function(binary) { return WebAssembly.instantiate(binary, info); }).then(receiver, function(reason) { err('failed to asynchronously prepare wasm: ' + reason); abort(reason); }); } // Prefer streaming instantiation if available. function instantiateAsync() { if (!wasmBinary && typeof WebAssembly.instantiateStreaming === 'function' && !isDataURI(wasmBinaryFile) && typeof fetch === 'function') { fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) { var result = WebAssembly.instantiateStreaming(response, info); return result.then(receiveInstantiatedSource, function(reason) { // We expect the most common failure cause to be a bad MIME type for the binary, // in which case falling back to ArrayBuffer instantiation should work. err('wasm streaming compile failed: ' + reason); err('falling back to ArrayBuffer instantiation'); instantiateArrayBuffer(receiveInstantiatedSource); }); }); } else { return instantiateArrayBuffer(receiveInstantiatedSource); } } // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel // to any other async startup actions they are performing. if (Module['instantiateWasm']) { try { var exports = Module['instantiateWasm'](info, receiveInstance); return exports; } catch(e) { err('Module.instantiateWasm callback failed with error: ' + e); return false; } } instantiateAsync(); return {}; // no exports yet; we'll fill them in later }
function createWasm() { // prepare imports var info = { 'env': asmLibraryArg, 'wasi_snapshot_preview1': asmLibraryArg }; // Load the wasm module and create an instance of using native support in the JS engine. // handle a generated wasm instance, receiving its exports and // performing other necessary setup function receiveInstance(instance, module) { var exports = instance.exports; Module['asm'] = exports; removeRunDependency('wasm-instantiate'); } // we can't run yet (except in a pthread, where we have a custom sync instantiator) addRunDependency('wasm-instantiate'); function receiveInstantiatedSource(output) { // 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance. // receiveInstance() will swap in the exports (to Module.asm) so they can be called // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line. // When the regression is fixed, can restore the above USE_PTHREADS-enabled path. receiveInstance(output['instance']); } function instantiateArrayBuffer(receiver) { return getBinaryPromise().then(function(binary) { return WebAssembly.instantiate(binary, info); }).then(receiver, function(reason) { err('failed to asynchronously prepare wasm: ' + reason); abort(reason); }); } // Prefer streaming instantiation if available. function instantiateAsync() { if (!wasmBinary && typeof WebAssembly.instantiateStreaming === 'function' && !isDataURI(wasmBinaryFile) && typeof fetch === 'function') { fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) { var result = WebAssembly.instantiateStreaming(response, info); return result.then(receiveInstantiatedSource, function(reason) { // We expect the most common failure cause to be a bad MIME type for the binary, // in which case falling back to ArrayBuffer instantiation should work. err('wasm streaming compile failed: ' + reason); err('falling back to ArrayBuffer instantiation'); instantiateArrayBuffer(receiveInstantiatedSource); }); }); } else { return instantiateArrayBuffer(receiveInstantiatedSource); } } // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel // to any other async startup actions they are performing. if (Module['instantiateWasm']) { try { var exports = Module['instantiateWasm'](info, receiveInstance); return exports; } catch(e) { err('Module.instantiateWasm callback failed with error: ' + e); return false; } } instantiateAsync(); return {}; // no exports yet; we'll fill them in later }
JavaScript
async function run(config, script) { const watcher = chokidar.watch(script); watcher.add(config.watch.map(dir => path.join(config.cwd, dir))); watcher.on('change', async file => { if (state !== StateEnum.STOPPING) { console.log(clc.green(`[RELOADER] Change detected on ${path.relative(config.cwd, file)}. Reloading...`)); await stopProcess(config.killDelay); startProcess(script, config.scriptArgs, config.nodeArgs); } }); process.on('SIGUSR1', async () => { console.log(clc.green('[RELOADER] Caught signal SIGUSR1. Restarting...')); await stopProcess(config.killDelay); startProcess(script, config.scriptArgs, config.nodeArgs); }); startProcess(script, config.scriptArgs, config.nodeArgs); }
async function run(config, script) { const watcher = chokidar.watch(script); watcher.add(config.watch.map(dir => path.join(config.cwd, dir))); watcher.on('change', async file => { if (state !== StateEnum.STOPPING) { console.log(clc.green(`[RELOADER] Change detected on ${path.relative(config.cwd, file)}. Reloading...`)); await stopProcess(config.killDelay); startProcess(script, config.scriptArgs, config.nodeArgs); } }); process.on('SIGUSR1', async () => { console.log(clc.green('[RELOADER] Caught signal SIGUSR1. Restarting...')); await stopProcess(config.killDelay); startProcess(script, config.scriptArgs, config.nodeArgs); }); startProcess(script, config.scriptArgs, config.nodeArgs); }
JavaScript
function startProcess (script, scriptArgs, nodeArgs) { childProcess = fork(script, scriptArgs, { detached: true, execArgv: nodeArgs, }); childProcess.on('exit', (code, signal) => { const msg = code !== null ? `code ${code}` : `signal ${signal}`; console.log(clc.red(`[RELOADER] Process exited with ${msg}. Waiting for a file change to restart it.`)); childProcess = null; state = StateEnum.STOPPED; }); // Exits child process on termination for (const signal of ['SIGINT', 'SIGTERM']) { // eslint-disable-next-line no-loop-func process.on(signal, () => { if (childProcess) { childProcess.kill(signal); } process.exit(); }); } state = StateEnum.RUNNING; }
function startProcess (script, scriptArgs, nodeArgs) { childProcess = fork(script, scriptArgs, { detached: true, execArgv: nodeArgs, }); childProcess.on('exit', (code, signal) => { const msg = code !== null ? `code ${code}` : `signal ${signal}`; console.log(clc.red(`[RELOADER] Process exited with ${msg}. Waiting for a file change to restart it.`)); childProcess = null; state = StateEnum.STOPPED; }); // Exits child process on termination for (const signal of ['SIGINT', 'SIGTERM']) { // eslint-disable-next-line no-loop-func process.on(signal, () => { if (childProcess) { childProcess.kill(signal); } process.exit(); }); } state = StateEnum.RUNNING; }
JavaScript
async function stopProcess (killDelay) { if (state !== StateEnum.RUNNING) { return; } state = StateEnum.STOPPING; childProcess.removeAllListeners(); let exited = false; childProcess.on('exit', () => { exited = true; }); childProcess.kill(); // Wait a certain delay for the process to stop itself and if time is up, kills it const now = Date.now(); let forced = false; while (!exited) { await new Promise(resolve => setTimeout(resolve, 200)); if (!forced && (Date.now() - now) > killDelay) { console.log(clc.red(`[RELOADER] Process still here after ${killDelay}ms. Sending a SIGKILL signal`)); childProcess.kill('SIGKILL'); forced = true; } } state = StateEnum.STOPPED; }
async function stopProcess (killDelay) { if (state !== StateEnum.RUNNING) { return; } state = StateEnum.STOPPING; childProcess.removeAllListeners(); let exited = false; childProcess.on('exit', () => { exited = true; }); childProcess.kill(); // Wait a certain delay for the process to stop itself and if time is up, kills it const now = Date.now(); let forced = false; while (!exited) { await new Promise(resolve => setTimeout(resolve, 200)); if (!forced && (Date.now() - now) > killDelay) { console.log(clc.red(`[RELOADER] Process still here after ${killDelay}ms. Sending a SIGKILL signal`)); childProcess.kill('SIGKILL'); forced = true; } } state = StateEnum.STOPPED; }
JavaScript
function resolveCss(cssText, baseURI) { return cssText.replace(CSS_URL_RX, function(m, pre, url, post) { return pre + '\'' + resolveUrl(url.replace(/["']/g, ''), baseURI) + '\'' + post; }); }
function resolveCss(cssText, baseURI) { return cssText.replace(CSS_URL_RX, function(m, pre, url, post) { return pre + '\'' + resolveUrl(url.replace(/["']/g, ''), baseURI) + '\'' + post; }); }
JavaScript
function cssFromTemplate(template, baseURI) { let cssText = ''; const e$ = stylesFromTemplate(template, baseURI); // if element is a template, get content from its .content for (let i=0; i < e$.length; i++) { let e = e$[i]; if (e.parentNode) { e.parentNode.removeChild(e); } cssText += e.textContent; } return cssText; }
function cssFromTemplate(template, baseURI) { let cssText = ''; const e$ = stylesFromTemplate(template, baseURI); // if element is a template, get content from its .content for (let i=0; i < e$.length; i++) { let e = e$[i]; if (e.parentNode) { e.parentNode.removeChild(e); } cssText += e.textContent; } return cssText; }
JavaScript
get assetpath() { // Don't override existing assetpath. if (!this.__assetpath) { // note: assetpath set via an attribute must be relative to this // element's location; accomodate polyfilled HTMLImports const owner = window.HTMLImports && HTMLImports.importForElement ? HTMLImports.importForElement(this) || document : this.ownerDocument; const url = resolveUrl( this.getAttribute('assetpath') || '', owner.baseURI); this.__assetpath = pathFromUrl(url); } return this.__assetpath; }
get assetpath() { // Don't override existing assetpath. if (!this.__assetpath) { // note: assetpath set via an attribute must be relative to this // element's location; accomodate polyfilled HTMLImports const owner = window.HTMLImports && HTMLImports.importForElement ? HTMLImports.importForElement(this) || document : this.ownerDocument; const url = resolveUrl( this.getAttribute('assetpath') || '', owner.baseURI); this.__assetpath = pathFromUrl(url); } return this.__assetpath; }
JavaScript
register(id) { id = id || this.id; if (id) { this.id = id; // store id separate from lowercased id so that // in all cases mixedCase id will stored distinctly // and lowercase version is a fallback modules[id] = this; lcModules[id.toLowerCase()] = this; styleOutsideTemplateCheck(this); } }
register(id) { id = id || this.id; if (id) { this.id = id; // store id separate from lowercased id so that // in all cases mixedCase id will stored distinctly // and lowercase version is a fallback modules[id] = this; lcModules[id.toLowerCase()] = this; styleOutsideTemplateCheck(this); } }
JavaScript
after(delay) { return { run(fn) { return window.setTimeout(fn, delay); }, cancel(handle) { window.clearTimeout(handle); } }; }
after(delay) { return { run(fn) { return window.setTimeout(fn, delay); }, cancel(handle) { window.clearTimeout(handle); } }; }
JavaScript
run(callback) { microtaskNode.textContent = microtaskNodeContent++; microtaskCallbacks.push(callback); return microtaskCurrHandle++; }
run(callback) { microtaskNode.textContent = microtaskNodeContent++; microtaskCallbacks.push(callback); return microtaskCurrHandle++; }
JavaScript
_createPropertyAccessor(property, readOnly) { this._addPropertyToAttributeMap(property); if (!this.hasOwnProperty('__dataHasAccessor')) { this.__dataHasAccessor = Object.assign({}, this.__dataHasAccessor); } if (!this.__dataHasAccessor[property]) { this.__dataHasAccessor[property] = true; this._definePropertyAccessor(property, readOnly); } }
_createPropertyAccessor(property, readOnly) { this._addPropertyToAttributeMap(property); if (!this.hasOwnProperty('__dataHasAccessor')) { this.__dataHasAccessor = Object.assign({}, this.__dataHasAccessor); } if (!this.__dataHasAccessor[property]) { this.__dataHasAccessor[property] = true; this._definePropertyAccessor(property, readOnly); } }
JavaScript
_addPropertyToAttributeMap(property) { if (!this.hasOwnProperty('__dataAttributes')) { this.__dataAttributes = Object.assign({}, this.__dataAttributes); } if (!this.__dataAttributes[property]) { const attr = this.constructor.attributeNameForProperty(property); this.__dataAttributes[attr] = property; } }
_addPropertyToAttributeMap(property) { if (!this.hasOwnProperty('__dataAttributes')) { this.__dataAttributes = Object.assign({}, this.__dataAttributes); } if (!this.__dataAttributes[property]) { const attr = this.constructor.attributeNameForProperty(property); this.__dataAttributes[attr] = property; } }
JavaScript
_initializeProperties() { // Capture instance properties; these will be set into accessors // during first flush. Don't set them here, since we want // these to overwrite defaults/constructor assignments for (let p in this.__dataHasAccessor) { if (this.hasOwnProperty(p)) { this.__dataInstanceProps = this.__dataInstanceProps || {}; this.__dataInstanceProps[p] = this[p]; delete this[p]; } } }
_initializeProperties() { // Capture instance properties; these will be set into accessors // during first flush. Don't set them here, since we want // these to overwrite defaults/constructor assignments for (let p in this.__dataHasAccessor) { if (this.hasOwnProperty(p)) { this.__dataInstanceProps = this.__dataInstanceProps || {}; this.__dataInstanceProps[p] = this[p]; delete this[p]; } } }
JavaScript
_setPendingProperty(property, value, ext) { let old = this.__data[property]; let changed = this._shouldPropertyChange(property, value, old); if (changed) { if (!this.__dataPending) { this.__dataPending = {}; this.__dataOld = {}; } // Ensure old is captured from the last turn if (this.__dataOld && !(property in this.__dataOld)) { this.__dataOld[property] = old; } this.__data[property] = value; this.__dataPending[property] = value; } return changed; }
_setPendingProperty(property, value, ext) { let old = this.__data[property]; let changed = this._shouldPropertyChange(property, value, old); if (changed) { if (!this.__dataPending) { this.__dataPending = {}; this.__dataOld = {}; } // Ensure old is captured from the last turn if (this.__dataOld && !(property in this.__dataOld)) { this.__dataOld[property] = old; } this.__data[property] = value; this.__dataPending[property] = value; } return changed; }
JavaScript
_enableProperties() { if (!this.__dataEnabled) { this.__dataEnabled = true; if (this.__dataInstanceProps) { this._initializeInstanceProperties(this.__dataInstanceProps); this.__dataInstanceProps = null; } this.ready(); } }
_enableProperties() { if (!this.__dataEnabled) { this.__dataEnabled = true; if (this.__dataInstanceProps) { this._initializeInstanceProperties(this.__dataInstanceProps); this.__dataInstanceProps = null; } this.ready(); } }
JavaScript
_flushProperties() { const props = this.__data; const changedProps = this.__dataPending; const old = this.__dataOld; if (this._shouldPropertiesChange(props, changedProps, old)) { this.__dataPending = null; this.__dataOld = null; this._propertiesChanged(props, changedProps, old); } }
_flushProperties() { const props = this.__data; const changedProps = this.__dataPending; const old = this.__dataOld; if (this._shouldPropertiesChange(props, changedProps, old)) { this.__dataPending = null; this.__dataOld = null; this._propertiesChanged(props, changedProps, old); } }
JavaScript
_shouldPropertyChange(property, value, old) { return ( // Strict equality check (old !== value && // This ensures (old==NaN, value==NaN) always returns false (old === old || value === value)) ); }
_shouldPropertyChange(property, value, old) { return ( // Strict equality check (old !== value && // This ensures (old==NaN, value==NaN) always returns false (old === old || value === value)) ); }
JavaScript
_serializeValue(value) { switch (typeof value) { case 'boolean': return value ? '' : undefined; default: return value != null ? value.toString() : undefined; } }
_serializeValue(value) { switch (typeof value) { case 'boolean': return value ? '' : undefined; default: return value != null ? value.toString() : undefined; } }
JavaScript
_deserializeValue(value, type) { switch (type) { case Boolean: return (value !== null); case Number: return Number(value); default: return value; } }
_deserializeValue(value, type) { switch (type) { case Boolean: return (value !== null); case Number: return Number(value); default: return value; } }
JavaScript
static createPropertiesForAttributes() { let a$ = this.observedAttributes; for (let i=0; i < a$.length; i++) { this.prototype._createPropertyAccessor(caseMap$1.dashToCamelCase(a$[i])); } }
static createPropertiesForAttributes() { let a$ = this.observedAttributes; for (let i=0; i < a$.length; i++) { this.prototype._createPropertyAccessor(caseMap$1.dashToCamelCase(a$[i])); } }
JavaScript
_initializeProperties() { if (this.__dataProto) { this._initializeProtoProperties(this.__dataProto); this.__dataProto = null; } super._initializeProperties(); }
_initializeProperties() { if (this.__dataProto) { this._initializeProtoProperties(this.__dataProto); this.__dataProto = null; } super._initializeProperties(); }
JavaScript
_initializeProtoProperties(props) { for (let p in props) { this._setProperty(p, props[p]); } }
_initializeProtoProperties(props) { for (let p in props) { this._setProperty(p, props[p]); } }
JavaScript
_serializeValue(value) { /* eslint-disable no-fallthrough */ switch (typeof value) { case 'object': if (value instanceof Date) { return value.toString(); } else if (value) { try { return JSON.stringify(value); } catch(x) { return ''; } } default: return super._serializeValue(value); } }
_serializeValue(value) { /* eslint-disable no-fallthrough */ switch (typeof value) { case 'object': if (value instanceof Date) { return value.toString(); } else if (value) { try { return JSON.stringify(value); } catch(x) { return ''; } } default: return super._serializeValue(value); } }
JavaScript
_deserializeValue(value, type) { /** * @type {*} */ let outValue; switch (type) { case Object: try { outValue = JSON.parse(/** @type {string} */(value)); } catch(x) { // allow non-JSON literals like Strings and Numbers outValue = value; } break; case Array: try { outValue = JSON.parse(/** @type {string} */(value)); } catch(x) { outValue = null; console.warn(`Polymer::Attributes: couldn't decode Array as JSON: ${value}`); } break; case Date: outValue = isNaN(value) ? String(value) : Number(value); outValue = new Date(outValue); break; default: outValue = super._deserializeValue(value, type); break; } return outValue; }
_deserializeValue(value, type) { /** * @type {*} */ let outValue; switch (type) { case Object: try { outValue = JSON.parse(/** @type {string} */(value)); } catch(x) { // allow non-JSON literals like Strings and Numbers outValue = value; } break; case Array: try { outValue = JSON.parse(/** @type {string} */(value)); } catch(x) { outValue = null; console.warn(`Polymer::Attributes: couldn't decode Array as JSON: ${value}`); } break; case Date: outValue = isNaN(value) ? String(value) : Number(value); outValue = new Date(outValue); break; default: outValue = super._deserializeValue(value, type); break; } return outValue; }
JavaScript
function applyEventListener(inst, node, nodeInfo) { if (nodeInfo.events && nodeInfo.events.length) { for (let j=0, e$=nodeInfo.events, e; (j<e$.length) && (e=e$[j]); j++) { inst._addMethodEventListenerToNode(node, e.name, e.value, inst); } } }
function applyEventListener(inst, node, nodeInfo) { if (nodeInfo.events && nodeInfo.events.length) { for (let j=0, e$=nodeInfo.events, e; (j<e$.length) && (e=e$[j]); j++) { inst._addMethodEventListenerToNode(node, e.name, e.value, inst); } } }
JavaScript
function applyTemplateContent(inst, node, nodeInfo) { if (nodeInfo.templateInfo) { node._templateInfo = nodeInfo.templateInfo; } }
function applyTemplateContent(inst, node, nodeInfo) { if (nodeInfo.templateInfo) { node._templateInfo = nodeInfo.templateInfo; } }
JavaScript
static _parseTemplate(template, outerTemplateInfo) { // since a template may be re-used, memo-ize metadata if (!template._templateInfo) { let templateInfo = template._templateInfo = {}; templateInfo.nodeInfoList = []; templateInfo.stripWhiteSpace = (outerTemplateInfo && outerTemplateInfo.stripWhiteSpace) || template.hasAttribute('strip-whitespace'); this._parseTemplateContent(template, templateInfo, {parent: null}); } return template._templateInfo; }
static _parseTemplate(template, outerTemplateInfo) { // since a template may be re-used, memo-ize metadata if (!template._templateInfo) { let templateInfo = template._templateInfo = {}; templateInfo.nodeInfoList = []; templateInfo.stripWhiteSpace = (outerTemplateInfo && outerTemplateInfo.stripWhiteSpace) || template.hasAttribute('strip-whitespace'); this._parseTemplateContent(template, templateInfo, {parent: null}); } return template._templateInfo; }
JavaScript
static _parseTemplateNode(node, templateInfo, nodeInfo) { let noted; let element = /** @type {Element} */(node); if (element.localName == 'template' && !element.hasAttribute('preserve-content')) { noted = this._parseTemplateNestedTemplate(element, templateInfo, nodeInfo) || noted; } else if (element.localName === 'slot') { // For ShadyDom optimization, indicating there is an insertion point templateInfo.hasInsertionPoint = true; } if (element.firstChild) { noted = this._parseTemplateChildNodes(element, templateInfo, nodeInfo) || noted; } if (element.hasAttributes && element.hasAttributes()) { noted = this._parseTemplateNodeAttributes(element, templateInfo, nodeInfo) || noted; } return noted; }
static _parseTemplateNode(node, templateInfo, nodeInfo) { let noted; let element = /** @type {Element} */(node); if (element.localName == 'template' && !element.hasAttribute('preserve-content')) { noted = this._parseTemplateNestedTemplate(element, templateInfo, nodeInfo) || noted; } else if (element.localName === 'slot') { // For ShadyDom optimization, indicating there is an insertion point templateInfo.hasInsertionPoint = true; } if (element.firstChild) { noted = this._parseTemplateChildNodes(element, templateInfo, nodeInfo) || noted; } if (element.hasAttributes && element.hasAttributes()) { noted = this._parseTemplateNodeAttributes(element, templateInfo, nodeInfo) || noted; } return noted; }
JavaScript
static _parseTemplateChildNodes(root, templateInfo, nodeInfo) { if (root.localName === 'script' || root.localName === 'style') { return; } for (let node=root.firstChild, parentIndex=0, next; node; node=next) { // Wrap templates if (node.localName == 'template') { node = wrapTemplateExtension(node); } // collapse adjacent textNodes: fixes an IE issue that can cause // text nodes to be inexplicably split =( // note that root.normalize() should work but does not so we do this // manually. next = node.nextSibling; if (node.nodeType === Node.TEXT_NODE) { let /** Node */ n = next; while (n && (n.nodeType === Node.TEXT_NODE)) { node.textContent += n.textContent; next = n.nextSibling; root.removeChild(n); n = next; } // optionally strip whitespace if (templateInfo.stripWhiteSpace && !node.textContent.trim()) { root.removeChild(node); continue; } } let childInfo = { parentIndex, parentInfo: nodeInfo }; if (this._parseTemplateNode(node, templateInfo, childInfo)) { childInfo.infoIndex = templateInfo.nodeInfoList.push(/** @type {!NodeInfo} */(childInfo)) - 1; } // Increment if not removed if (node.parentNode) { parentIndex++; } } }
static _parseTemplateChildNodes(root, templateInfo, nodeInfo) { if (root.localName === 'script' || root.localName === 'style') { return; } for (let node=root.firstChild, parentIndex=0, next; node; node=next) { // Wrap templates if (node.localName == 'template') { node = wrapTemplateExtension(node); } // collapse adjacent textNodes: fixes an IE issue that can cause // text nodes to be inexplicably split =( // note that root.normalize() should work but does not so we do this // manually. next = node.nextSibling; if (node.nodeType === Node.TEXT_NODE) { let /** Node */ n = next; while (n && (n.nodeType === Node.TEXT_NODE)) { node.textContent += n.textContent; next = n.nextSibling; root.removeChild(n); n = next; } // optionally strip whitespace if (templateInfo.stripWhiteSpace && !node.textContent.trim()) { root.removeChild(node); continue; } } let childInfo = { parentIndex, parentInfo: nodeInfo }; if (this._parseTemplateNode(node, templateInfo, childInfo)) { childInfo.infoIndex = templateInfo.nodeInfoList.push(/** @type {!NodeInfo} */(childInfo)) - 1; } // Increment if not removed if (node.parentNode) { parentIndex++; } } }
JavaScript
static _parseTemplateNestedTemplate(node, outerTemplateInfo, nodeInfo) { let templateInfo = this._parseTemplate(node, outerTemplateInfo); let content = templateInfo.content = node.content.ownerDocument.createDocumentFragment(); content.appendChild(node.content); nodeInfo.templateInfo = templateInfo; return true; }
static _parseTemplateNestedTemplate(node, outerTemplateInfo, nodeInfo) { let templateInfo = this._parseTemplate(node, outerTemplateInfo); let content = templateInfo.content = node.content.ownerDocument.createDocumentFragment(); content.appendChild(node.content); nodeInfo.templateInfo = templateInfo; return true; }
JavaScript
static _parseTemplateNodeAttributes(node, templateInfo, nodeInfo) { // Make copy of original attribute list, since the order may change // as attributes are added and removed let noted = false; let attrs = Array.from(node.attributes); for (let i=attrs.length-1, a; (a=attrs[i]); i--) { noted = this._parseTemplateNodeAttribute(node, templateInfo, nodeInfo, a.name, a.value) || noted; } return noted; }
static _parseTemplateNodeAttributes(node, templateInfo, nodeInfo) { // Make copy of original attribute list, since the order may change // as attributes are added and removed let noted = false; let attrs = Array.from(node.attributes); for (let i=attrs.length-1, a; (a=attrs[i]); i--) { noted = this._parseTemplateNodeAttribute(node, templateInfo, nodeInfo, a.name, a.value) || noted; } return noted; }
JavaScript
_stampTemplate(template) { // Polyfill support: bootstrap the template if it has not already been if (template && !template.content && window.HTMLTemplateElement && HTMLTemplateElement.decorate) { HTMLTemplateElement.decorate(template); } let templateInfo = this.constructor._parseTemplate(template); let nodeInfo = templateInfo.nodeInfoList; let content = templateInfo.content || template.content; let dom = /** @type {DocumentFragment} */ (document.importNode(content, true)); // NOTE: ShadyDom optimization indicating there is an insertion point dom.__noInsertionPoint = !templateInfo.hasInsertionPoint; let nodes = dom.nodeList = new Array(nodeInfo.length); dom.$ = {}; for (let i=0, l=nodeInfo.length, info; (i<l) && (info=nodeInfo[i]); i++) { let node = nodes[i] = findTemplateNode(dom, info); applyIdToMap(this, dom.$, node, info); applyTemplateContent(this, node, info); applyEventListener(this, node, info); } dom = /** @type {!StampedTemplate} */(dom); // eslint-disable-line no-self-assign return dom; }
_stampTemplate(template) { // Polyfill support: bootstrap the template if it has not already been if (template && !template.content && window.HTMLTemplateElement && HTMLTemplateElement.decorate) { HTMLTemplateElement.decorate(template); } let templateInfo = this.constructor._parseTemplate(template); let nodeInfo = templateInfo.nodeInfoList; let content = templateInfo.content || template.content; let dom = /** @type {DocumentFragment} */ (document.importNode(content, true)); // NOTE: ShadyDom optimization indicating there is an insertion point dom.__noInsertionPoint = !templateInfo.hasInsertionPoint; let nodes = dom.nodeList = new Array(nodeInfo.length); dom.$ = {}; for (let i=0, l=nodeInfo.length, info; (i<l) && (info=nodeInfo[i]); i++) { let node = nodes[i] = findTemplateNode(dom, info); applyIdToMap(this, dom.$, node, info); applyTemplateContent(this, node, info); applyEventListener(this, node, info); } dom = /** @type {!StampedTemplate} */(dom); // eslint-disable-line no-self-assign return dom; }
JavaScript
_addMethodEventListenerToNode(node, eventName, methodName, context) { context = context || node; let handler = createNodeEventHandler(context, eventName, methodName); this._addEventListenerToNode(node, eventName, handler); return handler; }
_addMethodEventListenerToNode(node, eventName, methodName, context) { context = context || node; let handler = createNodeEventHandler(context, eventName, methodName); this._addEventListenerToNode(node, eventName, handler); return handler; }
JavaScript
function ensureOwnEffectMap(model, type) { let effects = model[type]; if (!effects) { effects = model[type] = {}; } else if (!model.hasOwnProperty(type)) { effects = model[type] = Object.create(model[type]); for (let p in effects) { let protoFx = effects[p]; let instFx = effects[p] = Array(protoFx.length); for (let i=0; i<protoFx.length; i++) { instFx[i] = protoFx[i]; } } } return effects; }
function ensureOwnEffectMap(model, type) { let effects = model[type]; if (!effects) { effects = model[type] = {}; } else if (!model.hasOwnProperty(type)) { effects = model[type] = Object.create(model[type]); for (let p in effects) { let protoFx = effects[p]; let instFx = effects[p] = Array(protoFx.length); for (let i=0; i<protoFx.length; i++) { instFx[i] = protoFx[i]; } } } return effects; }
JavaScript
function runEffects(inst, effects, props, oldProps, hasPaths, extraArgs) { if (effects) { let ran = false; let id = dedupeId$1++; for (let prop in props) { if (runEffectsForProperty(inst, effects, id, prop, props, oldProps, hasPaths, extraArgs)) { ran = true; } } return ran; } return false; }
function runEffects(inst, effects, props, oldProps, hasPaths, extraArgs) { if (effects) { let ran = false; let id = dedupeId$1++; for (let prop in props) { if (runEffectsForProperty(inst, effects, id, prop, props, oldProps, hasPaths, extraArgs)) { ran = true; } } return ran; } return false; }
JavaScript
function runEffectsForProperty(inst, effects, dedupeId, prop, props, oldProps, hasPaths, extraArgs) { let ran = false; let rootProperty = hasPaths ? root(prop) : prop; let fxs = effects[rootProperty]; if (fxs) { for (let i=0, l=fxs.length, fx; (i<l) && (fx=fxs[i]); i++) { if ((!fx.info || fx.info.lastRun !== dedupeId) && (!hasPaths || pathMatchesTrigger(prop, fx.trigger))) { if (fx.info) { fx.info.lastRun = dedupeId; } fx.fn(inst, prop, props, oldProps, fx.info, hasPaths, extraArgs); ran = true; } } } return ran; }
function runEffectsForProperty(inst, effects, dedupeId, prop, props, oldProps, hasPaths, extraArgs) { let ran = false; let rootProperty = hasPaths ? root(prop) : prop; let fxs = effects[rootProperty]; if (fxs) { for (let i=0, l=fxs.length, fx; (i<l) && (fx=fxs[i]); i++) { if ((!fx.info || fx.info.lastRun !== dedupeId) && (!hasPaths || pathMatchesTrigger(prop, fx.trigger))) { if (fx.info) { fx.info.lastRun = dedupeId; } fx.fn(inst, prop, props, oldProps, fx.info, hasPaths, extraArgs); ran = true; } } } return ran; }
JavaScript
function pathMatchesTrigger(path, trigger) { if (trigger) { let triggerPath = trigger.name; return (triggerPath == path) || (trigger.structured && isAncestor(triggerPath, path)) || (trigger.wildcard && isDescendant(triggerPath, path)); } else { return true; } }
function pathMatchesTrigger(path, trigger) { if (trigger) { let triggerPath = trigger.name; return (triggerPath == path) || (trigger.structured && isAncestor(triggerPath, path)) || (trigger.wildcard && isDescendant(triggerPath, path)); } else { return true; } }
JavaScript
function runNotifyEffects(inst, notifyProps, props, oldProps, hasPaths) { // Notify let fxs = inst[TYPES.NOTIFY]; let notified; let id = dedupeId$1++; // Try normal notify effects; if none, fall back to try path notification for (let prop in notifyProps) { if (notifyProps[prop]) { if (fxs && runEffectsForProperty(inst, fxs, id, prop, props, oldProps, hasPaths)) { notified = true; } else if (hasPaths && notifyPath(inst, prop, props)) { notified = true; } } } // Flush host if we actually notified and host was batching // And the host has already initialized clients; this prevents // an issue with a host observing data changes before clients are ready. let host; if (notified && (host = inst.__dataHost) && host._invalidateProperties) { host._invalidateProperties(); } }
function runNotifyEffects(inst, notifyProps, props, oldProps, hasPaths) { // Notify let fxs = inst[TYPES.NOTIFY]; let notified; let id = dedupeId$1++; // Try normal notify effects; if none, fall back to try path notification for (let prop in notifyProps) { if (notifyProps[prop]) { if (fxs && runEffectsForProperty(inst, fxs, id, prop, props, oldProps, hasPaths)) { notified = true; } else if (hasPaths && notifyPath(inst, prop, props)) { notified = true; } } } // Flush host if we actually notified and host was batching // And the host has already initialized clients; this prevents // an issue with a host observing data changes before clients are ready. let host; if (notified && (host = inst.__dataHost) && host._invalidateProperties) { host._invalidateProperties(); } }
JavaScript
function notifyPath(inst, path, props) { let rootProperty = root(path); if (rootProperty !== path) { let eventName = camelToDashCase(rootProperty) + '-changed'; dispatchNotifyEvent(inst, eventName, props[path], path); return true; } return false; }
function notifyPath(inst, path, props) { let rootProperty = root(path); if (rootProperty !== path) { let eventName = camelToDashCase(rootProperty) + '-changed'; dispatchNotifyEvent(inst, eventName, props[path], path); return true; } return false; }
JavaScript
function handleNotification(event, inst, fromProp, toPath, negate) { let value; let detail = /** @type {Object} */(event.detail); let fromPath = detail && detail.path; if (fromPath) { toPath = translate(fromProp, toPath, fromPath); value = detail && detail.value; } else { value = event.target[fromProp]; } value = negate ? !value : value; if (!inst[TYPES.READ_ONLY] || !inst[TYPES.READ_ONLY][toPath]) { if (inst._setPendingPropertyOrPath(toPath, value, true, Boolean(fromPath)) && (!detail || !detail.queueProperty)) { inst._invalidateProperties(); } } }
function handleNotification(event, inst, fromProp, toPath, negate) { let value; let detail = /** @type {Object} */(event.detail); let fromPath = detail && detail.path; if (fromPath) { toPath = translate(fromProp, toPath, fromPath); value = detail && detail.value; } else { value = event.target[fromProp]; } value = negate ? !value : value; if (!inst[TYPES.READ_ONLY] || !inst[TYPES.READ_ONLY][toPath]) { if (inst._setPendingPropertyOrPath(toPath, value, true, Boolean(fromPath)) && (!detail || !detail.queueProperty)) { inst._invalidateProperties(); } } }
JavaScript
function runComputedEffects(inst, changedProps, oldProps, hasPaths) { let computeEffects = inst[TYPES.COMPUTE]; if (computeEffects) { let inputProps = changedProps; while (runEffects(inst, computeEffects, inputProps, oldProps, hasPaths)) { Object.assign(oldProps, inst.__dataOld); Object.assign(changedProps, inst.__dataPending); inputProps = inst.__dataPending; inst.__dataPending = null; } } }
function runComputedEffects(inst, changedProps, oldProps, hasPaths) { let computeEffects = inst[TYPES.COMPUTE]; if (computeEffects) { let inputProps = changedProps; while (runEffects(inst, computeEffects, inputProps, oldProps, hasPaths)) { Object.assign(oldProps, inst.__dataOld); Object.assign(changedProps, inst.__dataPending); inputProps = inst.__dataPending; inst.__dataPending = null; } } }
JavaScript
function runComputedEffect(inst, property, props, oldProps, info) { let result = runMethodEffect(inst, property, props, oldProps, info); let computedProp = info.methodInfo; if (inst.__dataHasAccessor && inst.__dataHasAccessor[computedProp]) { inst._setPendingProperty(computedProp, result, true); } else { inst[computedProp] = result; } }
function runComputedEffect(inst, property, props, oldProps, info) { let result = runMethodEffect(inst, property, props, oldProps, info); let computedProp = info.methodInfo; if (inst.__dataHasAccessor && inst.__dataHasAccessor[computedProp]) { inst._setPendingProperty(computedProp, result, true); } else { inst[computedProp] = result; } }
JavaScript
function computeLinkedPaths(inst, path, value) { let links = inst.__dataLinkedPaths; if (links) { let link; for (let a in links) { let b = links[a]; if (isDescendant(a, path)) { link = translate(a, b, path); inst._setPendingPropertyOrPath(link, value, true, true); } else if (isDescendant(b, path)) { link = translate(b, a, path); inst._setPendingPropertyOrPath(link, value, true, true); } } } }
function computeLinkedPaths(inst, path, value) { let links = inst.__dataLinkedPaths; if (links) { let link; for (let a in links) { let b = links[a]; if (isDescendant(a, path)) { link = translate(a, b, path); inst._setPendingPropertyOrPath(link, value, true, true); } else if (isDescendant(b, path)) { link = translate(b, a, path); inst._setPendingPropertyOrPath(link, value, true, true); } } } }
JavaScript
function addBinding(constructor, templateInfo, nodeInfo, kind, target, parts, literal) { // Create binding metadata and add to nodeInfo nodeInfo.bindings = nodeInfo.bindings || []; let /** Binding */ binding = { kind, target, parts, literal, isCompound: (parts.length !== 1) }; nodeInfo.bindings.push(binding); // Add listener info to binding metadata if (shouldAddListener(binding)) { let {event, negate} = binding.parts[0]; binding.listenerEvent = event || (CaseMap.camelToDashCase(target) + '-changed'); binding.listenerNegate = negate; } // Add "propagate" property effects to templateInfo let index = templateInfo.nodeInfoList.length; for (let i=0; i<binding.parts.length; i++) { let part = binding.parts[i]; part.compoundIndex = i; addEffectForBindingPart(constructor, templateInfo, binding, part, index); } }
function addBinding(constructor, templateInfo, nodeInfo, kind, target, parts, literal) { // Create binding metadata and add to nodeInfo nodeInfo.bindings = nodeInfo.bindings || []; let /** Binding */ binding = { kind, target, parts, literal, isCompound: (parts.length !== 1) }; nodeInfo.bindings.push(binding); // Add listener info to binding metadata if (shouldAddListener(binding)) { let {event, negate} = binding.parts[0]; binding.listenerEvent = event || (CaseMap.camelToDashCase(target) + '-changed'); binding.listenerNegate = negate; } // Add "propagate" property effects to templateInfo let index = templateInfo.nodeInfoList.length; for (let i=0; i<binding.parts.length; i++) { let part = binding.parts[i]; part.compoundIndex = i; addEffectForBindingPart(constructor, templateInfo, binding, part, index); } }
JavaScript
function addEffectForBindingPart(constructor, templateInfo, binding, part, index) { if (!part.literal) { if (binding.kind === 'attribute' && binding.target[0] === '-') { console.warn('Cannot set attribute ' + binding.target + ' because "-" is not a valid attribute starting character'); } else { let dependencies = part.dependencies; let info = { index, binding, part, evaluator: constructor }; for (let j=0; j<dependencies.length; j++) { let trigger = dependencies[j]; if (typeof trigger == 'string') { trigger = parseArg(trigger); trigger.wildcard = true; } constructor._addTemplatePropertyEffect(templateInfo, trigger.rootProperty, { fn: runBindingEffect, info, trigger }); } } } }
function addEffectForBindingPart(constructor, templateInfo, binding, part, index) { if (!part.literal) { if (binding.kind === 'attribute' && binding.target[0] === '-') { console.warn('Cannot set attribute ' + binding.target + ' because "-" is not a valid attribute starting character'); } else { let dependencies = part.dependencies; let info = { index, binding, part, evaluator: constructor }; for (let j=0; j<dependencies.length; j++) { let trigger = dependencies[j]; if (typeof trigger == 'string') { trigger = parseArg(trigger); trigger.wildcard = true; } constructor._addTemplatePropertyEffect(templateInfo, trigger.rootProperty, { fn: runBindingEffect, info, trigger }); } } } }
JavaScript
function computeBindingValue(node, value, binding, part) { if (binding.isCompound) { let storage = node.__dataCompoundStorage[binding.target]; storage[part.compoundIndex] = value; value = storage.join(''); } if (binding.kind !== 'attribute') { // Some browsers serialize `undefined` to `"undefined"` if (binding.target === 'textContent' || (binding.target === 'value' && (node.localName === 'input' || node.localName === 'textarea'))) { value = value == undefined ? '' : value; } } return value; }
function computeBindingValue(node, value, binding, part) { if (binding.isCompound) { let storage = node.__dataCompoundStorage[binding.target]; storage[part.compoundIndex] = value; value = storage.join(''); } if (binding.kind !== 'attribute') { // Some browsers serialize `undefined` to `"undefined"` if (binding.target === 'textContent' || (binding.target === 'value' && (node.localName === 'input' || node.localName === 'textarea'))) { value = value == undefined ? '' : value; } } return value; }
JavaScript
function createMethodEffect(model, sig, type, effectFn, methodInfo, dynamicFn) { dynamicFn = sig.static || (dynamicFn && (typeof dynamicFn !== 'object' || dynamicFn[sig.methodName])); let info = { methodName: sig.methodName, args: sig.args, methodInfo, dynamicFn }; for (let i=0, arg; (i<sig.args.length) && (arg=sig.args[i]); i++) { if (!arg.literal) { model._addPropertyEffect(arg.rootProperty, type, { fn: effectFn, info: info, trigger: arg }); } } if (dynamicFn) { model._addPropertyEffect(sig.methodName, type, { fn: effectFn, info: info }); } }
function createMethodEffect(model, sig, type, effectFn, methodInfo, dynamicFn) { dynamicFn = sig.static || (dynamicFn && (typeof dynamicFn !== 'object' || dynamicFn[sig.methodName])); let info = { methodName: sig.methodName, args: sig.args, methodInfo, dynamicFn }; for (let i=0, arg; (i<sig.args.length) && (arg=sig.args[i]); i++) { if (!arg.literal) { model._addPropertyEffect(arg.rootProperty, type, { fn: effectFn, info: info, trigger: arg }); } } if (dynamicFn) { model._addPropertyEffect(sig.methodName, type, { fn: effectFn, info: info }); } }