Calculate the height of the visible part of a flex item (regardless of its content)

I’m trying to zoom children of a container to make it fit the container’s height. The container is a flexbox item and may share the available space with other elements, i.e. a heading.

My problem is that I don’t know how to examine the visible height of a flex item, minus the height of siblings:

screenshot

I have created a codepen example here:

https://codepen.io/jmuheim/pen/GgRBMbZ

In the end, all cards should have the same height (so the first two cards’ contents need to shrink even more).

I played around with scrollHeight, clientHeight, offsetHeight, getBoundingClientRect().height, but didn’t succeed.

tracing settimeout warnings in angular with zone.js

I wrote a library for a third party component provider, which basically adds some new features to one of it’s components. Everything was fine, performance was fine, all OK. All was written with the default change detection mechanism and with use of zone.js.

Now, I updated both Angular and the third party component to the latest, and I get console warnings like [Violation] 'setTimeout' handler took 537ms and [Violation] Forced reflow while executing JavaScript took 222ms. And the page becomes noticeable slow. Before the updating I also got this kind of warnings, but the delays were like 10 to 50 ms.

Before or after updating, I didn’t add any new code to the library. The only changes were the updating to the latest versions. I guess, it must be some internal changes in the third party component.

The question is, how can I trace this warnings? I’m more interested in the setTimeout warning, but also the forced reflow could be interesting.

Thansk.

I’m Having Trouble with a Google Apps Script Array to Iterate Thru Rows

So, I’ve been teaching myself JavaScript to use with Google Sheets to make little programs to improve my life for several months now (side projects). I’m working on a randomizing Dinner Picker right now, but I’ve been stuck on this looping array for weeks now, and scouring Google and forums hasn’t yielded results yet.

This is where I am stuck. The array works with the logger portion, but nothing else. I cannot figure out what I need to replace the ??? with to get the values of certain cells in the rows, so I can check against them, and add the values of one cell into another.

// A looping function that goes down the rows, starting with row 2, and adds +1 to +5 depending on the priority of the meal.
// Stops and continues the main script once a priority is null. 
function iterateThroughRows() {
  var activePage = SpreadsheetApp.getActive().getSheetByName("Meal List");
  var data = activePage.getDataRange().getValues();

  data.forEach(function (row) { 
    Logger.log(row);
    var mealPriority = ???(row, 2).getValue(); // MEAL ( B / 2 )
    var mealSkip = ???(row, 3).getValue(); // TEMP_SKIP ( C / 3 )
    var mealPickedChance = ???(row, 4).getValue(); // PICKED_CHANCE ( D / 4 )

    console.log("Logger Row"); // DEBUGGING LOGS
    console.log("mealPriority = " + mealPriority); // DEBUGGING LOGS
    console.log("mealSkip = " + mealSkip); // DEBUGGING LOGS
    console.log("mealPickedChance = " + mealPickedChance); // DEBUGGING LOGS

    // if mealSkip == TRUE (set to FALSE and skip to the next row)
    // else mealPickedChance.setValue(mealPickedChance+mealPriority);
  });
}

I am trying to capture the values of 3 cells in each row.
One value is a bool, if it is set to TRUE, I want to change it to FALSE and them skip to the next row.
If that value is FALSE, I want to take the int value of one cell and add it into another.

(Example, if mealPriority = 5 and mealPickedChance = 4, then mealPickedChance would get updated to = 9.)
Rinse and repeat until the array finishes all rows.

So far I have tried:

  • getRange

  • getRow

  • getColumn

  • getCell

  • row

  • column

I’m pretty sure I can figure out the if and else statement and how to add the value from one cell to another. I’m just stuck on how to capture those values in the first place. Any help in the right direction would be greatly appreciated.

Regular expressions loop code, how Backtracking works?

Following the brilliant presentation of “Damian Conway” on how regular expression work, I have taken his pseudo-code and used my own example to try to understand it.

(see for reference the following 42:56) on
https://www.infoq.com/presentations/regex/

He conceptualises the 0 or more loop /X*/ as the following pseudocode

maxreps = Infinity;
loop {
    repcount = 0;
    for 1..maxreps {
        str[matchpos] == 'X' or exit for;
        matchpos++;
        repcount++;
    }
    try {
        // the rest of regex's commands here
    }
    catch Backtracking {
        maxreps = repcount - 1;
        maxreps >= 0 or throw Backtracking;
        next loop;
    }
    finally {
        exit loop;
    }
}

For that I have taken my example /X*i/ on the string deXXXixia ho
Transcribing it to Javascript

const Backtracking = new Error("Backtracking exception");

function executeRegex(str, startPos) {
    var returnState = false;


    matchPos = startPos
    while( matchPos <= str.length ) {

        maxReps = Infinity;
        while(true) {
            var repCount = 0;
            debugger;

            for (let j = 0; j < maxReps; j++ ) {
                if ( !(str[matchPos] == 'X') ) break ;
                matchPos++ ;
                repCount ++;
            } try {
                    if ( !(str[matchPos] == 'i') ) throw Backtracking ;
                    matchPos++ ;
                    returnState = true;
            } catch (e) {
                if (! (e == Backtracking)) throw e;            // Only catch Backtracking errors
                maxReps = repCount - 1;
                continue;
            } finally {
                matchPos++;
                break;
            }
        }
    }

    return returnState;                                       // Exhausting the whole string
}

console.log(executeRegex('deXXXoxia ho', 0));
//console.log(executeRegex('deXXXixia ho', 0));

Running the Node debugger with the following variables to watch

watch('startPos'); watch('matchPos'); watch('str[matchPos]'); watch('repCount'); watch('returnState')

I have an issue with the finally incrementing matchPos. Even if there is no match this will get incremented.
I know Damian didn’t add that matchPos++ after the finnally , but if I don’t add it it simply dont process the string if there is no initial Match.

Reimplementing Underscore’s _.reduce function by using the functionality of the _.each function

I’m working on problem for an upcoming bootcamp. Here’s where I’m at so far:

_.reduce = function (collection, iteratee, accumulator, context) {
if (arguments[2] !== undefined) {
    _.each(collection, function (element, key) {
      accumulator = iteratee.call(context, accumulator, element, key, collection);
    });
  } else {
    _.each(collection, function (element, key) {
      if (key === ???) {
        accumulator = collection[key];
      } else {
        accumulator = iteratee.call(context, accumulator, element, key, collection);
      }
    });
  }
  return accumulator;
};

I could write this longhand (iterating through objects || arrays manually), without using _.each. But a) that would spoil the fun and b) I get the feeling it’s possible as above. The issue is, in the instance that the accumulator argument isn’t provided as an argument, I need to iterate from the second value of the object || array, using the first value as the accumulator. But in writing the logic for this, I’m stuck on how to identify this first value, given it could be either an object property, or an array element. Hence the ??? in line 8. Hints welcome.

Cheers.

Why is my React State element being overwritten instead of replaced?

Ok I’m trying out something unique. I have a component where the state of the component is an element itself (not a simple variable or array). And this state element is directly being returned.

I realize this is not in line with the general principles of React but there is a reason why I’ve made it this way.

My component is a network of different SVG paths. Each path has a ‘d’ attribute which is undergoing changes. The state of the compoenent is an element which looks something like this:


<g className='PathNetwork'>
  <g>
    <Path d="pathCoordinates">
    <Path d="pathCoordinates">
    <Path d="pathCoordinates">
  </g>

  <g>
    <Path d="pathCoordinates">
    <Path d="pathCoordinates">
    <Path d="pathCoordinates">
  </g>
</g>

This “Pathnetwork” is the state of the component. And so when I want to update it, I end up creating a new structure similar to the one above with new “pathCoordinates” which will be assigned to the ‘d’ property. And once that new structure is created, I will insert it into the setter of the component’s state.

It seems to be working initially, but I am finding that the path network on my page is being over-drawn….the paths are being drawn, and then drawn on top of that….the paths are literally getting brighter with each second.

I’m wondering if I am updating the state correctly. Here is the relevant code. As you can see, I am procedurally creating new path objects, and inserting them into new elements, and finally when I’m doing I am trying to replace the data in the existing state with that new element. Am I doing it correctly? :

 const [pathNetwork, set_pathNetwork] = useState(createPathNetwork(props.coordinatesArr));

 //PathNetwork updating hook
    useEffect(()=>{
        if ( props.coordinatesArr.length >=1){
            updateDPropOfPaths( props.coordinatesArr) );
        }
    }, [ props.coordinatesArr]);


return(
        <g>
           {
           arrOfRayPaths != null ?
            arrOfRayPaths

            :null
           }          
         </g>
        )

function updateDPropOfPaths(freshCoordsArr){
   let compositePathsArr = pathNetwork.props.children;
   let finalStruct = React.createElement('g', {}, []);

   for (let x = 0; x < compositePathsArr .length; x++){
      let currCompRay = compositePathsArr[x];

       for(let i=0; i<freshCoordsArr.length; i++){ 
          let currTierStruct = React.createElement('g', {}, []);
          let originalIndividualPathsArr = currCompRay.props.children; 
           
           for(let c=0; c<3; c++ ){
              let currPath = originalIndividualPathsArr[c];
              let freshPath = createFreshPath(currPath, freshCoordsArr[i]);
              currTierStruct.props.children.push(freshPath);
           }
       finalStruct.props.children.push(currTierStruct);
        }
    }

      //Replacing the existing state structure with the newly created <g> element
      set_pathNetwork(null);
      set_pathNetwork(finalStruct);
 
}

Cropping text in animation by text height

I have a block with the text TEXT TEST. Here the word text should change with the help of animation. But I have a problem that during animation the text TEST goes beyond the height of the text TEXT, which should not happen. And I can’t make it so that TEST is cut off

This is how it works for me now

enter image description here

And it should be something like this

enter image description here

Help me please

$(document).ready(function() {
    let currentAnimation = true;

    function animateText() {
        if (currentAnimation) {
            $(".red").css({
                transform: "translateY(-100%)",
                opacity: 0
            });

            $(".blue").css({
                transform: "translateY(0)",
                opacity: 1
            });
        } else {
            $(".red").css({
                transform: "translateY(0)",
                opacity: 1
            });

            $(".blue").css({
                transform: "translateY(100%)",
                opacity: 0
            });
        }

        currentAnimation = !currentAnimation;

        setTimeout(() => {
            requestAnimationFrame(animateText);
        }, 2000);
    }

    requestAnimationFrame(animateText);
});
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #111;
  color: white;
  font-size: 48px;
  font-family: Arial, sans-serif;
}

.title {
  display: inline-block;
  overflow: hidden;
}

.red, .blue {
  position: absolute;
  display: inline-block;
  transition: transform 1s ease, opacity 1s ease;
}

.red {
  color: red;
}

.blue {
  color: blue;
  transform: translateY(100%);
  opacity: 0;
}
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<div class="title">TEXT<span class="red">TEST</span><span class="blue">TEST</span></div>

ViTest Mock is not replacing function

For some reason in ViTest mocks are not replacing my real function. I have a main function here

const { handler1 } = require(./path/handler1)

exports.mainFunction = async (event) => {
 try {
    const val1 = await handler1(event)
    console.log(val1)

Handler 1 looks like

exports.handler1 = async (data) => { return "real" }

I am trying to write unit tests for mainFunction where I can mock the response from handler1 (Handler1 already has its own unit tests)

import { handler1} from '../path/handler1.js';
vi.mock('../path/handler1.js');

describe('mainFunction()', function () {
  it("should return fake")  async function () {
    let handlerMock = {
      handler1: () => "Fake",
    };
    handler1.mockResolvedValue(handlerMock);
    await mainFunction("event")
    // mainFunction is outputting real and not fake

  }
}

How to fix vscode replacing words on the right

How to disable vsocde replacing a word next to the right when I hit enter.

A code for example: doSomething(), if go to the back of that function and type functionName and hit enter it replaces the doSomething to functionName().

I’ve tried the insertMode but it’s already in insert by default. I’ve also tried other stuff but nothing works. I need the suggestions when typing but I don’t want it to replace next word, thanks. Sorry for my English.

Swiper component won’t center the slide if freeMode is activated

I have a swiper that contains multiple slides (they don’t fit entirely on screen). I need the Swiper to have freeMode set to true so that on mobile the slides keep scrolling after touchEnd.
My problem is that even by using “sticky: true” inside freeMode{} the swiper won’t center the nearest slide to the center of the screen after the swiper stopped moving.

This is the code

 <Swiper
        slidesPerView={5}
        centeredSlides={true}
        // onSlideChangeTransitionEnd={onSlideChange}
        modules={[Navigation, Pagination, Scrollbar, A11y]}
        spaceBetween={0}
        navigation
        pagination={{ clickable: true }}
        scrollbar={{ draggable: true }}
        className={styles.swiper}
        touchRatio={1.5}
        longSwipes={true}
        grabCursor={true}
        cssMode={true}
        slideActiveClass={styles.selectedSlide}
        freeMode={{
          enabled: true,
          momentumBounce: true,
          sticky: true,
        }}
      >
        {slides}
      </Swiper>

(Three.js) How do I get the eyes to correctly follow the mouse?

I’m new to using Three.js. I want to create eye balls that follow the mouse, I managed to make them move but they don’t follow the mouse perfectly

threeJS mouse follow issue

Here is the part of the code that controls the eyes

class Eyes extends THREE.Group {
  constructor(camera) {
    super();
    this.camera = camera;

    this.plane = new THREE.Plane();
    this.planeNormal = new THREE.Vector3();
    this.planePoint = new THREE.Vector3();

    this.pointer = new THREE.Vector2();
    this.raycaster = new THREE.Raycaster();

    this.lookAt = new THREE.Vector3();

    this.clock = new THREE.Clock();

    this.blink = { value: 0 };

    this.eyes = new Array(2).fill().map((_, idx) => {
      let eye = new EyeBall();
      eye.position.set(idx < 1 ? -0.15 : 0.15, 0.025, 0.9);
      eye.scale.setScalar(0.13);
      this.add(eye);
      return eye;
    });

    document.addEventListener("pointermove", (event) => {
      this.pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
      this.pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
    });

    this.blinking();
  }

  blinking() {
    let duration = 500;
    let delay = Math.random() * 3000 + 2000;
    this.blink.value = 0;
    new TWEEN.Tween(this.blink)
      .to({ value: 1 }, duration)
      .delay(delay)
      .easing(TWEEN.Easing.Exponential.InOut)
      .onComplete(() => {
        this.blinking();
      })
      .start();
  }

  update() {
    this.raycaster.setFromCamera(this.pointer, this.camera);
    this.camera.getWorldDirection(this.planeNormal);

    const eyeWorldPosition = new THREE.Vector3();
    this.eyes[0].getWorldPosition(eyeWorldPosition);

    this.plane.setFromNormalAndCoplanarPoint(
      this.planeNormal,
      eyeWorldPosition
    );

    let tempLookAt = new THREE.Vector3();
    this.raycaster.ray.intersectPlane(this.plane, tempLookAt);
    this.lookAt.lerp(tempLookAt, 0.5);

    this.eyes.forEach((eye) => {
      eye.lookAt(this.lookAt);
    });
  }
}

I’ve tried looking up some solutions but a lot of them use regular html and js and not vite with reactJS. Also they never have the same issue I’m having.

Tools I’m using:
Vite
ReactJS
Javascript
Three.js

cookie related issue in MERN stack web app deployed on Render

I am having an issue about cookies in my mern stack project I use passport local strategy for auth and express-session for session storage and database is deployed on mongodb atlas, actually everything works correctly on the laptop but in incognito mode once I login and go to any protected route it says not authenticated and no cookie is set in application tab and in mobile phone some account works properly like I am able to login and other other operation also but I am not able to login on some accounts, so this is my problem for code base this is public GitHub Repo : https://github.com/Nikhil-Sirsat/LinkSpace

Webpack – Creating files in a sibling directory

I’m in a situation where I want to create “dist” files along a dynamic path but in a specific child directory, which is a sibling to the source directory.

My project structure ideally looks like this:

  • files/
    • directory1/
      • src/
        • index.js
      • dist/
        • index-dist.js
    • directory2/
      • src/
        • index.js
      • dist/
        • index-dist.js

What I have so far in my webpack config:

const path = require( 'path' );
const glob = require('glob');

module.exports = ( env ) => {
    return {
        entry: Object.fromEntries(glob.sync(path.resolve(__dirname, 'files/**/src/index.js')).map((v) => [ v.split('files/')[1], v, ] )),
        resolve: {
            extensions: [
                '.js',
            ],
        },
        output: {
            path: path.resolve( __dirname, 'files' ),
            filename: '[name]-dist.js',
        },
    }
};

However, this is producing:

  • files/
    • directory1/
      • src/
        • index.js <- this is my entry point
        • index.js-dist.js <- this is the output
    • directory2/
      • src/
        • index.js <- this is my entry point
        • index.js-dist.js <- this is the output

I saw there was something with [path] that could theoretically be used, but it just created a folder called “[path]” when I tried that.