language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
render() { // if the game is won, shows a winning msg & render nothing else if(this.state.hasWon){ return( <div className='Board-title'> <div className='winner'> <span className='neon-orange'>YOU</span> <span className='neon-blue'>WON!</span> </div> </div> ) } // makes table board let tblBoard = []; for(let y = 0; y < this.props.nrows; y++){ let row = []; for(let x = 0; x < this.props.ncols; x++){ let c = `${y}-${x}`; row.push(<Cell key={c} isLit={this.state.board[y][x]} flipCellsAroundMe={() => this.flipCellsAround(c)} />) } tblBoard.push(<tr key={y}>{row}</tr>) } return( <div> <div className='Board-title'> <div className='neon-orange'>Lights</div> <div className='neon-blue'>Out</div> </div> <table className='Board'> <tbody> {tblBoard} </tbody> </table> </div> ) }
render() { // if the game is won, shows a winning msg & render nothing else if(this.state.hasWon){ return( <div className='Board-title'> <div className='winner'> <span className='neon-orange'>YOU</span> <span className='neon-blue'>WON!</span> </div> </div> ) } // makes table board let tblBoard = []; for(let y = 0; y < this.props.nrows; y++){ let row = []; for(let x = 0; x < this.props.ncols; x++){ let c = `${y}-${x}`; row.push(<Cell key={c} isLit={this.state.board[y][x]} flipCellsAroundMe={() => this.flipCellsAround(c)} />) } tblBoard.push(<tr key={y}>{row}</tr>) } return( <div> <div className='Board-title'> <div className='neon-orange'>Lights</div> <div className='neon-blue'>Out</div> </div> <table className='Board'> <tbody> {tblBoard} </tbody> </table> </div> ) }
JavaScript
function handleInitialData() { return (dispatch) => { dispatch(showLoading()) return getInitialData() .then(({ users, tweets }) => { dispatch(receiveTweets(tweets)); dispatch(receiveUsers(users)); dispatch(receiveAuthUsers(authUser)); dispatch(hideLoading()) }); }; }
function handleInitialData() { return (dispatch) => { dispatch(showLoading()) return getInitialData() .then(({ users, tweets }) => { dispatch(receiveTweets(tweets)); dispatch(receiveUsers(users)); dispatch(receiveAuthUsers(authUser)); dispatch(hideLoading()) }); }; }
JavaScript
createReaction({ params }, res) { Thought.findOneAndUpdate({ _id: params.thoughtId }, { $addToSet: { reactions: { reactionId: params.reactionId } } }) .then(dbThoughtData => { if (!dbThoughtData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbThoughtData); }) .catch(err => res.status(400).json(err)); }
createReaction({ params }, res) { Thought.findOneAndUpdate({ _id: params.thoughtId }, { $addToSet: { reactions: { reactionId: params.reactionId } } }) .then(dbThoughtData => { if (!dbThoughtData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbThoughtData); }) .catch(err => res.status(400).json(err)); }
JavaScript
deleteReaction({ params }, res) { Thought.findOneAndUpdate({ _id: params.thoughtId }, { $pull: { reactions: { reactionId: params.reactionId } } }, { new: true }) .then(dbThoughtData => { if (!dbThoughtData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbThoughtData); }) .catch(err => res.status(400).json(err)); }
deleteReaction({ params }, res) { Thought.findOneAndUpdate({ _id: params.thoughtId }, { $pull: { reactions: { reactionId: params.reactionId } } }, { new: true }) .then(dbThoughtData => { if (!dbThoughtData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbThoughtData); }) .catch(err => res.status(400).json(err)); }
JavaScript
addUserFriend({ params }, res) { User.findOneAndUpdate({ _id: params.userId }, { $addToSet: { friends: params.friendId } }) .then(dbUserData => { if (!dbUserData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbUserData); }) .catch(err => res.status(400).json(err)); }
addUserFriend({ params }, res) { User.findOneAndUpdate({ _id: params.userId }, { $addToSet: { friends: params.friendId } }) .then(dbUserData => { if (!dbUserData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbUserData); }) .catch(err => res.status(400).json(err)); }
JavaScript
deleteUserFriend({ params }, res) { User.findOneAndUpdate({ _id: params.userId }, { $pull: { friends: params.friendId } }, { new: true } ) .then(dbUserData => { if (!dbUserData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbUserData); }) .catch(err => res.status(400).json(err)); }
deleteUserFriend({ params }, res) { User.findOneAndUpdate({ _id: params.userId }, { $pull: { friends: params.friendId } }, { new: true } ) .then(dbUserData => { if (!dbUserData) { res.status(404).json({ message: 'No user found with that ID!' }); return; } res.json(dbUserData); }) .catch(err => res.status(400).json(err)); }
JavaScript
function drawKitt(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY+10) fill(255) text(c.name, -20,c.size) fill(c.color) ellipse(0,0,c.size,c.size) fill(0) rect(-(c.size/2),-(c.size/5),c.size,c.size/10) rect(-(c.size/c.size)-1,-(c.size/10),c.size/25,c.size/8) strokeWeight(2) stroke(c.color) noFill() ellipse(0,0,c.size,c.size) fill(0) ellipse(0,c.size/3.33,c.size/3.33,c.size/3.33) fill(c.color) triangle(-(c.size/4.16),-(c.size/1.78),-(c.size/2.77),-(c.size/3.33),-(c.size/25),-(c.size/3.33)) rect(-(c.size/4.16),-(c.size/1.25),0.5,c.size/3.33) translate(-(c.size/4.16),-(c.size/1.162)) fill(c.color) ellipse(0,0,c.size/10,c.size/10) pop() }
function drawKitt(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY+10) fill(255) text(c.name, -20,c.size) fill(c.color) ellipse(0,0,c.size,c.size) fill(0) rect(-(c.size/2),-(c.size/5),c.size,c.size/10) rect(-(c.size/c.size)-1,-(c.size/10),c.size/25,c.size/8) strokeWeight(2) stroke(c.color) noFill() ellipse(0,0,c.size,c.size) fill(0) ellipse(0,c.size/3.33,c.size/3.33,c.size/3.33) fill(c.color) triangle(-(c.size/4.16),-(c.size/1.78),-(c.size/2.77),-(c.size/3.33),-(c.size/25),-(c.size/3.33)) rect(-(c.size/4.16),-(c.size/1.25),0.5,c.size/3.33) translate(-(c.size/4.16),-(c.size/1.162)) fill(c.color) ellipse(0,0,c.size/10,c.size/10) pop() }
JavaScript
function drawAngryStickman(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(c.color) ellipse(0,0,c.size,c.size) fill(0) ellipse(10,-10,c.size-40,c.size/16) ellipse(-10,-10,c.size/5,c.size/16) fill(216,95,125) stroke(0) strokeWeight(2) arc(0, 10, c.size-20, c.size-30, PI, TWO_PI); fill(0) strokeWeight(7) line(0,120,0,26) line(1,20,c.size,c.size+10) line(1,20,-c.size,c.size+10) line(1,120,-c.size,c.size*3.5) line(1,120,c.size,c.size*3.5) pop() }
function drawAngryStickman(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(c.color) ellipse(0,0,c.size,c.size) fill(0) ellipse(10,-10,c.size-40,c.size/16) ellipse(-10,-10,c.size/5,c.size/16) fill(216,95,125) stroke(0) strokeWeight(2) arc(0, 10, c.size-20, c.size-30, PI, TWO_PI); fill(0) strokeWeight(7) line(0,120,0,26) line(1,20,c.size,c.size+10) line(1,20,-c.size,c.size+10) line(1,120,-c.size,c.size*3.5) line(1,120,c.size,c.size*3.5) pop() }
JavaScript
function drawYogi(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(c.color) noStroke() push() translate(-c.size/2,-c.size/2) triangle(40,30,30,60,-10,-10) pop() rect(-50,-50,c.size,c.size) fill (0) ellipse(15,-20,10,10) ellipse(-15,-20,10,10) rect(-20,15,40,10) triangle(-5,5,5,5,0,10) fill(255) ellipse(17,-22,3,3) ellipse(-13,-22,3,3) ellipse(15,-18,5,5) ellipse(-15,-18,5,5) stroke (5) rect(-20,15,5,5) rect(-15,15,5,5) rect(-10,15,5,5) rect(-5,15,5,5) rect(0,15,5,5) rect(5,15,5,5) rect(10,15,5,5) rect(15,15,5,5) rect(-20,20,5,5) rect(-15,20,5,5) rect(-10,20,5,5) rect(-5,20,5,5) rect(0,20,5,5) rect(5,20,5,5) rect(10,20,5,5) rect(15,20,5,5) pop() }
function drawYogi(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(c.color) noStroke() push() translate(-c.size/2,-c.size/2) triangle(40,30,30,60,-10,-10) pop() rect(-50,-50,c.size,c.size) fill (0) ellipse(15,-20,10,10) ellipse(-15,-20,10,10) rect(-20,15,40,10) triangle(-5,5,5,5,0,10) fill(255) ellipse(17,-22,3,3) ellipse(-13,-22,3,3) ellipse(15,-18,5,5) ellipse(-15,-18,5,5) stroke (5) rect(-20,15,5,5) rect(-15,15,5,5) rect(-10,15,5,5) rect(-5,15,5,5) rect(0,15,5,5) rect(5,15,5,5) rect(10,15,5,5) rect(15,15,5,5) rect(-20,20,5,5) rect(-15,20,5,5) rect(-10,20,5,5) rect(-5,20,5,5) rect(0,20,5,5) rect(5,20,5,5) rect(10,20,5,5) rect(15,20,5,5) pop() }
JavaScript
function drawKeypoints() { // Loop through all the poses detected for (let i = 0; i < poses.length; i++) { // For each pose detected, loop through all the keypoints let pose = poses[i].pose; for (let j = 0; j < pose.keypoints.length; j++) { // A keypoint is an object describing a body part (like rightArm or leftShoulder) let keypoint = pose.keypoints[j]; // Only draw an ellipse is the pose probability is bigger than 0.2 if (keypoint.score > 0.2) { fill(255, 0, 0); noStroke(); //ellipse(keypoint.position.x, keypoint.position.y, 10, 10); text(j, keypoint.position.x, keypoint.position.y); if (j == 0) { push(); imageMode(CENTER); //image(nose,keypoint.position.x, keypoint.position.y, 50, 50); pop(); //text("NOSE", keypoint.position.x + -15, keypoint.position.y + 15); } } } } }
function drawKeypoints() { // Loop through all the poses detected for (let i = 0; i < poses.length; i++) { // For each pose detected, loop through all the keypoints let pose = poses[i].pose; for (let j = 0; j < pose.keypoints.length; j++) { // A keypoint is an object describing a body part (like rightArm or leftShoulder) let keypoint = pose.keypoints[j]; // Only draw an ellipse is the pose probability is bigger than 0.2 if (keypoint.score > 0.2) { fill(255, 0, 0); noStroke(); //ellipse(keypoint.position.x, keypoint.position.y, 10, 10); text(j, keypoint.position.x, keypoint.position.y); if (j == 0) { push(); imageMode(CENTER); //image(nose,keypoint.position.x, keypoint.position.y, 50, 50); pop(); //text("NOSE", keypoint.position.x + -15, keypoint.position.y + 15); } } } } }
JavaScript
function drawSanta(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(214,13,13) ellipse(c.size-50,c.size+15,c.size*2,c.size*2) fill(236,203,138) ellipse(c.size-50,c.size-50,c.size,c.size) fill(255,220) ellipse(c.size-50,c.size/1.85,c.size+1.5,c.size+1.5) fill(214,13,13) triangle(-c.size/2, -c.size/3.5, c.size/50, -c.size+-2, c.size/2, -c.size/3) fill(255) line(-c.size/5, c.size/5, c.size/5, c.size/5) line(-c.size/4, -c.size/6.25, -c.size/10-1, -c.size/5) line(c.size/4, -c.size/6.25, c.size/10-1, -c.size/5) ellipse(c.size-50,c.size-102,c.size/3,c.size/3) fill(0) ellipse(c.size/6.25,-c.size/16.6,c.size/7,c.size/7) ellipse(-c.size/6.25,-c.size/16.6,c.size/7,c.size/7) ellipse(c.size-50,c.size+10,c.size/3,c.size/3) ellipse(c.size-50,c.size+30,c.size/3,c.size/3) pop() }
function drawSanta(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(214,13,13) ellipse(c.size-50,c.size+15,c.size*2,c.size*2) fill(236,203,138) ellipse(c.size-50,c.size-50,c.size,c.size) fill(255,220) ellipse(c.size-50,c.size/1.85,c.size+1.5,c.size+1.5) fill(214,13,13) triangle(-c.size/2, -c.size/3.5, c.size/50, -c.size+-2, c.size/2, -c.size/3) fill(255) line(-c.size/5, c.size/5, c.size/5, c.size/5) line(-c.size/4, -c.size/6.25, -c.size/10-1, -c.size/5) line(c.size/4, -c.size/6.25, c.size/10-1, -c.size/5) ellipse(c.size-50,c.size-102,c.size/3,c.size/3) fill(0) ellipse(c.size/6.25,-c.size/16.6,c.size/7,c.size/7) ellipse(-c.size/6.25,-c.size/16.6,c.size/7,c.size/7) ellipse(c.size-50,c.size+10,c.size/3,c.size/3) ellipse(c.size-50,c.size+30,c.size/3,c.size/3) pop() }
JavaScript
function drawHippo(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(c.color) // ellipse(0,0,c.size,c.size) ellipse(0,30,c.size-50,c.size-50); fill(0) ellipse(15,6,c.size-140,c.size-140); ellipse(-15,6,c.size-140,c.size-140); fill(random(255),random(255),random(255)); ellipse(-30,-30,c.size-100,c.size-100); ellipse(35,-30,c.size-100,c.size-100); ellipse(35,-30,c.size-125,c.size-125); ellipse(-30,-30,c.size-125,c.size-125); ellipse(2,90,c.size-10,c.size-10); ellipse(2,90,c.size-30,c.size-30); pop() }
function drawHippo(){ let c = this push() // fill in code here, draw a funny face translate(c.posX,c.posY) text(c.name, c.size,-c.size) fill(c.color) // ellipse(0,0,c.size,c.size) ellipse(0,30,c.size-50,c.size-50); fill(0) ellipse(15,6,c.size-140,c.size-140); ellipse(-15,6,c.size-140,c.size-140); fill(random(255),random(255),random(255)); ellipse(-30,-30,c.size-100,c.size-100); ellipse(35,-30,c.size-100,c.size-100); ellipse(35,-30,c.size-125,c.size-125); ellipse(-30,-30,c.size-125,c.size-125); ellipse(2,90,c.size-10,c.size-10); ellipse(2,90,c.size-30,c.size-30); pop() }
JavaScript
function mousePressed() { // Check if mouse is inside the circle let d = dist(mouseX, mouseY, 200, 200); if (d < 100) { // Pick new random color values r = random(255); g = random(255); b = random(255); } }
function mousePressed() { // Check if mouse is inside the circle let d = dist(mouseX, mouseY, 200, 200); if (d < 100) { // Pick new random color values r = random(255); g = random(255); b = random(255); } }
JavaScript
function draw() { background(0) translate(windowWidth/2, windowHeight/4) rotate(-90) let hr=hour() let min=minute() let sec=second() strokeWeight(1) stroke(0, 210, 230) noFill() let end1 = map(sec, 0, 60, 0 ,360) arc(0,0, 340,340, 0,end1) let end2 = map(min, 0, 60, 0 ,360) arc(0,0, 300,300, 0,end2) let end3 = map(hr, 0, 12, 0 ,360) arc(0,0, 260,260, 0,end3) }
function draw() { background(0) translate(windowWidth/2, windowHeight/4) rotate(-90) let hr=hour() let min=minute() let sec=second() strokeWeight(1) stroke(0, 210, 230) noFill() let end1 = map(sec, 0, 60, 0 ,360) arc(0,0, 340,340, 0,end1) let end2 = map(min, 0, 60, 0 ,360) arc(0,0, 300,300, 0,end2) let end3 = map(hr, 0, 12, 0 ,360) arc(0,0, 260,260, 0,end3) }
JavaScript
function openNav() { console.log('open nav') document.getElementById("mySidebar").style.width = "500px"; document.getElementById("main").style.marginLeft = "500px"; }
function openNav() { console.log('open nav') document.getElementById("mySidebar").style.width = "500px"; document.getElementById("main").style.marginLeft = "500px"; }
JavaScript
function drawSkeleton() { // Loop through all the skeletons detected for (let i = 0; i < poses.length; i++) { let skeleton = poses[i].skeleton; // For every skeleton, loop through all body connections for (let j = 0; j < skeleton.length; j++) { let partA = skeleton[j][0]; let partB = skeleton[j][1]; stroke(0, 210, 230); line(partA.position.x, partA.position.y, partB.position.x, partB.position.y); } } }
function drawSkeleton() { // Loop through all the skeletons detected for (let i = 0; i < poses.length; i++) { let skeleton = poses[i].skeleton; // For every skeleton, loop through all body connections for (let j = 0; j < skeleton.length; j++) { let partA = skeleton[j][0]; let partB = skeleton[j][1]; stroke(0, 210, 230); line(partA.position.x, partA.position.y, partB.position.x, partB.position.y); } } }
JavaScript
function createProvider (collection, data, options = {}) { const result = validate([collection, data, options], providerSchemas) checkValidation(result) const args = result.values collection = args[0] data = args[1] options = args[2] const req = { pathParams: { collection }, body: data } if (Array.isArray(data)) { return createMultiple(req, options) } else { return createSingle(req, options) } }
function createProvider (collection, data, options = {}) { const result = validate([collection, data, options], providerSchemas) checkValidation(result) const args = result.values collection = args[0] data = args[1] options = args[2] const req = { pathParams: { collection }, body: data } if (Array.isArray(data)) { return createMultiple(req, options) } else { return createSingle(req, options) } }
JavaScript
function purgeProvider (path, options = {}) { const result = validate([path, options], providerSchemas) checkValidation(result) return purgeOp(...result.values) }
function purgeProvider (path, options = {}) { const result = validate([path, options], providerSchemas) checkValidation(result) return purgeOp(...result.values) }
JavaScript
function removeProvider (collection, data, options = {}) { const result = validate([collection, data, options], providerSchemas) checkValidation(result) const args = result.values collection = args[0] data = args[1] options = args[2] const req = { pathParams: { collection }, body: data } if (Array.isArray(data)) { return removeMultiple(req, options) } else { const shallowOpts = pick(options, shallowOptKeys) const deepOpts = omit(options, shallowOptKeys) return removeSingle(req, shallowOpts, deepOpts) } }
function removeProvider (collection, data, options = {}) { const result = validate([collection, data, options], providerSchemas) checkValidation(result) const args = result.values collection = args[0] data = args[1] options = args[2] const req = { pathParams: { collection }, body: data } if (Array.isArray(data)) { return removeMultiple(req, options) } else { const shallowOpts = pick(options, shallowOptKeys) const deepOpts = omit(options, shallowOptKeys) return removeSingle(req, shallowOpts, deepOpts) } }
JavaScript
function restoreProvider (path, options = {}) { const result = validate([path, options], providerSchemas) checkValidation(result) return restoreOp(...result.values) }
function restoreProvider (path, options = {}) { const result = validate([path, options], providerSchemas) checkValidation(result) return restoreOp(...result.values) }
JavaScript
function commitProvider (path, types) { const result = validate([path, types], providerSchemas) checkValidation(result) return syncOp(...result.values) }
function commitProvider (path, types) { const result = validate([path, types], providerSchemas) checkValidation(result) return syncOp(...result.values) }
JavaScript
function replaceProvider (collection, data, options = {}) { const result = validate([collection, data, options], providerSchemas) checkValidation(result) const args = result.values collection = args[0] data = args[1] options = args[2] const req = { pathParams: { collection }, body: data } if (Array.isArray(data)) { return replaceMultiple(req, options) } else { const shallowOpts = pick(options, shallowOptKeys) const deepOpts = omit(options, shallowOptKeys) return replaceSingle(req, shallowOpts, deepOpts) } }
function replaceProvider (collection, data, options = {}) { const result = validate([collection, data, options], providerSchemas) checkValidation(result) const args = result.values collection = args[0] data = args[1] options = args[2] const req = { pathParams: { collection }, body: data } if (Array.isArray(data)) { return replaceMultiple(req, options) } else { const shallowOpts = pick(options, shallowOptKeys) const deepOpts = omit(options, shallowOptKeys) return replaceSingle(req, shallowOpts, deepOpts) } }
JavaScript
function* loginAsync(action) { yield put(loginActions.enableLoader()); console.log("sdadsdqewqedadas",loginUser, action.username, action.password); try { const response = yield call( loginUser, action.username, action.password ); if (response.status == 200) { yield put(loginActions.onLoginResponse( response)); yield put(loginActions.disableLoader({})); yield call(navigationActions.navigateToHomeScreen); } else{ alert(response.message) yield put(loginActions.disableLoader({})); } } catch (error) { yield put(loginActions.loginFailed()); yield put(loginActions.disableLoader({})); } }
function* loginAsync(action) { yield put(loginActions.enableLoader()); console.log("sdadsdqewqedadas",loginUser, action.username, action.password); try { const response = yield call( loginUser, action.username, action.password ); if (response.status == 200) { yield put(loginActions.onLoginResponse( response)); yield put(loginActions.disableLoader({})); yield call(navigationActions.navigateToHomeScreen); } else{ alert(response.message) yield put(loginActions.disableLoader({})); } } catch (error) { yield put(loginActions.loginFailed()); yield put(loginActions.disableLoader({})); } }
JavaScript
_checkAppIntroStatus() { const { token } = this.props.loginReducer; console.log("Fsfsfsgfdg",this.props.loginReducer.token); if (token.length > 0) { this.props.navigation.navigate("DrawerStack"); } else { this.props.navigation.navigate("Login"); } }
_checkAppIntroStatus() { const { token } = this.props.loginReducer; console.log("Fsfsfsgfdg",this.props.loginReducer.token); if (token.length > 0) { this.props.navigation.navigate("DrawerStack"); } else { this.props.navigation.navigate("Login"); } }
JavaScript
function keyReleased() { if (keyCode === DOWN_ARROW) { balls[balls.length - 1].shoot(); cannoneplosion.play() } }
function keyReleased() { if (keyCode === DOWN_ARROW) { balls[balls.length - 1].shoot(); cannoneplosion.play() } }
JavaScript
function tth(message) { /** * Initialize the global variables * * @var alphabet a String that is split into a new Array(25); * * @var text a sanitized String of message with all characters * capitalized. Only letters A-Z are allowed * * @var hash an Array holding the running numerical total of the * block's columns. The final result will will be the hash */ var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""); var text = message.toUpperCase().replace(/[^A-Z]+/ig, ""); var hash = new Array(0, 0, 0, 0); /** * Compression Round 1: Create the blocks * * Seperate the sanitized text into 4 x 4 blocks. If the string * is not evenly divisable by 16 the remainders will be padded * with nulls. For future purposes a null holds the numerical * value of 0 just like 'A' * * @var blocks an Array that will hold the 4 x 4 blocks * from the sanitized String text. This Array * is pushed values of the Array rows * * @var rows an Array that will hold 4 rows of data * that is pushed from the letters Array * * @var letters an Array that will hold the index of the * alphabet Array based on the substring of the * sanitized text String * * @var blockRounds an Integer with a ceil value of text.length * divided by 16 * * @var letterCount an Integer that will track the letter position * of the sanitized text String */ var blocks = new Array(); var blockRounds = Math.ceil(text.length / 16); var letterCount = 0; while (blocks.length < blockRounds) { var rows = new Array(); while (rows.length < 4) { var letters = new Array(); while (letters.length < 4) { var letter = text.substr(letterCount, 1); letters.push((letter !== "") ? alphabet.indexOf(letter) : null); letterCount++; } rows.push(letters); } blocks.push(rows); } /** * Compression Round 2: Sum of Rows & Row Shifting * * This round of compression sums the columns of each block and adds * a modulus 26 of the sum to the hash total Array and then modulus 26 * the hash total. Next, each row of every block is shifted as follows: * The first row shifts one left, the second row shifts two left, the * third row shifts three left and the last row is reversed. The sums * of the columns of each shifted block are modulus 26 and added to the * running total. * * @var total an Array with 4 columns that holds the running total * of each block. The value of total is reset to 0, 0, 0, 0 * before each block's columns are summed */ for (var i = 0; i < blocks.length; i++) { var total = new Array(0, 0, 0, 0); for (var j = 0; j < blocks[i].length; j++) { /* Cycle through the columns and get their sum */ for (var k = 0; k < blocks[i][j].length; k++) { total[k] += blocks[i][j][k]; } } /* * Psudeo Arithmetic for adding up columns * * (COLUMN_1_SUM % 26, COLUMN_2_SUM % 26, COLUMN_3_SUM % 26, COLUMN_4_SUM % 26) PLUS * (RUN_TOTAL_1_SUM, RUN_TOTAL_2_SUM, RUN_TOTAL_3_SUM, RUN_TOTAL_4_SUM) EQUALS * (SUM_COL_1_SUM % 26, SUM_COL_2_SUM % 26, SUM_COL_3_SUM % 26, SUM_COL_4_SUM % 26) */ for (var j = 0; j < 4; j++) { hash[j] = (((total[j] % 26) + hash[j]) % 26); } var total = new Array(0, 0, 0, 0); for (var j = 0; j < blocks[i].length; j++) { /* Shift blocks switch */ switch (j) { /* Shift left 1 */ case 0: blocks[i][j].push(blocks[i][j].shift()); break; /* Shift left 2 */ case 1: blocks[i][j].push(blocks[i][j].shift()); blocks[i][j].push(blocks[i][j].shift()); break; /* Shift left 3 */ case 2: blocks[i][j].push(blocks[i][j].shift()); blocks[i][j].push(blocks[i][j].shift()); blocks[i][j].push(blocks[i][j].shift()); break; /* Reverse */ case 3: blocks[i][j].reverse(); break; } /* Cycle through the columns and get their sum */ for (var k = 0; k < blocks[i][j].length; k++) { total[k] += blocks[i][j][k]; } } /* * Psudeo Arithmetic for adding up columns * * (COLUMN_1_SUM % 26, COLUMN_2_SUM % 26, COLUMN_3_SUM % 26, COLUMN_4_SUM % 26) PLUS * (RUN_TOTAL_1_SUM, RUN_TOTAL_2_SUM, RUN_TOTAL_3_SUM, RUN_TOTAL_4_SUM) EQUALS * (SUM_COL_1_SUM % 26, SUM_COL_2_SUM % 26, SUM_COL_3_SUM % 26, SUM_COL_4_SUM % 26) */ for (var j = 0; j < 4; j++) { hash[j] = (((total[j] % 26) + hash[j]) % 26); } } /** * Alphanumeric Replacement * * Replace the Integer with the representative letter with the * alphabet Array */ for (var i = 0; i < 4; i++) { hash[i] = alphabet[hash[i]]; } /* Join the hash Array into a String with no seperator */ return hash.join(""); }
function tth(message) { /** * Initialize the global variables * * @var alphabet a String that is split into a new Array(25); * * @var text a sanitized String of message with all characters * capitalized. Only letters A-Z are allowed * * @var hash an Array holding the running numerical total of the * block's columns. The final result will will be the hash */ var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""); var text = message.toUpperCase().replace(/[^A-Z]+/ig, ""); var hash = new Array(0, 0, 0, 0); /** * Compression Round 1: Create the blocks * * Seperate the sanitized text into 4 x 4 blocks. If the string * is not evenly divisable by 16 the remainders will be padded * with nulls. For future purposes a null holds the numerical * value of 0 just like 'A' * * @var blocks an Array that will hold the 4 x 4 blocks * from the sanitized String text. This Array * is pushed values of the Array rows * * @var rows an Array that will hold 4 rows of data * that is pushed from the letters Array * * @var letters an Array that will hold the index of the * alphabet Array based on the substring of the * sanitized text String * * @var blockRounds an Integer with a ceil value of text.length * divided by 16 * * @var letterCount an Integer that will track the letter position * of the sanitized text String */ var blocks = new Array(); var blockRounds = Math.ceil(text.length / 16); var letterCount = 0; while (blocks.length < blockRounds) { var rows = new Array(); while (rows.length < 4) { var letters = new Array(); while (letters.length < 4) { var letter = text.substr(letterCount, 1); letters.push((letter !== "") ? alphabet.indexOf(letter) : null); letterCount++; } rows.push(letters); } blocks.push(rows); } /** * Compression Round 2: Sum of Rows & Row Shifting * * This round of compression sums the columns of each block and adds * a modulus 26 of the sum to the hash total Array and then modulus 26 * the hash total. Next, each row of every block is shifted as follows: * The first row shifts one left, the second row shifts two left, the * third row shifts three left and the last row is reversed. The sums * of the columns of each shifted block are modulus 26 and added to the * running total. * * @var total an Array with 4 columns that holds the running total * of each block. The value of total is reset to 0, 0, 0, 0 * before each block's columns are summed */ for (var i = 0; i < blocks.length; i++) { var total = new Array(0, 0, 0, 0); for (var j = 0; j < blocks[i].length; j++) { /* Cycle through the columns and get their sum */ for (var k = 0; k < blocks[i][j].length; k++) { total[k] += blocks[i][j][k]; } } /* * Psudeo Arithmetic for adding up columns * * (COLUMN_1_SUM % 26, COLUMN_2_SUM % 26, COLUMN_3_SUM % 26, COLUMN_4_SUM % 26) PLUS * (RUN_TOTAL_1_SUM, RUN_TOTAL_2_SUM, RUN_TOTAL_3_SUM, RUN_TOTAL_4_SUM) EQUALS * (SUM_COL_1_SUM % 26, SUM_COL_2_SUM % 26, SUM_COL_3_SUM % 26, SUM_COL_4_SUM % 26) */ for (var j = 0; j < 4; j++) { hash[j] = (((total[j] % 26) + hash[j]) % 26); } var total = new Array(0, 0, 0, 0); for (var j = 0; j < blocks[i].length; j++) { /* Shift blocks switch */ switch (j) { /* Shift left 1 */ case 0: blocks[i][j].push(blocks[i][j].shift()); break; /* Shift left 2 */ case 1: blocks[i][j].push(blocks[i][j].shift()); blocks[i][j].push(blocks[i][j].shift()); break; /* Shift left 3 */ case 2: blocks[i][j].push(blocks[i][j].shift()); blocks[i][j].push(blocks[i][j].shift()); blocks[i][j].push(blocks[i][j].shift()); break; /* Reverse */ case 3: blocks[i][j].reverse(); break; } /* Cycle through the columns and get their sum */ for (var k = 0; k < blocks[i][j].length; k++) { total[k] += blocks[i][j][k]; } } /* * Psudeo Arithmetic for adding up columns * * (COLUMN_1_SUM % 26, COLUMN_2_SUM % 26, COLUMN_3_SUM % 26, COLUMN_4_SUM % 26) PLUS * (RUN_TOTAL_1_SUM, RUN_TOTAL_2_SUM, RUN_TOTAL_3_SUM, RUN_TOTAL_4_SUM) EQUALS * (SUM_COL_1_SUM % 26, SUM_COL_2_SUM % 26, SUM_COL_3_SUM % 26, SUM_COL_4_SUM % 26) */ for (var j = 0; j < 4; j++) { hash[j] = (((total[j] % 26) + hash[j]) % 26); } } /** * Alphanumeric Replacement * * Replace the Integer with the representative letter with the * alphabet Array */ for (var i = 0; i < 4; i++) { hash[i] = alphabet[hash[i]]; } /* Join the hash Array into a String with no seperator */ return hash.join(""); }
JavaScript
function jsonHasChildrenArray(jsonObj){ return !$.isEmptyObject(jsonObj) && jsonObj.hasOwnProperty('children') && Array.isArray(jsonObj['children']); }
function jsonHasChildrenArray(jsonObj){ return !$.isEmptyObject(jsonObj) && jsonObj.hasOwnProperty('children') && Array.isArray(jsonObj['children']); }
JavaScript
function searchJsonArrayByName(jsonArray, name){ var res = null; for (let i = 0; i < jsonArray.length; i++){ if (jsonArray[i]['name'] === name){ res = jsonArray[i]; break }; if (jsonHasChildrenArray(jsonArray[i])) res = searchJsonArrayByName(jsonArray[i]['children'], name); if (res) break; // Return immediately if res is valid. Important for recursion. } return res; }
function searchJsonArrayByName(jsonArray, name){ var res = null; for (let i = 0; i < jsonArray.length; i++){ if (jsonArray[i]['name'] === name){ res = jsonArray[i]; break }; if (jsonHasChildrenArray(jsonArray[i])) res = searchJsonArrayByName(jsonArray[i]['children'], name); if (res) break; // Return immediately if res is valid. Important for recursion. } return res; }
JavaScript
function parseJson(loopBlock, pParentId, json){ let realName = loopBlock['name']; let vBlockName = (json) ? json['name'] : realName; let columns = {}; columns['pl'] = loopBlock['pl']; columns['ii'] = loopBlock['ii']; columns['af'] = loopBlock['af']; columns['mi'] = loopBlock['mi']; columns['lt'] = loopBlock['lt']; columns['si'] = (json) ? json['data'][2] : "n/a"; // block // details still comes from old json columns['brief'] = (json && json.hasOwnProperty('details') && json['details'][0]['type']==="brief") ? json['details'][0]['text']: ""; let noteCall = 'clearDivContent()'; if ( json && json.hasOwnProperty('details') ){ let detailHTML = getHTMLDetailsFromJSON(json['details'], json['name']); noteCall = 'changeDivContent(0,' + JSON.stringify(detailHTML) + ')'; } let debugLoc = null; if (loopBlock.hasOwnProperty('debug')) { debugLoc = loopBlock['debug']; } let rowId = loopBlock['id']; // Add Component invocation to name // name still comes from old json until we unify all the names let secondaryName = (loopBlock.hasOwnProperty('ci') && loopBlock['ci'] === '1') ? " (Component invocation)" : ""; loopDataRows.push( new FPGADataRow(rowId, vBlockName+secondaryName, debugLoc, columns, '', pParentId, 0, '', noteCall, '') ); // iterate using loopBlock because it's topologically sorted if ( jsonHasChildrenArray(loopBlock) ) { loopBlock['children'].forEach(function (child) { if (child['type'] === 'loop') { let vSubLoopName = child['name']; if (jsonHasChildrenArray(json)) { let vSubLoop = null; // just search immediate children for subloop for (let i = 0; i < json['children'].length; i++) { if (vSubLoopName === getRealName(json['children'][i]['name'])) { vSubLoop = json['children'][i]; break; } } parseJson(child, rowId, vSubLoop); } else { // can't find subloop in old loopJSON parseJson(child, rowId, null); } } else if (vShowBlock) { parseJson(child, rowId, null); } }); } }
function parseJson(loopBlock, pParentId, json){ let realName = loopBlock['name']; let vBlockName = (json) ? json['name'] : realName; let columns = {}; columns['pl'] = loopBlock['pl']; columns['ii'] = loopBlock['ii']; columns['af'] = loopBlock['af']; columns['mi'] = loopBlock['mi']; columns['lt'] = loopBlock['lt']; columns['si'] = (json) ? json['data'][2] : "n/a"; // block // details still comes from old json columns['brief'] = (json && json.hasOwnProperty('details') && json['details'][0]['type']==="brief") ? json['details'][0]['text']: ""; let noteCall = 'clearDivContent()'; if ( json && json.hasOwnProperty('details') ){ let detailHTML = getHTMLDetailsFromJSON(json['details'], json['name']); noteCall = 'changeDivContent(0,' + JSON.stringify(detailHTML) + ')'; } let debugLoc = null; if (loopBlock.hasOwnProperty('debug')) { debugLoc = loopBlock['debug']; } let rowId = loopBlock['id']; // Add Component invocation to name // name still comes from old json until we unify all the names let secondaryName = (loopBlock.hasOwnProperty('ci') && loopBlock['ci'] === '1') ? " (Component invocation)" : ""; loopDataRows.push( new FPGADataRow(rowId, vBlockName+secondaryName, debugLoc, columns, '', pParentId, 0, '', noteCall, '') ); // iterate using loopBlock because it's topologically sorted if ( jsonHasChildrenArray(loopBlock) ) { loopBlock['children'].forEach(function (child) { if (child['type'] === 'loop') { let vSubLoopName = child['name']; if (jsonHasChildrenArray(json)) { let vSubLoop = null; // just search immediate children for subloop for (let i = 0; i < json['children'].length; i++) { if (vSubLoopName === getRealName(json['children'][i]['name'])) { vSubLoop = json['children'][i]; break; } } parseJson(child, rowId, vSubLoop); } else { // can't find subloop in old loopJSON parseJson(child, rowId, null); } } else if (vShowBlock) { parseJson(child, rowId, null); } }); } }
JavaScript
function flattenNodesHelper(nodeList, parent) { if(!nodeList) return; nodeList.forEach(function(n) { n['parent'] = parent; flattenedNodes.set(n['id'], n); if(n['children']) { flattenNodesHelper(n['children'], n); } }) }
function flattenNodesHelper(nodeList, parent) { if(!nodeList) return; nodeList.forEach(function(n) { n['parent'] = parent; flattenedNodes.set(n['id'], n); if(n['children']) { flattenNodesHelper(n['children'], n); } }) }
JavaScript
function flattenNodesHelper(nodeList) { if(!nodeList) return; nodeList.forEach(function(n) { flattenedNodes.set(n['id'], n); if(n['children']) { flattenNodesHelper(n['children']); } }) }
function flattenNodesHelper(nodeList) { if(!nodeList) return; nodeList.forEach(function(n) { flattenedNodes.set(n['id'], n); if(n['children']) { flattenNodesHelper(n['children']); } }) }
JavaScript
function nodeListIncludes(nodeList, nodeId) { let found = false; nodeList.forEach(function(n) { if(n['id'] == nodeId) found = true; if(n['children'] && !found) found = nodeListIncludes(n['children'], nodeId); }); return found; }
function nodeListIncludes(nodeList, nodeId) { let found = false; nodeList.forEach(function(n) { if(n['id'] == nodeId) found = true; if(n['children'] && !found) found = nodeListIncludes(n['children'], nodeId); }); return found; }
JavaScript
function renderNoGraphForType(graph, title, type, details, message){ let contentText; switch(type){ case 'reg': contentText = OPT_AS_REG_DIV; break; case 'unsynth': contentText = UNSYNTH_DIV; break; case 'untrack': contentText = UNTRACK_DIV; break; case 'no_nodes': contentText = NO_NODES_DIV; break; case 'choose_graph': contentText = SELECT_GRAPH_DIV; break; case 'message': contentText = GRAPH_MESSAGE_PREFIX + message + GRAPH_MESSAGE_SUFFIX; break; default: contentText = ''; } $(graph).html(contentText); changeDetailsPane(details, title); }
function renderNoGraphForType(graph, title, type, details, message){ let contentText; switch(type){ case 'reg': contentText = OPT_AS_REG_DIV; break; case 'unsynth': contentText = UNSYNTH_DIV; break; case 'untrack': contentText = UNTRACK_DIV; break; case 'no_nodes': contentText = NO_NODES_DIV; break; case 'choose_graph': contentText = SELECT_GRAPH_DIV; break; case 'message': contentText = GRAPH_MESSAGE_PREFIX + message + GRAPH_MESSAGE_SUFFIX; break; default: contentText = ''; } $(graph).html(contentText); changeDetailsPane(details, title); }
JavaScript
function createTreeNode (pName, pCheckBox, pExpand, pType, pID, pLocation, pCaption, pIcon, pChildren) { var treeNode = {}; treeNode['name'] = pName; treeNode['title'] = document.createTextNode(pName).data; let vLocation = (pLocation) ? pLocation : null; if (vLocation) treeNode['debug'] = vLocation; if (pCaption) treeNode['title'] += '&nbsp;' + pCaption; if (pType) treeNode['type'] = pType; if (pID) treeNode['id'] = pID; treeNode['hideCheckbox'] = !pCheckBox; // old verion is hide (inverted) treeNode['expanded'] = pExpand; if (pIcon) treeNode['icon'] = pIcon; treeNode['children'] = []; if (pChildren !== undefined && pChildren !== null && Array.isArray(pChildren) && pChildren.lenght > 0) { for(let c=0; c<pChildren.length; c++) { this.vChildren.push(pChildren[ci]); } } return treeNode; }
function createTreeNode (pName, pCheckBox, pExpand, pType, pID, pLocation, pCaption, pIcon, pChildren) { var treeNode = {}; treeNode['name'] = pName; treeNode['title'] = document.createTextNode(pName).data; let vLocation = (pLocation) ? pLocation : null; if (vLocation) treeNode['debug'] = vLocation; if (pCaption) treeNode['title'] += '&nbsp;' + pCaption; if (pType) treeNode['type'] = pType; if (pID) treeNode['id'] = pID; treeNode['hideCheckbox'] = !pCheckBox; // old verion is hide (inverted) treeNode['expanded'] = pExpand; if (pIcon) treeNode['icon'] = pIcon; treeNode['children'] = []; if (pChildren !== undefined && pChildren !== null && Array.isArray(pChildren) && pChildren.lenght > 0) { for(let c=0; c<pChildren.length; c++) { this.vChildren.push(pChildren[ci]); } } return treeNode; }
JavaScript
function scrollToElement(element, parent, extraOffset) { var vExtraOffset = (extraOffset && parseInt(extraOffset)) ? parseInt(extraOffset) : 0; $(parent)[0].scrollIntoView(true); $(parent).animate({ scrollTop: $(parent).scrollTop() + $(element).offset().top - $(parent).offset().top - vExtraOffset }, { duration: 'slow', easing: 'swing' }); }
function scrollToElement(element, parent, extraOffset) { var vExtraOffset = (extraOffset && parseInt(extraOffset)) ? parseInt(extraOffset) : 0; $(parent)[0].scrollIntoView(true); $(parent).animate({ scrollTop: $(parent).scrollTop() + $(element).offset().top - $(parent).offset().top - vExtraOffset }, { duration: 'slow', easing: 'swing' }); }
JavaScript
function scrollToDiv(data) { var parent = $('#report-summary'); var elem = $('#' + data.node.data.id); scrollToElement(elem, parent); }
function scrollToDiv(data) { var parent = $('#report-summary'); var elem = $('#' + data.node.data.id); scrollToElement(elem, parent); }
JavaScript
function selectBottleneckNode(event, pBottleneckTreeData) { // Check if checkbox is clicked by first getting the current selected let vCurrSelBottlenecks = {}; pBottleneckTreeData.tree.getSelectedNodes().forEach(function (n) { if (n.data.type === "Occupancy limiter" || n.data.type === "Fmax/II") { vCurrSelBottlenecks[n.data.id] = 1; } }); // Compare the checked boxes against what was previously checked // remove bottleneck limiter that's not part of current selected let vNewSelected = true; for(let bi=0; bi<vSelectedBottleneckIDs.length; bi++) { let n = vSelectedBottleneckIDs[bi]; if (!vCurrSelBottlenecks.hasOwnProperty(n['id'])) { removeBottleneck(n); vSelectedBottleneckIDs.splice(bi, 1); vNewSelected = false; break; } } if (vNewSelected) { let vNodeData = pBottleneckTreeData.node.data; if (vNodeData.hasOwnProperty('id')) { let vIndex = parseInt(vNodeData['id'].substring(4)); let vSchBottleneck = addBottleneck(bottleneckJSON['bottlenecks'][vIndex]); vSchBottleneck['id'] = vNodeData['id']; vSelectedBottleneckIDs.push(vSchBottleneck); } } redrawSchedule(); }
function selectBottleneckNode(event, pBottleneckTreeData) { // Check if checkbox is clicked by first getting the current selected let vCurrSelBottlenecks = {}; pBottleneckTreeData.tree.getSelectedNodes().forEach(function (n) { if (n.data.type === "Occupancy limiter" || n.data.type === "Fmax/II") { vCurrSelBottlenecks[n.data.id] = 1; } }); // Compare the checked boxes against what was previously checked // remove bottleneck limiter that's not part of current selected let vNewSelected = true; for(let bi=0; bi<vSelectedBottleneckIDs.length; bi++) { let n = vSelectedBottleneckIDs[bi]; if (!vCurrSelBottlenecks.hasOwnProperty(n['id'])) { removeBottleneck(n); vSelectedBottleneckIDs.splice(bi, 1); vNewSelected = false; break; } } if (vNewSelected) { let vNodeData = pBottleneckTreeData.node.data; if (vNodeData.hasOwnProperty('id')) { let vIndex = parseInt(vNodeData['id'].substring(4)); let vSchBottleneck = addBottleneck(bottleneckJSON['bottlenecks'][vIndex]); vSchBottleneck['id'] = vNodeData['id']; vSelectedBottleneckIDs.push(vSchBottleneck); } } redrawSchedule(); }
JavaScript
function newFPGAElement(pParent, pType, pClass, pID, pText) { let vID = (pID !== undefined && pID) ? pID : 0; // cannot be 0 let vNewElem = pParent.appendChild(document.createElement(pType)); if (pClass) vNewElem.className = pClass; if (pText !== undefined && pText !== null) { if (pText.indexOf && pText.indexOf('<') === -1 && pText.indexOf && pText.indexOf('&') !== 0 ) vNewElem.appendChild(document.createTextNode(pText)); else vNewElem.insertAdjacentHTML('beforeend', pText); } if (vID) vNewElem.id = vID; return vNewElem; }
function newFPGAElement(pParent, pType, pClass, pID, pText) { let vID = (pID !== undefined && pID) ? pID : 0; // cannot be 0 let vNewElem = pParent.appendChild(document.createElement(pType)); if (pClass) vNewElem.className = pClass; if (pText !== undefined && pText !== null) { if (pText.indexOf && pText.indexOf('<') === -1 && pText.indexOf && pText.indexOf('&') !== 0 ) vNewElem.appendChild(document.createTextNode(pText)); else vNewElem.insertAdjacentHTML('beforeend', pText); } if (vID) vNewElem.id = vID; return vNewElem; }
JavaScript
function createEmptyCard(pParent, pID, pName, pClass) { let vTmpClass = (pClass) ? pClass+' ' : ''; var vTmpCard = newFPGAElement(pParent, 'div', vTmpClass+'card'); vTmpClass = (pClass) ? pClass+'-header ' : ''; var vTmpDiv = newFPGAElement(vTmpCard, 'h7', vTmpClass+'card-header', pID); vTmpDiv.setAttribute('role', 'tab'); vTmpDiv = newFPGAElement(vTmpDiv, 'a', 'd-block', 0, pName); vTmpDiv.className = 'disabled'; // disable this link pParent.appendChild(vTmpCard); }
function createEmptyCard(pParent, pID, pName, pClass) { let vTmpClass = (pClass) ? pClass+' ' : ''; var vTmpCard = newFPGAElement(pParent, 'div', vTmpClass+'card'); vTmpClass = (pClass) ? pClass+'-header ' : ''; var vTmpDiv = newFPGAElement(vTmpCard, 'h7', vTmpClass+'card-header', pID); vTmpDiv.setAttribute('role', 'tab'); vTmpDiv = newFPGAElement(vTmpDiv, 'a', 'd-block', 0, pName); vTmpDiv.className = 'disabled'; // disable this link pParent.appendChild(vTmpCard); }
JavaScript
function createTreeCard(pParent, pID, headerName, enableFilter) { let vID = pID; let vHeaderID = vID+'Header'; let vTmpDiv = newFPGAElement(pParent, 'div', 'card', 'report-panel-tree'); let treeHeading = newFPGAElement(vTmpDiv, 'div', 'card-header', vHeaderID, headerName); if (enableFilter) { let filterButton = document.createElement('button'); filterButton.className = "btn btn-default btn-sm dropdown-toggle"; filterButton.setAttribute("data-toggle", "dropdown"); // Make the filter button text let filterButtonText = document.createElement('span'); filterButtonText.className = "body glyphicon"; filterButtonText.innerHTML = "&#xe138;"; filterButton.appendChild(filterButtonText); filterButtonText = document.createElement('span'); filterButtonText.className = "caret"; filterButton.appendChild(filterButtonText); // Button and dropdown list let filterButtonGroup = document.createElement('div'); filterButtonGroup.id = pID + "-button"; filterButtonGroup.className = "btn-group float-right"; filterButtonGroup.appendChild(filterButton); // Drop down, data will be fill dynamically for each view let filterDropDown = document.createElement('div'); filterDropDown.id = pID + "-filter"; filterDropDown.className = "dropdown-menu dropdown-menu-right"; filterButtonGroup.appendChild(filterDropDown); treeHeading.appendChild(filterButtonGroup); } vTmpDiv = newFPGAElement(vTmpDiv, 'div', 'tree-body card-body', vID); }
function createTreeCard(pParent, pID, headerName, enableFilter) { let vID = pID; let vHeaderID = vID+'Header'; let vTmpDiv = newFPGAElement(pParent, 'div', 'card', 'report-panel-tree'); let treeHeading = newFPGAElement(vTmpDiv, 'div', 'card-header', vHeaderID, headerName); if (enableFilter) { let filterButton = document.createElement('button'); filterButton.className = "btn btn-default btn-sm dropdown-toggle"; filterButton.setAttribute("data-toggle", "dropdown"); // Make the filter button text let filterButtonText = document.createElement('span'); filterButtonText.className = "body glyphicon"; filterButtonText.innerHTML = "&#xe138;"; filterButton.appendChild(filterButtonText); filterButtonText = document.createElement('span'); filterButtonText.className = "caret"; filterButton.appendChild(filterButtonText); // Button and dropdown list let filterButtonGroup = document.createElement('div'); filterButtonGroup.id = pID + "-button"; filterButtonGroup.className = "btn-group float-right"; filterButtonGroup.appendChild(filterButton); // Drop down, data will be fill dynamically for each view let filterDropDown = document.createElement('div'); filterDropDown.id = pID + "-filter"; filterDropDown.className = "dropdown-menu dropdown-menu-right"; filterButtonGroup.appendChild(filterDropDown); treeHeading.appendChild(filterButtonGroup); } vTmpDiv = newFPGAElement(vTmpDiv, 'div', 'tree-body card-body', vID); }
JavaScript
splitTimestamp(timestamp) { let num; const out = { large: null, small: null }; if (timestamp !== null && timestamp !== undefined) { num = new BN(timestamp, 10); out.small = num.and(new BN('FFFFFFFF', 16)).toNumber(); out.large = num.shrn(32).toNumber(); } return out; }
splitTimestamp(timestamp) { let num; const out = { large: null, small: null }; if (timestamp !== null && timestamp !== undefined) { num = new BN(timestamp, 10); out.small = num.and(new BN('FFFFFFFF', 16)).toNumber(); out.large = num.shrn(32).toNumber(); } return out; }
JavaScript
joinTimestamp(splitTimestamp) { let nl, ns; let out = null; if ( splitTimestamp && splitTimestamp.large !== undefined && splitTimestamp.small !== undefined ) { nl = new BN(splitTimestamp.large, 10); ns = new BN(splitTimestamp.small, 10); out = nl.shln(32).toNumber() + ns.toNumber(); } return out; }
joinTimestamp(splitTimestamp) { let nl, ns; let out = null; if ( splitTimestamp && splitTimestamp.large !== undefined && splitTimestamp.small !== undefined ) { nl = new BN(splitTimestamp.large, 10); ns = new BN(splitTimestamp.small, 10); out = nl.shln(32).toNumber() + ns.toNumber(); } return out; }
JavaScript
intToRawStr(intVal) { const i1 = intVal >>> 24 & 255; const i2 = intVal >>> 16 & 255; const i3 = intVal >>> 8 & 255; const i4 = intVal >>> 0 & 255; const s1 = String.fromCharCode(i1); const s2 = String.fromCharCode(i2); const s3 = String.fromCharCode(i3); const s4 = String.fromCharCode(i4); return `${s1}${s2}${s3}${s4}`; }
intToRawStr(intVal) { const i1 = intVal >>> 24 & 255; const i2 = intVal >>> 16 & 255; const i3 = intVal >>> 8 & 255; const i4 = intVal >>> 0 & 255; const s1 = String.fromCharCode(i1); const s2 = String.fromCharCode(i2); const s3 = String.fromCharCode(i3); const s4 = String.fromCharCode(i4); return `${s1}${s2}${s3}${s4}`; }
JavaScript
rawStrToInt(rawStr) { const s1 = rawStr.charAt(0); const s2 = rawStr.charAt(1); const s3 = rawStr.charAt(2); const s4 = rawStr.charAt(3); const c1 = s1.charCodeAt(0); const c2 = s2.charCodeAt(0); const c3 = s3.charCodeAt(0); const c4 = s4.charCodeAt(0); const i1 = c1 << 24 >>> 0; const i2 = c2 << 16 >>> 0; const i3 = c3 << 8 >>> 0; const i4 = c4 << 0 >>> 0; return i1 + i2 + i3 + i4; }
rawStrToInt(rawStr) { const s1 = rawStr.charAt(0); const s2 = rawStr.charAt(1); const s3 = rawStr.charAt(2); const s4 = rawStr.charAt(3); const c1 = s1.charCodeAt(0); const c2 = s2.charCodeAt(0); const c3 = s3.charCodeAt(0); const c4 = s4.charCodeAt(0); const i1 = c1 << 24 >>> 0; const i2 = c2 << 16 >>> 0; const i3 = c3 << 8 >>> 0; const i4 = c4 << 0 >>> 0; return i1 + i2 + i3 + i4; }
JavaScript
uuidToRawBuffer(uuid) { let str, num; const buff = []; uuid = uuid.replace(/-/g, ''); for (let itr = 0; itr < 16; itr++) { str = uuid.charAt(itr * 2) + uuid.charAt(itr * 2 + 1); num = Number.parseInt(str, 16); buff.push(num); } const out = Buffer.from(buff); return out; }
uuidToRawBuffer(uuid) { let str, num; const buff = []; uuid = uuid.replace(/-/g, ''); for (let itr = 0; itr < 16; itr++) { str = uuid.charAt(itr * 2) + uuid.charAt(itr * 2 + 1); num = Number.parseInt(str, 16); buff.push(num); } const out = Buffer.from(buff); return out; }
JavaScript
cryptInt(intVal, passphrase, iv) { const pass = Buffer.allocUnsafe(32).fill('\u0000'); Buffer.from(passphrase).copy(pass); const cipher = crypto.createCipheriv('aes-256-ctr', pass, iv); let enc = cipher.update(this.intToRawStr(intVal), 'latin1', 'latin1'); enc += cipher.final('latin1'); const out = this.rawStrToInt(enc); return out; }
cryptInt(intVal, passphrase, iv) { const pass = Buffer.allocUnsafe(32).fill('\u0000'); Buffer.from(passphrase).copy(pass); const cipher = crypto.createCipheriv('aes-256-ctr', pass, iv); let enc = cipher.update(this.intToRawStr(intVal), 'latin1', 'latin1'); enc += cipher.final('latin1'); const out = this.rawStrToInt(enc); return out; }
JavaScript
function authenticate(helper, paramsValues, credentials) { print("Wordpress Authenticating via JavaScript script..."); // Make sure any Java classes used explicitly are imported var HttpRequestHeader = Java.type("org.parosproxy.paros.network.HttpRequestHeader") var HttpHeader = Java.type("org.parosproxy.paros.network.HttpHeader") var URI = Java.type("org.apache.commons.httpclient.URI") var Cookie = Java.type("org.apache.commons.httpclient.Cookie") // Prepare the login request details var domain = paramsValues.get("Domain"); var path = paramsValues.get("Path"); print("Logging in to domain " + domain + " and path " + path); var requestUri = new URI("http://"+domain + path + "wp-login.php", false); var requestMethod = HttpRequestHeader.POST; // Build the request body using the credentials values var requestBody = "log=" + encodeURIComponent(credentials.getParam("Username")); requestBody = requestBody + "&pwd=" + encodeURIComponent(credentials.getParam("Password")); requestBody = requestBody + "&rememberme=forever&wp-submit=Log+In&testcookie=1"; // Add the proper cookie to the header var requestHeader = new HttpRequestHeader(requestMethod, requestUri, HttpHeader.HTTP10); requestHeader.setHeader(HttpHeader.COOKIE, "wordpress_test_cookie=WP+Cookie+check"); // Build the actual message to be sent print("Sending " + requestMethod + " request to " + requestUri + " with body: " + requestBody); var msg = helper.prepareMessage(); msg.setRequestHeader(requestHeader); msg.setRequestBody(requestBody); // Send the authentication message and return it helper.sendAndReceive(msg); print("Received response status code for authentication request: " + msg.getResponseHeader().getStatusCode()); // The path Wordpress sets on the session cookies is illegal according to the standard. The web browsers ignore this and use the cookies anyway, but the Apache Commons HttpClient used in ZAP really cares about this (probably the only one who does it) and simply ignores the "invalid" cookies [0] , [1],so we must make sure we MANUALLY add the response cookies if(path != "/" && path.charAt(path.length() - 1) == '/') { path = path.substring(0, path.length() - 1); } print("Cleaned cookie path: " + path); var cookies = msg.getResponseHeader().getCookieParams(); var state = helper.getCorrespondingHttpState(); for(var iterator = cookies.iterator(); iterator.hasNext();){ var cookie = iterator.next(); print("Manually adding cookie: " + cookie.getName() + " = " + cookie.getValue()); state.addCookie(new Cookie(domain, cookie.getName(), cookie.getValue(), path, 999999, false)); } return msg; }
function authenticate(helper, paramsValues, credentials) { print("Wordpress Authenticating via JavaScript script..."); // Make sure any Java classes used explicitly are imported var HttpRequestHeader = Java.type("org.parosproxy.paros.network.HttpRequestHeader") var HttpHeader = Java.type("org.parosproxy.paros.network.HttpHeader") var URI = Java.type("org.apache.commons.httpclient.URI") var Cookie = Java.type("org.apache.commons.httpclient.Cookie") // Prepare the login request details var domain = paramsValues.get("Domain"); var path = paramsValues.get("Path"); print("Logging in to domain " + domain + " and path " + path); var requestUri = new URI("http://"+domain + path + "wp-login.php", false); var requestMethod = HttpRequestHeader.POST; // Build the request body using the credentials values var requestBody = "log=" + encodeURIComponent(credentials.getParam("Username")); requestBody = requestBody + "&pwd=" + encodeURIComponent(credentials.getParam("Password")); requestBody = requestBody + "&rememberme=forever&wp-submit=Log+In&testcookie=1"; // Add the proper cookie to the header var requestHeader = new HttpRequestHeader(requestMethod, requestUri, HttpHeader.HTTP10); requestHeader.setHeader(HttpHeader.COOKIE, "wordpress_test_cookie=WP+Cookie+check"); // Build the actual message to be sent print("Sending " + requestMethod + " request to " + requestUri + " with body: " + requestBody); var msg = helper.prepareMessage(); msg.setRequestHeader(requestHeader); msg.setRequestBody(requestBody); // Send the authentication message and return it helper.sendAndReceive(msg); print("Received response status code for authentication request: " + msg.getResponseHeader().getStatusCode()); // The path Wordpress sets on the session cookies is illegal according to the standard. The web browsers ignore this and use the cookies anyway, but the Apache Commons HttpClient used in ZAP really cares about this (probably the only one who does it) and simply ignores the "invalid" cookies [0] , [1],so we must make sure we MANUALLY add the response cookies if(path != "/" && path.charAt(path.length() - 1) == '/') { path = path.substring(0, path.length() - 1); } print("Cleaned cookie path: " + path); var cookies = msg.getResponseHeader().getCookieParams(); var state = helper.getCorrespondingHttpState(); for(var iterator = cookies.iterator(); iterator.hasNext();){ var cookie = iterator.next(); print("Manually adding cookie: " + cookie.getName() + " = " + cookie.getValue()); state.addCookie(new Cookie(domain, cookie.getName(), cookie.getValue(), path, 999999, false)); } return msg; }
JavaScript
function extractWebSession(sessionWrapper) { // You can add any objects to the session as required sessionWrapper.getSession().setValue("value1", "Example 1"); sessionWrapper.getSession().setValue("value2", "Example 2"); }
function extractWebSession(sessionWrapper) { // You can add any objects to the session as required sessionWrapper.getSession().setValue("value1", "Example 1"); sessionWrapper.getSession().setValue("value2", "Example 2"); }
JavaScript
function processMessageToMatchSession(sessionWrapper) { // You can retrieve any objects stored to the session as required var val1 = sessionWrapper.getSession().getValue("value1"); var val2 = sessionWrapper.getSession().getValue("value2"); var exampleTargetURL = sessionWrapper.getParam('exampleTargetURL'); print('Got val1: ' + val1 + ' val2: ' + val2 + ' exampleTargetURL: ' + exampleTargetURL) }
function processMessageToMatchSession(sessionWrapper) { // You can retrieve any objects stored to the session as required var val1 = sessionWrapper.getSession().getValue("value1"); var val2 = sessionWrapper.getSession().getValue("value2"); var exampleTargetURL = sessionWrapper.getParam('exampleTargetURL'); print('Got val1: ' + val1 + ' val2: ' + val2 + ' exampleTargetURL: ' + exampleTargetURL) }
JavaScript
function handleAmbiguousExtensionType(filepath) { try { let dirname = path.dirname(filepath); let extname = path.extname(filepath); let basename = path.basename(filepath, extname); let configuration = require(`${ dirname }/${ basename }.js`); return Promisie.resolve(configuration); } catch (e) { return fs.readJson(filepath); } }
function handleAmbiguousExtensionType(filepath) { try { let dirname = path.dirname(filepath); let extname = path.extname(filepath); let basename = path.basename(filepath, extname); let configuration = require(`${ dirname }/${ basename }.js`); return Promisie.resolve(configuration); } catch (e) { return fs.readJson(filepath); } }
JavaScript
function handleManifestCompilation(manifests) { return manifests.reduce((result, manifest) => { result.containers = Object.assign(result.containers || {}, manifest.containers); return result; }, {}); }
function handleManifestCompilation(manifests) { return manifests.reduce((result, manifest) => { result.containers = Object.assign(result.containers || {}, manifest.containers); return result; }, {}); }
JavaScript
function pullManifestSettings(configuration, isUnauthenticated = false) { let extensions = (Array.isArray(configuration))? configuration: configuration.extensions || []; let filePaths = extensions.reduce((result, config) => { if (config.enabled && config.periodic_config && config.periodic_config['periodicjs_ext_reactapp'] && config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests']) { if (Array.isArray(config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests'])) return result.concat(config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests']); result.push(config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests']); } return result; }, []); return readAndStoreConfigurations(filePaths || [], (isUnauthenticated) ? 'unauthenticated' : 'manifest') .then(handleManifestCompilation) .catch(e => Promisie.reject(e)); }
function pullManifestSettings(configuration, isUnauthenticated = false) { let extensions = (Array.isArray(configuration))? configuration: configuration.extensions || []; let filePaths = extensions.reduce((result, config) => { if (config.enabled && config.periodic_config && config.periodic_config['periodicjs_ext_reactapp'] && config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests']) { if (Array.isArray(config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests'])) return result.concat(config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests']); result.push(config.periodic_config['periodicjs_ext_reactapp'][(isUnauthenticated) ? 'unauthenticated_manifests' : 'manifests']); } return result; }, []); return readAndStoreConfigurations(filePaths || [], (isUnauthenticated) ? 'unauthenticated' : 'manifest') .then(handleManifestCompilation) .catch(e => Promisie.reject(e)); }
JavaScript
function pullComponentSettings(refresh) { if (Object.keys(components).length && !refresh) return Promisie.resolve(components); // console.log({components}) return readAndStoreConfigurations([ handleAmbiguousExtensionType.bind(null, path.join(__dirname, '../periodicjs.reactapp.json')), handleAmbiguousExtensionType.bind(null, path.join(__dirname, `../../../content/container/${appSettings.theme || appSettings.themename}/periodicjs.reactapp.json`)), ]) .then(results => { // console.log('util.inspect(results,{depth:20})', util.inspect(results, { depth: 20 })); switch (Object.keys(results).length.toString()) { case '1': return Object.assign({}, (results[0]['periodicjs_ext_reactapp']) ? results[0]['periodicjs_ext_reactapp'].components : {}); case '2': return Object.assign({}, (results[0]['periodicjs_ext_reactapp']) ? results[0]['periodicjs_ext_reactapp'].components : {}, (results[1]['periodicjs_ext_reactapp']) ? results[1]['periodicjs_ext_reactapp'].components : {}); default: return {}; } }) .then(results => { if (!components || typeof refresh !== 'string') return results; else if (typeof refresh === 'string') return { [refresh]: results[refresh], }; }) .then(results => Promisie.parallel(generateComponentOperations(results, (!components) ? DEFAULT_COMPONENTS : components))) .then(results => { components = Object.assign(components, (!components) ? DEFAULT_COMPONENTS : components, results); return assignComponentStatus(components); }) .catch(e => Promisie.reject(e)); }
function pullComponentSettings(refresh) { if (Object.keys(components).length && !refresh) return Promisie.resolve(components); // console.log({components}) return readAndStoreConfigurations([ handleAmbiguousExtensionType.bind(null, path.join(__dirname, '../periodicjs.reactapp.json')), handleAmbiguousExtensionType.bind(null, path.join(__dirname, `../../../content/container/${appSettings.theme || appSettings.themename}/periodicjs.reactapp.json`)), ]) .then(results => { // console.log('util.inspect(results,{depth:20})', util.inspect(results, { depth: 20 })); switch (Object.keys(results).length.toString()) { case '1': return Object.assign({}, (results[0]['periodicjs_ext_reactapp']) ? results[0]['periodicjs_ext_reactapp'].components : {}); case '2': return Object.assign({}, (results[0]['periodicjs_ext_reactapp']) ? results[0]['periodicjs_ext_reactapp'].components : {}, (results[1]['periodicjs_ext_reactapp']) ? results[1]['periodicjs_ext_reactapp'].components : {}); default: return {}; } }) .then(results => { if (!components || typeof refresh !== 'string') return results; else if (typeof refresh === 'string') return { [refresh]: results[refresh], }; }) .then(results => Promisie.parallel(generateComponentOperations(results, (!components) ? DEFAULT_COMPONENTS : components))) .then(results => { components = Object.assign(components, (!components) ? DEFAULT_COMPONENTS : components, results); return assignComponentStatus(components); }) .catch(e => Promisie.reject(e)); }
JavaScript
function handleConfigurationReload(type) { if (type.toLowerCase() === 'components') { return pullComponentSettings.bind(null, true); } else { return pullConfigurationSettings.bind(null, type.toLowerCase()); } }
function handleConfigurationReload(type) { if (type.toLowerCase() === 'components') { return pullComponentSettings.bind(null, true); } else { return pullConfigurationSettings.bind(null, type.toLowerCase()); } }
JavaScript
function pullConfigurationSettings(reload) { if (Object.keys(manifestSettings).length && Object.keys(navigationSettings).length && Object.keys(unauthenticatedManifestSettings).length && !reload) return Promisie.resolve({ manifest: manifestSettings, navigation: navigationSettings, unauthenticated: unauthenticatedManifestSettings, }); return Promisie.all( [ Promise.resolve({ extensions:Array.from(periodic.extensions.values()).filter(ext => ext.periodic_config && ext.periodic_config.periodicjs_ext_reactapp), }), // fs.readJson(path.join(__dirname, '../../../content/config/extensions.json')), handleAmbiguousExtensionType(path.join(__dirname, '../periodicjs.reactapp.json')), ] ) .then(configurationData => { let [configuration, adminExtSettings, ] = configurationData; adminExtSettings = adminExtSettings['periodicjs_ext_reactapp']; if (periodic.settings.extensions[ 'periodicjs.ext.reactapp' ].default_manifests.include_default_manifests === false) { adminExtSettings.manifests = []; adminExtSettings.unauthenticated = []; } let operations = {}; if (reload === 'manifest' || reload === true || !Object.keys(manifestSettings).length) { operations = Object.assign(operations, { manifests: pullManifestSettings.bind(null, configuration), default_manifests: readAndStoreConfigurations.bind(null, adminExtSettings.manifests || [], 'manifest'), }); } if (reload === 'unauthenticated' || reload === true || !Object.keys(unauthenticatedManifestSettings).length) { operations = Object.assign(operations, { unauthenticated_manifests: pullManifestSettings.bind(null, configuration, true), default_unauthenticated_manifests: readAndStoreConfigurations.bind(null, adminExtSettings.unauthenticated_manifests || [], 'unauthenticated'), }); } if (reload === 'navigation' || reload === true || !Object.keys(navigationSettings).length) { operations = Object.assign(operations, { navigation: pullNavigationSettings.bind(null, configuration), default_navigation: readAndStoreConfigurations.bind(null, adminExtSettings.navigation || [], 'navigation'), }); } return Promisie.parallel(operations); }) .then(sanitizeConfigurations) .then(finalizeSettingsWithTheme) .then(result => { let { manifest, navigation, unauthenticated_manifest, } = result; // const util = require('util'); // console.log(util.inspect(navigation,{depth:20 })); manifestSettings = Object.assign(manifestSettings, (reload === 'manifest' || reload === true || !Object.keys(manifestSettings).length) ? manifest : manifestSettings); navigationSettings = Object.assign(navigationSettings, (reload === 'navigation' || reload === true || !Object.keys(navigationSettings).length) ? navigation : navigationSettings); unauthenticatedManifestSettings = Object.assign(unauthenticatedManifestSettings, (reload === 'unauthenticated' || reload === true || !Object.keys(unauthenticatedManifestSettings).length) ? unauthenticated_manifest : unauthenticatedManifestSettings); return result; }) .catch(e => Promisie.reject(e)); }
function pullConfigurationSettings(reload) { if (Object.keys(manifestSettings).length && Object.keys(navigationSettings).length && Object.keys(unauthenticatedManifestSettings).length && !reload) return Promisie.resolve({ manifest: manifestSettings, navigation: navigationSettings, unauthenticated: unauthenticatedManifestSettings, }); return Promisie.all( [ Promise.resolve({ extensions:Array.from(periodic.extensions.values()).filter(ext => ext.periodic_config && ext.periodic_config.periodicjs_ext_reactapp), }), // fs.readJson(path.join(__dirname, '../../../content/config/extensions.json')), handleAmbiguousExtensionType(path.join(__dirname, '../periodicjs.reactapp.json')), ] ) .then(configurationData => { let [configuration, adminExtSettings, ] = configurationData; adminExtSettings = adminExtSettings['periodicjs_ext_reactapp']; if (periodic.settings.extensions[ 'periodicjs.ext.reactapp' ].default_manifests.include_default_manifests === false) { adminExtSettings.manifests = []; adminExtSettings.unauthenticated = []; } let operations = {}; if (reload === 'manifest' || reload === true || !Object.keys(manifestSettings).length) { operations = Object.assign(operations, { manifests: pullManifestSettings.bind(null, configuration), default_manifests: readAndStoreConfigurations.bind(null, adminExtSettings.manifests || [], 'manifest'), }); } if (reload === 'unauthenticated' || reload === true || !Object.keys(unauthenticatedManifestSettings).length) { operations = Object.assign(operations, { unauthenticated_manifests: pullManifestSettings.bind(null, configuration, true), default_unauthenticated_manifests: readAndStoreConfigurations.bind(null, adminExtSettings.unauthenticated_manifests || [], 'unauthenticated'), }); } if (reload === 'navigation' || reload === true || !Object.keys(navigationSettings).length) { operations = Object.assign(operations, { navigation: pullNavigationSettings.bind(null, configuration), default_navigation: readAndStoreConfigurations.bind(null, adminExtSettings.navigation || [], 'navigation'), }); } return Promisie.parallel(operations); }) .then(sanitizeConfigurations) .then(finalizeSettingsWithTheme) .then(result => { let { manifest, navigation, unauthenticated_manifest, } = result; // const util = require('util'); // console.log(util.inspect(navigation,{depth:20 })); manifestSettings = Object.assign(manifestSettings, (reload === 'manifest' || reload === true || !Object.keys(manifestSettings).length) ? manifest : manifestSettings); navigationSettings = Object.assign(navigationSettings, (reload === 'navigation' || reload === true || !Object.keys(navigationSettings).length) ? navigation : navigationSettings); unauthenticatedManifestSettings = Object.assign(unauthenticatedManifestSettings, (reload === 'unauthenticated' || reload === true || !Object.keys(unauthenticatedManifestSettings).length) ? unauthenticated_manifest : unauthenticatedManifestSettings); return result; }) .catch(e => Promisie.reject(e)); }
JavaScript
function readConfigurations(originalFilePath, configurationType) { const filePath = path.join(periodic.config.app_root, originalFilePath); let _import = function(_path) { if (path.extname(_path) !== '.js' && path.extname(_path) !== '.json') { return undefined; } if (extsettings.hot_reload) { if (path.extname(_path) === '.js') return reloader(_path, handleConfigurationReload(configurationType), periodic); else return reloader(_path, handleConfigurationReload(configurationType)); } if (path.extname(_path) !== '.js') { return fs.readJson(_path); } else { let requiredFile = require(_path); requiredFile = (typeof requiredFile === 'function') ? requiredFile(periodic) : requiredFile; return Promisie.resolve(requiredFile); } }; return fs.stat(filePath) .then(stats => { if (stats.isFile()) return _import(filePath); else if (stats.isDirectory()) { return fs.readdir(filePath) .then(files => { if (files.length) { return Promisie.map(files, file => { let fullPath = path.join(filePath, file); return _import(fullPath); }); } return []; }) .catch(e => Promisie.reject(e)); } else return Promisie.reject(new TypeError('Configuration path is not a file or directory')); }) .catch(e => Promisie.reject(e)); }
function readConfigurations(originalFilePath, configurationType) { const filePath = path.join(periodic.config.app_root, originalFilePath); let _import = function(_path) { if (path.extname(_path) !== '.js' && path.extname(_path) !== '.json') { return undefined; } if (extsettings.hot_reload) { if (path.extname(_path) === '.js') return reloader(_path, handleConfigurationReload(configurationType), periodic); else return reloader(_path, handleConfigurationReload(configurationType)); } if (path.extname(_path) !== '.js') { return fs.readJson(_path); } else { let requiredFile = require(_path); requiredFile = (typeof requiredFile === 'function') ? requiredFile(periodic) : requiredFile; return Promisie.resolve(requiredFile); } }; return fs.stat(filePath) .then(stats => { if (stats.isFile()) return _import(filePath); else if (stats.isDirectory()) { return fs.readdir(filePath) .then(files => { if (files.length) { return Promisie.map(files, file => { let fullPath = path.join(filePath, file); return _import(fullPath); }); } return []; }) .catch(e => Promisie.reject(e)); } else return Promisie.reject(new TypeError('Configuration path is not a file or directory')); }) .catch(e => Promisie.reject(e)); }
JavaScript
function readAndStoreConfigurations(paths, type) { paths = (Array.isArray(paths)) ? paths : [paths, ]; // console.log({ paths }); let reads = paths.map(_path => { if (typeof _path === 'string') return readConfigurations.bind(null, _path, type); if (typeof _path === 'function') return _path; return () => Promisie.reject(new Error('No path specified')); }); return Promisie.settle(reads) .then(result => { if (result.rejected.length) logger.error('Invalid Manifest', result.rejected, result.rejected); let { fulfilled, } = result; fulfilled = fulfilled.map(data => data.value); let flatten = function(result, data) { if (Array.isArray(data)) return result.concat(data.reduce(flatten, [])); if (data) result.push(data); return result; }; return fulfilled.reduce(flatten, []); }) .catch(e => Promisie.reject(e)); }
function readAndStoreConfigurations(paths, type) { paths = (Array.isArray(paths)) ? paths : [paths, ]; // console.log({ paths }); let reads = paths.map(_path => { if (typeof _path === 'string') return readConfigurations.bind(null, _path, type); if (typeof _path === 'function') return _path; return () => Promisie.reject(new Error('No path specified')); }); return Promisie.settle(reads) .then(result => { if (result.rejected.length) logger.error('Invalid Manifest', result.rejected, result.rejected); let { fulfilled, } = result; fulfilled = fulfilled.map(data => data.value); let flatten = function(result, data) { if (Array.isArray(data)) return result.concat(data.reduce(flatten, [])); if (data) result.push(data); return result; }; return fulfilled.reduce(flatten, []); }) .catch(e => Promisie.reject(e)); }
JavaScript
function generateComponentOperations(data, defaults) { return Object.keys(data).reduce((result, key) => { if (typeof data[key] === 'string') { result[key] = function() { return readAndStoreConfigurations([data[key], ], 'components') .then(result => { if (result.length) return result[0]; return Promisie.reject('unable to read property resetting to default value'); }) .catch(() => (defaults && defaults[key]) ? defaults[key] : undefined); }; } else if (typeof data[key] === 'object') result[key] = Promisie.parallel.bind(Promisie, generateComponentOperations(data[key], (defaults) ? defaults[key] : undefined)); else result[key] = () => Promisie.resolve(data[key]); return result; }, {}); }
function generateComponentOperations(data, defaults) { return Object.keys(data).reduce((result, key) => { if (typeof data[key] === 'string') { result[key] = function() { return readAndStoreConfigurations([data[key], ], 'components') .then(result => { if (result.length) return result[0]; return Promisie.reject('unable to read property resetting to default value'); }) .catch(() => (defaults && defaults[key]) ? defaults[key] : undefined); }; } else if (typeof data[key] === 'object') result[key] = Promisie.parallel.bind(Promisie, generateComponentOperations(data[key], (defaults) ? defaults[key] : undefined)); else result[key] = () => Promisie.resolve(data[key]); return result; }, {}); }
JavaScript
function assignComponentStatus(component) { if (component && component.layout) { if (typeof component.status === 'undefined' || (component.status !== 'undefined' && component.status !== 'uninitialized')) component.status = 'active'; } else if (component && typeof component === 'object') { component = Object.keys(component).reduce((result, key) => { result[key] = assignComponentStatus(component[key]); return result; }, {}); } return component; }
function assignComponentStatus(component) { if (component && component.layout) { if (typeof component.status === 'undefined' || (component.status !== 'undefined' && component.status !== 'uninitialized')) component.status = 'active'; } else if (component && typeof component === 'object') { component = Object.keys(component).reduce((result, key) => { result[key] = assignComponentStatus(component[key]); return result; }, {}); } return component; }
JavaScript
function handleNavigationCompilation(navigation, isExtension) { // const util = require('util'); // console.log(util.inspect(navigation,{depth:20 })); // console.log({ isExtension}) let extensionsNav = [{ component: 'MenuLabel', children: 'Extensions', }, { component: 'MenuList', children: [], }, ]; let subLinks = extensionsNav[1]; let compiled = navigation.reduce((result, nav) => { result.wrapper = Object.assign(result.wrapper || {}, nav.wrapper); result.container = Object.assign(result.container || {}, nav.container); result.layout = result.layout || { children: [], }; if (!isExtension) result.layout = Object.assign(result.layout, nav.layout, { children: result.layout.children.concat(nav.layout.children), }); else subLinks.children = subLinks.children.concat(nav.layout.children); return result; }, {}); if (subLinks.children.length) compiled.layout.children = compiled.layout.children.concat(extensionsNav); return compiled; }
function handleNavigationCompilation(navigation, isExtension) { // const util = require('util'); // console.log(util.inspect(navigation,{depth:20 })); // console.log({ isExtension}) let extensionsNav = [{ component: 'MenuLabel', children: 'Extensions', }, { component: 'MenuList', children: [], }, ]; let subLinks = extensionsNav[1]; let compiled = navigation.reduce((result, nav) => { result.wrapper = Object.assign(result.wrapper || {}, nav.wrapper); result.container = Object.assign(result.container || {}, nav.container); result.layout = result.layout || { children: [], }; if (!isExtension) result.layout = Object.assign(result.layout, nav.layout, { children: result.layout.children.concat(nav.layout.children), }); else subLinks.children = subLinks.children.concat(nav.layout.children); return result; }, {}); if (subLinks.children.length) compiled.layout.children = compiled.layout.children.concat(extensionsNav); return compiled; }
JavaScript
function pullNavigationSettings(configuration) { let extensions = configuration.extensions || []; let filePaths = extensions.reduce((result, config) => { if (config.enabled && config.periodic_config && config.periodic_config['periodicjs_ext_reactapp'] && config.periodic_config['periodicjs_ext_reactapp'].navigation) result.push(config.periodic_config['periodicjs_ext_reactapp'].navigation); return result; }, []); return readAndStoreConfigurations(filePaths || [], 'navigation') .then(result => handleNavigationCompilation(result, true)) .catch(e => Promisie.reject(e)); }
function pullNavigationSettings(configuration) { let extensions = configuration.extensions || []; let filePaths = extensions.reduce((result, config) => { if (config.enabled && config.periodic_config && config.periodic_config['periodicjs_ext_reactapp'] && config.periodic_config['periodicjs_ext_reactapp'].navigation) result.push(config.periodic_config['periodicjs_ext_reactapp'].navigation); return result; }, []); return readAndStoreConfigurations(filePaths || [], 'navigation') .then(result => handleNavigationCompilation(result, true)) .catch(e => Promisie.reject(e)); }
JavaScript
function sanitizeConfigurations(data) { return Object.keys(data).reduce((result, key) => { if (key === 'default_manifests' || key === 'default_unauthenticated_manifests') result[key] = handleManifestCompilation(data[key]); else if (key === 'default_navigation') result[key] = handleNavigationCompilation(data[key]); else result[key] = data[key]; return result; }, {}); }
function sanitizeConfigurations(data) { return Object.keys(data).reduce((result, key) => { if (key === 'default_manifests' || key === 'default_unauthenticated_manifests') result[key] = handleManifestCompilation(data[key]); else if (key === 'default_navigation') result[key] = handleNavigationCompilation(data[key]); else result[key] = data[key]; return result; }, {}); }
JavaScript
function determineAccess(privileges, layout) { try { if (!privileges.length && ( !layout || !layout.privileges || !layout.privileges.length)) { return true; } let hasAccess = false; if (!layout.privileges) hasAccess = true; else { if (privileges.length) { for (let i = 0; i < privileges.length; i++) { hasAccess = (layout.privileges.indexOf(privileges[i]) !== -1); if (hasAccess) break; } } } return hasAccess; } catch (e) { console.log('ERROR', { privileges, layout ,}); throw e; } }
function determineAccess(privileges, layout) { try { if (!privileges.length && ( !layout || !layout.privileges || !layout.privileges.length)) { return true; } let hasAccess = false; if (!layout.privileges) hasAccess = true; else { if (privileges.length) { for (let i = 0; i < privileges.length; i++) { hasAccess = (layout.privileges.indexOf(privileges[i]) !== -1); if (hasAccess) break; } } } return hasAccess; } catch (e) { console.log('ERROR', { privileges, layout ,}); throw e; } }
JavaScript
function removeNullIndexes(data) { let index = data.indexOf(null); while (index > -1) { data.splice(index, 1); index = data.indexOf(null); } return data; }
function removeNullIndexes(data) { let index = data.indexOf(null); while (index > -1) { data.splice(index, 1); index = data.indexOf(null); } return data; }
JavaScript
function recursivePrivilegesFilter(privileges = {}, config = {}, isRoot = false) { privileges = (Array.isArray(privileges)) ? privileges : []; return Object.keys(config).reduce((result, key) => { let layout = (isRoot) ? config[key].layout : config[key]; let hasAccess = determineAccess(privileges, layout); if (hasAccess && layout) { result[key] = config[key]; if (Array.isArray(layout.children) && layout.children.length) result[key].children = recursivePrivilegesFilter(privileges, result[key].children); } return (Array.isArray(result)) ? removeNullIndexes(result) : result; }, (Array.isArray(config)) ? [] : {}); }
function recursivePrivilegesFilter(privileges = {}, config = {}, isRoot = false) { privileges = (Array.isArray(privileges)) ? privileges : []; return Object.keys(config).reduce((result, key) => { let layout = (isRoot) ? config[key].layout : config[key]; let hasAccess = determineAccess(privileges, layout); if (hasAccess && layout) { result[key] = config[key]; if (Array.isArray(layout.children) && layout.children.length) result[key].children = recursivePrivilegesFilter(privileges, result[key].children); } return (Array.isArray(result)) ? removeNullIndexes(result) : result; }, (Array.isArray(config)) ? [] : {}); }
JavaScript
function execCodeAction(button, editor) { if(button.classList.contains('active')) { // show visuell view visuellView.innerHTML = htmlView.value; htmlView.style.display = 'none'; visuellView.style.display = 'block'; button.classList.remove('active'); } else { // show html view htmlView.innerText = visuellView.innerHTML; visuellView.style.display = 'none'; htmlView.style.display = 'block'; button.classList.add('active'); } }
function execCodeAction(button, editor) { if(button.classList.contains('active')) { // show visuell view visuellView.innerHTML = htmlView.value; htmlView.style.display = 'none'; visuellView.style.display = 'block'; button.classList.remove('active'); } else { // show html view htmlView.innerText = visuellView.innerHTML; visuellView.style.display = 'none'; htmlView.style.display = 'block'; button.classList.add('active'); } }
JavaScript
function execLinkAction() { modal.style.display = 'block'; let selection = saveSelection(); let submit = modal.querySelectorAll('button.done')[0]; let close = modal.querySelectorAll('.close')[0]; // done button active => add link submit.addEventListener('click', function(e) { e.preventDefault(); let newTabCheckbox = modal.querySelectorAll('#new-tab')[0]; let linkInput = modal.querySelectorAll('#linkValue')[0]; let linkValue = linkInput.value; let newTab = newTabCheckbox.checked; restoreSelection(selection); if(window.getSelection().toString()) { let a = document.createElement('a'); a.href = linkValue; if(newTab) a.target = '_blank'; window.getSelection().getRangeAt(0).surroundContents(a); } modal.style.display = 'none'; linkInput.value = ''; // deregister modal events submit.removeEventListener('click', arguments.callee); close.removeEventListener('click', arguments.callee); }); // close modal on X click close.addEventListener('click', function(e) { e.preventDefault(); let linkInput = modal.querySelectorAll('#linkValue')[0]; modal.style.display = 'none'; linkInput.value = ''; // deregister modal events submit.removeEventListener('click', arguments.callee); close.removeEventListener('click', arguments.callee); }); }
function execLinkAction() { modal.style.display = 'block'; let selection = saveSelection(); let submit = modal.querySelectorAll('button.done')[0]; let close = modal.querySelectorAll('.close')[0]; // done button active => add link submit.addEventListener('click', function(e) { e.preventDefault(); let newTabCheckbox = modal.querySelectorAll('#new-tab')[0]; let linkInput = modal.querySelectorAll('#linkValue')[0]; let linkValue = linkInput.value; let newTab = newTabCheckbox.checked; restoreSelection(selection); if(window.getSelection().toString()) { let a = document.createElement('a'); a.href = linkValue; if(newTab) a.target = '_blank'; window.getSelection().getRangeAt(0).surroundContents(a); } modal.style.display = 'none'; linkInput.value = ''; // deregister modal events submit.removeEventListener('click', arguments.callee); close.removeEventListener('click', arguments.callee); }); // close modal on X click close.addEventListener('click', function(e) { e.preventDefault(); let linkInput = modal.querySelectorAll('#linkValue')[0]; modal.style.display = 'none'; linkInput.value = ''; // deregister modal events submit.removeEventListener('click', arguments.callee); close.removeEventListener('click', arguments.callee); }); }
JavaScript
function selectionChange(e) { for(let i = 0; i < buttons.length; i++) { let button = buttons[i]; // don't remove active class on code toggle button if(button.dataset.action === 'toggle-view') continue; button.classList.remove('active'); } if(!childOf(window.getSelection().anchorNode.parentNode, editor)) return false; parentTagActive(window.getSelection().anchorNode.parentNode); }
function selectionChange(e) { for(let i = 0; i < buttons.length; i++) { let button = buttons[i]; // don't remove active class on code toggle button if(button.dataset.action === 'toggle-view') continue; button.classList.remove('active'); } if(!childOf(window.getSelection().anchorNode.parentNode, editor)) return false; parentTagActive(window.getSelection().anchorNode.parentNode); }
JavaScript
function parentTagActive(elem) { if(!elem ||!elem.classList || elem.classList.contains('visuell-view')) return false; let toolbarButton; // active by tag names let tagName = elem.tagName.toLowerCase(); toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-tag-name="${tagName}"]`)[0]; if(toolbarButton) { toolbarButton.classList.add('active'); } // active by text-align let textAlign = elem.style.textAlign; toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-style="textAlign:${textAlign}"]`)[0]; if(toolbarButton) { toolbarButton.classList.add('active'); } return parentTagActive(elem.parentNode); }
function parentTagActive(elem) { if(!elem ||!elem.classList || elem.classList.contains('visuell-view')) return false; let toolbarButton; // active by tag names let tagName = elem.tagName.toLowerCase(); toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-tag-name="${tagName}"]`)[0]; if(toolbarButton) { toolbarButton.classList.add('active'); } // active by text-align let textAlign = elem.style.textAlign; toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-style="textAlign:${textAlign}"]`)[0]; if(toolbarButton) { toolbarButton.classList.add('active'); } return parentTagActive(elem.parentNode); }
JavaScript
function pasteEvent(e) { e.preventDefault(); let text = (e.originalEvent || e).clipboardData.getData('text/plain'); document.execCommand('insertHTML', false, text); }
function pasteEvent(e) { e.preventDefault(); let text = (e.originalEvent || e).clipboardData.getData('text/plain'); document.execCommand('insertHTML', false, text); }
JavaScript
function addParagraphTag(evt) { if (evt.keyCode == '13') { // don't add a p tag on list item if(window.getSelection().anchorNode.parentNode.tagName === 'LI') return; document.execCommand('formatBlock', false, 'p'); } }
function addParagraphTag(evt) { if (evt.keyCode == '13') { // don't add a p tag on list item if(window.getSelection().anchorNode.parentNode.tagName === 'LI') return; document.execCommand('formatBlock', false, 'p'); } }
JavaScript
function removeColAndRows(element) { var COLANDROW = ["col-2", "col-3", "col-4", "row-2", "row-3", "row-4"], i = 0; for (i = 0; i < COLANDROW.length; i++) { if (element.classList.contains(COLANDROW[i])) { element.classList.remove(COLANDROW[i]); } } }
function removeColAndRows(element) { var COLANDROW = ["col-2", "col-3", "col-4", "row-2", "row-3", "row-4"], i = 0; for (i = 0; i < COLANDROW.length; i++) { if (element.classList.contains(COLANDROW[i])) { element.classList.remove(COLANDROW[i]); } } }
JavaScript
function showNewPlayerArea() { if (newPlayerArea.classList.contains("hidden")) { newPlayerArea.classList.remove('hidden'); } playerArea.classList.add("shrunk"); }
function showNewPlayerArea() { if (newPlayerArea.classList.contains("hidden")) { newPlayerArea.classList.remove('hidden'); } playerArea.classList.add("shrunk"); }
JavaScript
function changeHealth(target, num) { var label, health, tracker, el = target.parentNode; // Move up the DOM until you reach secondRow while (!el.classList.contains("secondRow")) { el = el.parentNode; } // Find the health label label = el.querySelector(".healthArea"); // Get the current point value and add the chosen number health = parseInt(label.innerHTML); health += num; label.innerHTML = health; }
function changeHealth(target, num) { var label, health, tracker, el = target.parentNode; // Move up the DOM until you reach secondRow while (!el.classList.contains("secondRow")) { el = el.parentNode; } // Find the health label label = el.querySelector(".healthArea"); // Get the current point value and add the chosen number health = parseInt(label.innerHTML); health += num; label.innerHTML = health; }
JavaScript
function modButton(num) { var modArea = document.createElement("div"); modArea.classList.add("quick"); if (num > 0) { modArea.innerHTML = "+" + num; } else { modArea.innerHTML = num; } modArea.addEventListener("click", function (e) { e = e || window.event; changeHealth(e.target, num); }, false); return modArea; }
function modButton(num) { var modArea = document.createElement("div"); modArea.classList.add("quick"); if (num > 0) { modArea.innerHTML = "+" + num; } else { modArea.innerHTML = num; } modArea.addEventListener("click", function (e) { e = e || window.event; changeHealth(e.target, num); }, false); return modArea; }
JavaScript
function darkCheck(int) { if (int < 115) { return true; } }
function darkCheck(int) { if (int < 115) { return true; } }
JavaScript
function createColors() { var int1 = 0, int2 = 0, int3 = 0, bounce = false, i = 0, color, SPACER = 23; // 0-255, 0, 0; for (int1 = 0; int1 < 256; int1 += SPACER) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } } int1 = 0; // 0, 0-255, 0 for (int2 = SPACER; int2 < 256; int2 += SPACER) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } } int2 = 0; // 0, 0, 0-255 for (int3 = SPACER; int3 < 256; int3 += SPACER) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } } // 0-255, 0-255, 0 for (int1 = SPACER, int2 = SPACER, int3 = 0; (int1 < 255 && int2 < 255); bounce = !bounce) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (bounce) { int1 += SPACER; if (int1 > 255) { int1 = 255; } } else { int2 += SPACER; if (int2 > 255) { int2 = 255; } } } // 0, 0-255, 0-255 for (int1 = 0, int2 = SPACER, int3 = SPACER; (int2 < 255 && int3 < 255); bounce = !bounce) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (bounce) { int2 += SPACER; if (int2 > 255) { int2 = 255; } } else { int3 += SPACER; if (int3 > 255) { int3 = 255; } } } // 0-255, 0, 0-255 for (int1 = SPACER, int2 = 0, int3 = SPACER; (int1 < 255 && int3 < 255); bounce = !bounce) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (bounce) { int1 += SPACER; if (int1 > 255) { int1 = 255; } } else { int3 += SPACER; if (int3 > 255) { int3 = 255; } } } // 0-255, 0-255, 0-255 for (int1 = SPACER, int2 = SPACER, int3 = SPACER; (int2 < 255 && int3 < 255); i++) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (i === 0) { int1 += SPACER; if (int1 > 255) { int1 = 255; } } else if (i === 1) { int2 += SPACER; if (int2 > 255) { int2 = 255; } } else { int3 += SPACER; if (int3 > 255) { int3 = 255; } i = -1; } } }
function createColors() { var int1 = 0, int2 = 0, int3 = 0, bounce = false, i = 0, color, SPACER = 23; // 0-255, 0, 0; for (int1 = 0; int1 < 256; int1 += SPACER) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } } int1 = 0; // 0, 0-255, 0 for (int2 = SPACER; int2 < 256; int2 += SPACER) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } } int2 = 0; // 0, 0, 0-255 for (int3 = SPACER; int3 < 256; int3 += SPACER) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } } // 0-255, 0-255, 0 for (int1 = SPACER, int2 = SPACER, int3 = 0; (int1 < 255 && int2 < 255); bounce = !bounce) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (bounce) { int1 += SPACER; if (int1 > 255) { int1 = 255; } } else { int2 += SPACER; if (int2 > 255) { int2 = 255; } } } // 0, 0-255, 0-255 for (int1 = 0, int2 = SPACER, int3 = SPACER; (int2 < 255 && int3 < 255); bounce = !bounce) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (bounce) { int2 += SPACER; if (int2 > 255) { int2 = 255; } } else { int3 += SPACER; if (int3 > 255) { int3 = 255; } } } // 0-255, 0, 0-255 for (int1 = SPACER, int2 = 0, int3 = SPACER; (int1 < 255 && int3 < 255); bounce = !bounce) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (bounce) { int1 += SPACER; if (int1 > 255) { int1 = 255; } } else { int3 += SPACER; if (int3 > 255) { int3 = 255; } } } // 0-255, 0-255, 0-255 for (int1 = SPACER, int2 = SPACER, int3 = SPACER; (int2 < 255 && int3 < 255); i++) { color = "rgb(" + int1 + ", " + int2 + ", " + int3 + ")"; if (!darkCheck(int1+int2+int3)) { COLORS.push(color); } if (i === 0) { int1 += SPACER; if (int1 > 255) { int1 = 255; } } else if (i === 1) { int2 += SPACER; if (int2 > 255) { int2 = 255; } } else { int3 += SPACER; if (int3 > 255) { int3 = 255; } i = -1; } } }
JavaScript
function contrastText(red, green, blue) { var brightness; brightness = (red * 299) + (green * 587) + (blue * 114); brightness = brightness / 255000; // values range from 0 to 1 // anything greater than 0.5 should be bright enough for dark text if (brightness >= 0.5) { return "dark-text"; } else { return "light-text"; } }
function contrastText(red, green, blue) { var brightness; brightness = (red * 299) + (green * 587) + (blue * 114); brightness = brightness / 255000; // values range from 0 to 1 // anything greater than 0.5 should be bright enough for dark text if (brightness >= 0.5) { return "dark-text"; } else { return "light-text"; } }
JavaScript
function chooseColor(target) { var children = document.getElementById("colorPicker").children, i; for (i = 0; i < children.length; i++) { children[i].classList.remove("selected"); } target.classList.add("selected"); }
function chooseColor(target) { var children = document.getElementById("colorPicker").children, i; for (i = 0; i < children.length; i++) { children[i].classList.remove("selected"); } target.classList.add("selected"); }
JavaScript
function autoReveal(logFunction) { logger = logFunction; // If Web Components are already ready, run the handler right away. If they // are not yet ready, wait. // // see https://github.com/github/webcomponentsjs#webcomponents-loaderjs for // info about web component readiness events const polyfillPresent = window.WebComponents; const polyfillReady = polyfillPresent && window.WebComponents.ready; if (!polyfillPresent || polyfillReady) { handleWebComponentsReady(); } else { window.addEventListener("WebComponentsReady", handleWebComponentsReady); } }
function autoReveal(logFunction) { logger = logFunction; // If Web Components are already ready, run the handler right away. If they // are not yet ready, wait. // // see https://github.com/github/webcomponentsjs#webcomponents-loaderjs for // info about web component readiness events const polyfillPresent = window.WebComponents; const polyfillReady = polyfillPresent && window.WebComponents.ready; if (!polyfillPresent || polyfillReady) { handleWebComponentsReady(); } else { window.addEventListener("WebComponentsReady", handleWebComponentsReady); } }
JavaScript
static debugLog(preference = null) { if (preference !== null) { // wrap localStorage references in a try/catch; merely referencing it can // throw errors in some locked down environments try { localStorage.pfeLog = !!preference; } catch (e) { // if localStorage fails, fall back to PFElement._debugLog PFElement._debugLog = !!preference; return PFElement._debugLog; } } // @TODO the reference to _debugLog is for backwards compatibiilty and will be removed in 2.0 return localStorage.pfeLog === "true" || PFElement._debugLog; }
static debugLog(preference = null) { if (preference !== null) { // wrap localStorage references in a try/catch; merely referencing it can // throw errors in some locked down environments try { localStorage.pfeLog = !!preference; } catch (e) { // if localStorage fails, fall back to PFElement._debugLog PFElement._debugLog = !!preference; return PFElement._debugLog; } } // @TODO the reference to _debugLog is for backwards compatibiilty and will be removed in 2.0 return localStorage.pfeLog === "true" || PFElement._debugLog; }
JavaScript
static trackPerformance(preference = null) { if (preference !== null) { PFElement._trackPerformance = !!preference; } return PFElement._trackPerformance; }
static trackPerformance(preference = null) { if (preference !== null) { PFElement._trackPerformance = !!preference; } return PFElement._trackPerformance; }
JavaScript
static get PfeTypes() { return { Container: "container", Content: "content", Combo: "combo", }; }
static get PfeTypes() { return { Container: "container", Content: "content", Combo: "combo", }; }
JavaScript
static get properties() { return { pfelement: { title: "Upgraded flag", type: Boolean, default: true, observer: "_upgradeObserver", }, on: { title: "Context", description: "Describes the visual context (backgrounds).", type: String, values: ["light", "dark", "saturated"], default: (el) => el.contextVariable, observer: "_onObserver", }, context: { title: "Context hook", description: "Lets you override the system-set context.", type: String, values: ["light", "dark", "saturated"], observer: "_contextObserver", }, // @TODO: Deprecated with 1.0 oldTheme: { type: String, values: ["light", "dark", "saturated"], alias: "context", attr: "pfe-theme", }, _style: { title: "Custom styles", type: String, attr: "style", observer: "_inlineStyleObserver", }, type: { title: "Component type", type: String, values: ["container", "content", "combo"], }, }; }
static get properties() { return { pfelement: { title: "Upgraded flag", type: Boolean, default: true, observer: "_upgradeObserver", }, on: { title: "Context", description: "Describes the visual context (backgrounds).", type: String, values: ["light", "dark", "saturated"], default: (el) => el.contextVariable, observer: "_onObserver", }, context: { title: "Context hook", description: "Lets you override the system-set context.", type: String, values: ["light", "dark", "saturated"], observer: "_contextObserver", }, // @TODO: Deprecated with 1.0 oldTheme: { type: String, values: ["light", "dark", "saturated"], alias: "context", attr: "pfe-theme", }, _style: { title: "Custom styles", type: String, attr: "style", observer: "_inlineStyleObserver", }, type: { title: "Component type", type: String, values: ["container", "content", "combo"], }, }; }
JavaScript
hasSlot(name) { if (!name) { this.warn(`Please provide at least one slot name for which to search.`); return; } if (typeof name === "string") { return ( [...this.children].filter((child) => child.hasAttribute("slot") && child.getAttribute("slot") === name ).length > 0 ); } else if (Array.isArray(name)) { return name.reduce( (n) => [...this.children].filter((child) => child.hasAttribute("slot") && child.getAttribute("slot") === n ).length > 0, ); } else { this.warn( `Expected hasSlot argument to be a string or an array, but it was given: ${typeof name}.`, ); return; } }
hasSlot(name) { if (!name) { this.warn(`Please provide at least one slot name for which to search.`); return; } if (typeof name === "string") { return ( [...this.children].filter((child) => child.hasAttribute("slot") && child.getAttribute("slot") === name ).length > 0 ); } else if (Array.isArray(name)) { return name.reduce( (n) => [...this.children].filter((child) => child.hasAttribute("slot") && child.getAttribute("slot") === n ).length > 0, ); } else { this.warn( `Expected hasSlot argument to be a string or an array, but it was given: ${typeof name}.`, ); return; } }
JavaScript
contextUpdate() { // Loop over light DOM elements, find direct descendants that are components const lightEls = [...this.querySelectorAll("*")] .filter((item) => item.tagName.toLowerCase().slice(0, 4) === `${prefix}-`) // Closest will return itself or it's ancestor matching that selector .filter((item) => { // If there is no parent element, return null if (!item.parentElement) return; // Otherwise, find the closest component that's this one else { return item.parentElement.closest( `[${this._pfeClass._getCache("prop2attr").pfelement}]`, ) === this; } }); // Loop over shadow elements, find direct descendants that are components let shadowEls = [...this.shadowRoot.querySelectorAll("*")] .filter((item) => item.tagName.toLowerCase().slice(0, 4) === `${prefix}-`) // Closest will return itself or it's ancestor matching that selector .filter((item) => { // If there is a parent element and we can find another web component in the ancestor tree if ( item.parentElement && item.parentElement.closest( `[${this._pfeClass._getCache("prop2attr").pfelement}]`, ) ) { return item.parentElement.closest( `[${this._pfeClass._getCache("prop2attr").pfelement}]`, ) === this; } // Otherwise, check if the host matches this context if (item.getRootNode().host === this) return true; // If neither state is true, return false return false; }); const nestedEls = lightEls.concat(shadowEls); // If nested elements don't exist, return without processing if (nestedEls.length === 0) return; // Loop over the nested elements and reset their context nestedEls.map((child) => { if (child.resetContext) { this.log(`Update context of ${child.tagName.toLowerCase()}`); // Ask the component to recheck it's context in case it changed child.resetContext(this.on); } }); }
contextUpdate() { // Loop over light DOM elements, find direct descendants that are components const lightEls = [...this.querySelectorAll("*")] .filter((item) => item.tagName.toLowerCase().slice(0, 4) === `${prefix}-`) // Closest will return itself or it's ancestor matching that selector .filter((item) => { // If there is no parent element, return null if (!item.parentElement) return; // Otherwise, find the closest component that's this one else { return item.parentElement.closest( `[${this._pfeClass._getCache("prop2attr").pfelement}]`, ) === this; } }); // Loop over shadow elements, find direct descendants that are components let shadowEls = [...this.shadowRoot.querySelectorAll("*")] .filter((item) => item.tagName.toLowerCase().slice(0, 4) === `${prefix}-`) // Closest will return itself or it's ancestor matching that selector .filter((item) => { // If there is a parent element and we can find another web component in the ancestor tree if ( item.parentElement && item.parentElement.closest( `[${this._pfeClass._getCache("prop2attr").pfelement}]`, ) ) { return item.parentElement.closest( `[${this._pfeClass._getCache("prop2attr").pfelement}]`, ) === this; } // Otherwise, check if the host matches this context if (item.getRootNode().host === this) return true; // If neither state is true, return false return false; }); const nestedEls = lightEls.concat(shadowEls); // If nested elements don't exist, return without processing if (nestedEls.length === 0) return; // Loop over the nested elements and reset their context nestedEls.map((child) => { if (child.resetContext) { this.log(`Update context of ${child.tagName.toLowerCase()}`); // Ask the component to recheck it's context in case it changed child.resetContext(this.on); } }); }
JavaScript
connectedCallback() { this._initializeAttributeDefaults(); if (window.ShadyCSS) window.ShadyCSS.styleElement(this); // Register this instance with the pointer for the scoped class and the global context this._pfeClass.instances.push(this); PFElement.allInstances.push(this); // If the slot definition exists, set up an observer if (typeof this.slots === "object") { this._slotsObserver = new MutationObserver(() => this._initializeSlots(this.tag, this.slots) ); this._initializeSlots(this.tag, this.slots); } }
connectedCallback() { this._initializeAttributeDefaults(); if (window.ShadyCSS) window.ShadyCSS.styleElement(this); // Register this instance with the pointer for the scoped class and the global context this._pfeClass.instances.push(this); PFElement.allInstances.push(this); // If the slot definition exists, set up an observer if (typeof this.slots === "object") { this._slotsObserver = new MutationObserver(() => this._initializeSlots(this.tag, this.slots) ); this._initializeSlots(this.tag, this.slots); } }
JavaScript
disconnectedCallback() { if (this._cascadeObserver) this._cascadeObserver.disconnect(); if (this._slotsObserver) this._slotsObserver.disconnect(); // Remove this instance from the pointer const classIdx = this._pfeClass.instances.find((item) => item !== this); delete this._pfeClass.instances[classIdx]; const globalIdx = PFElement.allInstances.find((item) => item !== this); delete PFElement.allInstances[globalIdx]; }
disconnectedCallback() { if (this._cascadeObserver) this._cascadeObserver.disconnect(); if (this._slotsObserver) this._slotsObserver.disconnect(); // Remove this instance from the pointer const classIdx = this._pfeClass.instances.find((item) => item !== this); delete this._pfeClass.instances[classIdx]; const globalIdx = PFElement.allInstances.find((item) => item !== this); delete PFElement.allInstances[globalIdx]; }
JavaScript
attributeChangedCallback(attr, oldVal, newVal) { if (!this._pfeClass.allProperties) return; let propName = this._pfeClass._attr2prop(attr); const propDef = this._pfeClass.allProperties[propName]; // If the attribute that changed derives from a property definition if (propDef) { // If the property/attribute pair has an alias, copy the new value to the alias target if (propDef.alias) { const aliasedPropDef = this._pfeClass.allProperties[propDef.alias]; const aliasedAttr = this._pfeClass._prop2attr(propDef.alias); const aliasedAttrVal = this.getAttribute(aliasedAttr); if (aliasedAttrVal !== newVal) { this[propDef.alias] = this._castPropertyValue(aliasedPropDef, newVal); } } // If the property/attribute pair has an observer, fire it // Observers receive the oldValue and the newValue from the attribute changed callback if (propDef.observer) { this[propDef.observer]( this._castPropertyValue(propDef, oldVal), this._castPropertyValue(propDef, newVal), ); } // If the property/attribute pair has a cascade target, copy the attribute to the matching elements // Note: this handles the cascading of new/updated attributes if (propDef.cascade) { this._cascadeAttribute( attr, this._pfeClass._convertSelectorsToArray(propDef.cascade), ); } } }
attributeChangedCallback(attr, oldVal, newVal) { if (!this._pfeClass.allProperties) return; let propName = this._pfeClass._attr2prop(attr); const propDef = this._pfeClass.allProperties[propName]; // If the attribute that changed derives from a property definition if (propDef) { // If the property/attribute pair has an alias, copy the new value to the alias target if (propDef.alias) { const aliasedPropDef = this._pfeClass.allProperties[propDef.alias]; const aliasedAttr = this._pfeClass._prop2attr(propDef.alias); const aliasedAttrVal = this.getAttribute(aliasedAttr); if (aliasedAttrVal !== newVal) { this[propDef.alias] = this._castPropertyValue(aliasedPropDef, newVal); } } // If the property/attribute pair has an observer, fire it // Observers receive the oldValue and the newValue from the attribute changed callback if (propDef.observer) { this[propDef.observer]( this._castPropertyValue(propDef, oldVal), this._castPropertyValue(propDef, newVal), ); } // If the property/attribute pair has a cascade target, copy the attribute to the matching elements // Note: this handles the cascading of new/updated attributes if (propDef.cascade) { this._cascadeAttribute( attr, this._pfeClass._convertSelectorsToArray(propDef.cascade), ); } } }
JavaScript
emitEvent( name, { bubbles = true, cancelable = false, composed = true, detail = {} } = {}, ) { if (detail) this.log(`Custom event: ${name}`, detail); else this.log(`Custom event: ${name}`); this.dispatchEvent( new CustomEvent(name, { bubbles, cancelable, composed, detail, }), ); }
emitEvent( name, { bubbles = true, cancelable = false, composed = true, detail = {} } = {}, ) { if (detail) this.log(`Custom event: ${name}`, detail); else this.log(`Custom event: ${name}`); this.dispatchEvent( new CustomEvent(name, { bubbles, cancelable, composed, detail, }), ); }
JavaScript
cascadeProperties(nodeList) { const cascade = this._pfeClass._getCache("cascadingProperties"); if (cascade) { if (this._cascadeObserver) this._cascadeObserver.disconnect(); let selectors = Object.keys(cascade); // Find out if anything in the nodeList matches any of the observed selectors for cacading properties if (selectors) { if (nodeList) { [...nodeList].forEach((nodeItem) => { selectors.forEach((selector) => { // if this node has a match function (i.e., it's an HTMLElement, not // a text node), see if it matches the selector, otherwise drop it (like it's hot). if (nodeItem.matches && nodeItem.matches(selector)) { let attrNames = cascade[selector]; // each selector can match multiple properties/attributes, so // copy each of them attrNames.forEach((attrName) => this._copyAttribute(attrName, nodeItem) ); } }); }); } else { // If a match was found, cascade each attribute to the element const components = selectors .filter((item) => item.slice(0, prefix.length + 1) === `${prefix}-`) .map((name) => customElements.whenDefined(name)); if (components) { Promise.all(components).then(() => { this._cascadeAttributes(selectors, cascade); }); } else this._cascadeAttributes(selectors, cascade); } } if (this._rendered && this._cascadeObserver) { this._cascadeObserver.observe(this, { attributes: true, childList: true, subtree: true, }); } } }
cascadeProperties(nodeList) { const cascade = this._pfeClass._getCache("cascadingProperties"); if (cascade) { if (this._cascadeObserver) this._cascadeObserver.disconnect(); let selectors = Object.keys(cascade); // Find out if anything in the nodeList matches any of the observed selectors for cacading properties if (selectors) { if (nodeList) { [...nodeList].forEach((nodeItem) => { selectors.forEach((selector) => { // if this node has a match function (i.e., it's an HTMLElement, not // a text node), see if it matches the selector, otherwise drop it (like it's hot). if (nodeItem.matches && nodeItem.matches(selector)) { let attrNames = cascade[selector]; // each selector can match multiple properties/attributes, so // copy each of them attrNames.forEach((attrName) => this._copyAttribute(attrName, nodeItem) ); } }); }); } else { // If a match was found, cascade each attribute to the element const components = selectors .filter((item) => item.slice(0, prefix.length + 1) === `${prefix}-`) .map((name) => customElements.whenDefined(name)); if (components) { Promise.all(components).then(() => { this._cascadeAttributes(selectors, cascade); }); } else this._cascadeAttributes(selectors, cascade); } } if (this._rendered && this._cascadeObserver) { this._cascadeObserver.observe(this, { attributes: true, childList: true, subtree: true, }); } } }
JavaScript
_contextObserver(oldValue, newValue) { if (newValue && ((oldValue && oldValue !== newValue) || !oldValue)) { this.log(`Running the context observer`); this.on = newValue; this.cssVariable("context", newValue); } }
_contextObserver(oldValue, newValue) { if (newValue && ((oldValue && oldValue !== newValue) || !oldValue)) { this.log(`Running the context observer`); this.on = newValue; this.cssVariable("context", newValue); } }
JavaScript
_onObserver(oldValue, newValue) { if ((oldValue && oldValue !== newValue) || (newValue && !oldValue)) { this.log(`Context update`); // Fire an event for child components this.contextUpdate(); } }
_onObserver(oldValue, newValue) { if ((oldValue && oldValue !== newValue) || (newValue && !oldValue)) { this.log(`Context update`); // Fire an event for child components this.contextUpdate(); } }
JavaScript
_inlineStyleObserver(oldValue, newValue) { if (oldValue === newValue) return; // If there are no inline styles, a context might have been deleted, so call resetContext if (!newValue) this.resetContext(); else { this.log( `Style observer activated on ${this.tag}`, `${newValue || "null"}`, ); // Grep for context/theme const regex = /--[\w|-]*(?:context|theme):\s*(?:\"*(light|dark|saturated)\"*)/gi; let match = regex.exec(newValue); // If no match is returned, exit the observer if (!match) return; const newContext = match[1]; // If the new context value differs from the on value, update if (newContext !== this.on && !this.context) this.on = newContext; } }
_inlineStyleObserver(oldValue, newValue) { if (oldValue === newValue) return; // If there are no inline styles, a context might have been deleted, so call resetContext if (!newValue) this.resetContext(); else { this.log( `Style observer activated on ${this.tag}`, `${newValue || "null"}`, ); // Grep for context/theme const regex = /--[\w|-]*(?:context|theme):\s*(?:\"*(light|dark|saturated)\"*)/gi; let match = regex.exec(newValue); // If no match is returned, exit the observer if (!match) return; const newContext = match[1]; // If the new context value differs from the on value, update if (newContext !== this.on && !this.context) this.on = newContext; } }
JavaScript
_parseObserver(mutationsList) { // Iterate over the mutation list, look for cascade updates for (let mutation of mutationsList) { // If a new node is added, attempt to cascade attributes to it if (mutation.type === "childList" && mutation.addedNodes.length) { const nonTextNodes = [...mutation.addedNodes].filter((n) => n.nodeType !== HTMLElement.TEXT_NODE ); this.cascadeProperties(nonTextNodes); } } }
_parseObserver(mutationsList) { // Iterate over the mutation list, look for cascade updates for (let mutation of mutationsList) { // If a new node is added, attempt to cascade attributes to it if (mutation.type === "childList" && mutation.addedNodes.length) { const nonTextNodes = [...mutation.addedNodes].filter((n) => n.nodeType !== HTMLElement.TEXT_NODE ); this.cascadeProperties(nonTextNodes); } } }
JavaScript
static _validateProperties() { for (let propName in this.allProperties) { const propDef = this.allProperties[propName]; // Verify that properties conform to the allowed data types if (!isAllowedType(propDef)) { this.error( `Property "${propName}" on ${this.name} must have type String, Number, or Boolean.`, ); } // Verify the property name conforms to our naming rules if (!/^[a-z_]/.test(propName)) { this.error( `Property ${this.name}.${propName} defined, but prop names must begin with a lower-case letter or an underscore`, ); } const isFunction = typeof propDef.default === "function"; // If the default value is not the same type as defined by the property // and it's not a function (we can't validate the output of the function // on the class level), throw a warning if (propDef.default && !isValidDefaultType(propDef) && !isFunction) { this.error( `[${this.name}] The default value \`${propDef.default}\` does not match the assigned type ${propDef.type.name} for the \'${propName}\' property`, ); } } }
static _validateProperties() { for (let propName in this.allProperties) { const propDef = this.allProperties[propName]; // Verify that properties conform to the allowed data types if (!isAllowedType(propDef)) { this.error( `Property "${propName}" on ${this.name} must have type String, Number, or Boolean.`, ); } // Verify the property name conforms to our naming rules if (!/^[a-z_]/.test(propName)) { this.error( `Property ${this.name}.${propName} defined, but prop names must begin with a lower-case letter or an underscore`, ); } const isFunction = typeof propDef.default === "function"; // If the default value is not the same type as defined by the property // and it's not a function (we can't validate the output of the function // on the class level), throw a warning if (propDef.default && !isValidDefaultType(propDef) && !isFunction) { this.error( `[${this.name}] The default value \`${propDef.default}\` does not match the assigned type ${propDef.type.name} for the \'${propName}\' property`, ); } } }
JavaScript
_castPropertyValue(propDef, attrValue) { switch (propDef.type) { case Number: // map various attribute string values to their respective // desired property values return { [attrValue]: Number(attrValue), null: null, NaN: NaN, undefined: undefined, }[attrValue]; case Boolean: return attrValue !== null; case String: return { [attrValue]: attrValue, undefined: undefined, }[attrValue]; default: return attrValue; } }
_castPropertyValue(propDef, attrValue) { switch (propDef.type) { case Number: // map various attribute string values to their respective // desired property values return { [attrValue]: Number(attrValue), null: null, NaN: NaN, undefined: undefined, }[attrValue]; case Boolean: return attrValue !== null; case String: return { [attrValue]: attrValue, undefined: undefined, }[attrValue]; default: return attrValue; } }
JavaScript
_initializeSlots(tag, slots) { this.log("Validate slots..."); if (this._slotsObserver) this._slotsObserver.disconnect(); // Loop over the properties provided by the schema Object.keys(slots).forEach((slot) => { let slotObj = slots[slot]; // Only attach the information if the data provided is a schema object if (typeof slotObj === "object") { let slotExists = false; let result = []; // If it's a named slot, look for that slot definition if (slotObj.namedSlot) { // Check prefixed slots result = this.getSlot(`${tag}--${slot}`); if (result.length > 0) { slotObj.nodes = result; slotExists = true; } // Check for unprefixed slots result = this.getSlot(`${slot}`); if (result.length > 0) { slotObj.nodes = result; slotExists = true; } // If it's the default slot, look for direct children not assigned to a slot } else { result = [...this.children].filter((child) => !child.hasAttribute("slot") ); if (result.length > 0) { slotObj.nodes = result; slotExists = true; } } // If the slot exists, attach an attribute to the parent to indicate that if (slotExists) { this.setAttribute(`has_${slot}`, ""); } else { this.removeAttribute(`has_${slot}`); } } }); this.log("Slots validated."); if (this._slotsObserver) { this._slotsObserver.observe(this, { childList: true }); } }
_initializeSlots(tag, slots) { this.log("Validate slots..."); if (this._slotsObserver) this._slotsObserver.disconnect(); // Loop over the properties provided by the schema Object.keys(slots).forEach((slot) => { let slotObj = slots[slot]; // Only attach the information if the data provided is a schema object if (typeof slotObj === "object") { let slotExists = false; let result = []; // If it's a named slot, look for that slot definition if (slotObj.namedSlot) { // Check prefixed slots result = this.getSlot(`${tag}--${slot}`); if (result.length > 0) { slotObj.nodes = result; slotExists = true; } // Check for unprefixed slots result = this.getSlot(`${slot}`); if (result.length > 0) { slotObj.nodes = result; slotExists = true; } // If it's the default slot, look for direct children not assigned to a slot } else { result = [...this.children].filter((child) => !child.hasAttribute("slot") ); if (result.length > 0) { slotObj.nodes = result; slotExists = true; } } // If the slot exists, attach an attribute to the parent to indicate that if (slotExists) { this.setAttribute(`has_${slot}`, ""); } else { this.removeAttribute(`has_${slot}`); } } }); this.log("Slots validated."); if (this._slotsObserver) { this._slotsObserver.observe(this, { childList: true }); } }
JavaScript
_initializeProperties() { const properties = this._pfeClass.allProperties; let hasCascade = false; if (Object.keys(properties).length > 0) this.log(`Initialize properties`); for (let propName in properties) { const propDef = properties[propName]; // Check if the property exists, throw a warning if it does. // HTMLElements have a LOT of properties; it wouldn't be hard // to overwrite one accidentally. if (typeof this[propName] !== "undefined") { this.log( `Property "${propName}" on ${this.constructor.name} cannot be defined because the property name is reserved`, ); } else { const attrName = this._pfeClass._prop2attr(propName); if (propDef.cascade) hasCascade = true; Object.defineProperty(this, propName, { get: () => { const attrValue = this.getAttribute(attrName); return this._castPropertyValue(propDef, attrValue); }, set: (rawNewVal) => { // Assign the value to the attribute this._assignValueToAttribute(propDef, attrName, rawNewVal); return rawNewVal; }, writeable: true, enumerable: true, configurable: false, }); } } // If any of the properties has cascade, attach a new mutation observer to the component if (hasCascade) { this._cascadeObserver = new MutationObserver(this._parseObserver); } }
_initializeProperties() { const properties = this._pfeClass.allProperties; let hasCascade = false; if (Object.keys(properties).length > 0) this.log(`Initialize properties`); for (let propName in properties) { const propDef = properties[propName]; // Check if the property exists, throw a warning if it does. // HTMLElements have a LOT of properties; it wouldn't be hard // to overwrite one accidentally. if (typeof this[propName] !== "undefined") { this.log( `Property "${propName}" on ${this.constructor.name} cannot be defined because the property name is reserved`, ); } else { const attrName = this._pfeClass._prop2attr(propName); if (propDef.cascade) hasCascade = true; Object.defineProperty(this, propName, { get: () => { const attrValue = this.getAttribute(attrName); return this._castPropertyValue(propDef, attrValue); }, set: (rawNewVal) => { // Assign the value to the attribute this._assignValueToAttribute(propDef, attrName, rawNewVal); return rawNewVal; }, writeable: true, enumerable: true, configurable: false, }); } } // If any of the properties has cascade, attach a new mutation observer to the component if (hasCascade) { this._cascadeObserver = new MutationObserver(this._parseObserver); } }
JavaScript
static _convertPropNameToAttrName(propName) { const propDef = this.allProperties[propName]; if (propDef.attr) { return propDef.attr; } return propName .replace(/^_/, "") .replace(/^[A-Z]/, (l) => l.toLowerCase()) .replace(/[A-Z]/g, (l) => `-${l.toLowerCase()}`); }
static _convertPropNameToAttrName(propName) { const propDef = this.allProperties[propName]; if (propDef.attr) { return propDef.attr; } return propName .replace(/^_/, "") .replace(/^[A-Z]/, (l) => l.toLowerCase()) .replace(/[A-Z]/g, (l) => `-${l.toLowerCase()}`); }