How to create a scrollable/touchable grid in CSS and JS?

I’m interested in how I can make a grid with an undetermined amount of columns and rows that I can put inside another div and have it not spill into others objects or mess with the parent size.

I want it to be square and I’m using Tailwind CSS but I can adapt to SCSS or vanilla CSS. Also I want it to be touchable/moveable with a mouse on desktop and touch capable devices.

How would I go about accomplishing this?

JavaScript/AngularJS Condition to check for key in array not working

I have a piece of code that checks if a column named “agendaitem” exists, if it did not exist, then a window alert is shown.

I now have to add another check for a column named “agenda#” – the original value in the array is “Agenda #”, I added the check as shown on the code below, but the value seems to be only affected by the toLowerCase function turning it to “agenda #”, and not by the replace space with nothing function. It always goes into the alert part of the code.

Can someone be kind to show me what I am doing wrong?

Thank you in advance.

This is what I have tried:

       for (var j = 0; j < data.length; j++) {

            var xdata = data[j];

            Object.keys(xdata).map(function (columnName) {
                normalizedXData[columnName.toLowerCase().replace(" ", "")] = xdata[columnName]
            })

            if (!("agendaitem" in normalizedXData && "agenda#" in normalizedXData)) {

                window.alert("The file that you are trying to upload is not formatted correctly.n" +
                            "Make sure that the headers and data it contains meets the expected criteria.n" +
                            "Once you have verified your file is correct, please click the Upload button to try again.n" +
                            "Thank you!");

                isValid = false;                    
            }

            rowCounter++;
        }
        return isValid;

enter image description here

The close button does not close the modal

I have a modal that opens when a user clicks the ‘start here’ button, after clicking next on the first modal it goes to the next three modals automatically, then it goes to the last modal with a form. I have two “close” onclicks, one on the first modal and the other on the last modal. The problem is that the modal closes on the first one but not on the last one. I need it to close on the last one too.

My code is here:

// Get the modal
var modal = document.getElementById("myModal");
var modal2 = document.getElementById("myModal2");
var modal3 = document.getElementById("myModal3");
var modal4 = document.getElementById("myModal4");
var modal5 = document.getElementById("myModal5");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var btn2 = document.getElementById("myBtn2");
var btn3 = document.getElementById("myBtn3");
var btn4 = document.getElementById("myBtn4");
var btn5 = document.getElementById("myBtn5");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

btn2.onclick = function() {
  modal2.style.display = "block";
  setTimeout(() => {
    modal3.style.display = "block";
  }, 4500);
  setTimeout(() => {
    modal4.style.display = "block";
  }, 8500);
  setTimeout(() => {
    modal5.style.display = "block";
  }, 12900);
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
  modal2.style.display = "none";
  modal3.style.display = "none";
  modal4.style.display = "none";
  modal5.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal5) {
    modal.style.display = "none";
    modal2.style.display = "none";
    modal3.style.display = "none";
    modal4.style.display = "none";
    modal5.style.display = "none";
  }
}
.showthis {
  display: block;
  z-index: 10000 !important;
}


/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
  overflow-y: hidden;
}


/* Modal Content */

.modal-content {
  background-color: #ededed;
  margin: auto;
  padding: 0;
  border: 6px solid #d1222b;
  width: 100%;
  height: 100%;
}


/* The Close Button */

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
  padding: 25px;
  position: absolute;
  right: 0;
}

.close:hover,
.close:focus {
  color: #d1222b;
  text-decoration: none;
  cursor: pointer;
}

.mgl-row {
  display: flex;
  flex-wrap: nowrap;
}

.slide-1-img {
  height: 98.75vh;
}

.mgl-col-2 {
  align-self: center;
  margin: auto;
}

.mgl-col-2 .content {
  margin: auto;
  align-self: center;
  width: 100%;
}

.mgl-col-2 .content h2 {
  color: #d1222b;
  font-size: 54px;
  line-height: 64px;
  padding-right: 100px;
  margin-top: 50px;
}

.mgl-col-2 input {
  width: 100%;
  background: whitesmoke;
  border: 0;
  padding: 10px;
}

.mgl-col-3 {
  margin: auto;
  height: 100vh;
  margin-top: 100px;
  text-align: center;
  width: 100%;
}

.mgl-col-3 .content {
  width: 75%;
  margin: auto;
  padding-top: 100px;
}

.mgl-col-3 .content h3 {
  color: #d1222b;
  font-size: 21px;
  margin-top: 75px;
}

.mgl-col-3 .content h2 {
  color: #0a314b;
  font-size: 54px;
}

.mt-50 {
  margin-top: 50px;
}

.progress-line {
  width: 100px;
  height: 5px;
  background: white;
  margin: 0px 10px;
}

.progress-line.red-bg {
  background: #d1222b;
}

.sm-text {
  font-size: 14px;
  line-height: 21px;
  opacity: .75;
}

.j-center {
  align-items: center;
  justify-content: center;
}

.modal-btn {
  padding: 20px 25px;
  background: #d1222b;
  color: white;
  text-transform: uppercase;
  font-weight: 800;
  position: relative;
  transition: all 0.1s linear;
}

.modal-btn:hover {
  background: #3c3c3c;
  color: #fff;
}

.btn-box {
  margin-top: 25px;
  margin-bottom: 25px;
}

#myModal5 input {
  width: 35%;
  border: none;
  padding: 10px;
  margin: 10px;
}

#myModal5 .modal-content {
  background-image: url('https://www.rsisecurity.com/wp-content/uploads/2021/12/image-2.jpg');
  background-color: black;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

#myModal5 h2 {
  color: white;
}

#myModal5 h2 span {
  color: #d1222b;
}

#myModal5 p {
  color: #fff;
}

#myModal5 .btn-box {
  margin-bottom: 50px;
}

#myModal5 .rsi-logo {
  width: 100px;
}

#myBtn {
  color: black;
}

.text-left {
  text-align: left !important;
}


/* iPad Pro */

@media (min-width: 992px) and (max-width: 1199px) {
  .slide-1-img {
    height: 98.75vh;
    width: 400px;
    object-fit: cover;
  }
}


/* iPad */

@media (min-width: 760px) and (max-width: 991px) {
  .slide-1-img {
    height: 98.75vh;
    width: 300px;
    object-fit: cover;
  }
  #myModal .mgl-col-2 .content {
    margin: auto;
    align-self: center;
    width: 100%;
    padding: 0px 25px;
  }
  #myModal .mgl-col-2 .content h2 {
    font-size: 42px;
    line-height: 52px;
    padding-right: 0px;
  }
  .mgl-col-3 .content h2 {
    font-size: 36px;
  }
  #myModal5 h2 {
    font-size: 34px;
  }
}


/* Mobile Landscape */

@media (min-width: 560px) and (max-width: 759px) {}

@media screen and (min-width:992px) {}


/* Mobile */

@media only screen and (max-width: 559px) {
  .mgl-col-1 {
    display: none;
  }
  #myModal .mgl-col-2 .content h2 {
    color: #d1222b;
    font-size: 36px;
    line-height: 46px;
    padding-right: 0px;
    margin-top: 50px;
    margin-bottom: 25px;
  }
  #myModal .modal-content {
    padding-top: 50px;
  }
  .btn-box {
    margin-top: 35px;
    margin-bottom: 45px;
  }
  .mgl-col-3 .content {
    width: 75%;
    margin: auto;
    margin-top: 0;
    padding-top: 0;
  }
  .mgl-col-3 .content h2 {
    font-size: 21px;
    line-height: 28px;
    margin-bottom: 15px;
  }
  .mgl-col-3 .content h3 {
    margin-top: 25px;
    font-size: 14px;
  }
  .mt-50 {
    margin-top: 35px;
  }
  .progress-line {
    width: 50px;
    height: 3px;
  }
  .mgl-col-3 .content {
    width: 90%;
  }
  #myModal5 input {
    width: 45%;
    border: none;
    padding: 10px;
    margin: 5px;
  }
  .sm-text {
    font-size: 12px;
    line-height: 16px;
    opacity: .75;
  }
  #myModal5 h2 {
    font-size: 26px;
  }
  #myModal5 .rsi-logo {
    width: 75px;
    margin-bottom: 25px;
  }
}


/* iPhone */

@media only screen and (max-width: 375px) {}


/* Galaxy S5 */

@media only screen and (max-width: 360px) {}


/* iPhone 5 */

@media only screen and (max-width: 320px) {}


/* Galaxy Fold */

@media only screen and (max-width: 280px) {}
<div class="white-outlined-btn width-50 m-auto " id="myBtn">Start Here</div>

<!-- The Modal -->
<form>
  <div id="myModal" class="modal" style="display:none;">

    <!-- Modal content -->
    <div class="modal-content">
      <span class="close">&times;</span>
      <div class="mgl-row">
        <div class="mgl-col-1">
          <img src="https://www.rsisecurity.com/wp-content/uploads/2021/12/image.jpg" alt="free assessment" class="slide-1-img">
        </div>
        <div class="mgl-col-2">
          <div class="content">
            <img src="https://www.rsisecurity.com/wp-content/uploads/2022/03/rsi-logo.svg" alt="rsi logo" class="rsi-logo">
            <h2 class="text-left">
              Get your FREE <br> Cyber Risk Score <br> Assessment
            </h2>
            <p class="text-left">
              Enter URL Below:
            </p>

            <input type="text" class="form-control" name="Website" id="Website" placeholder="Enter URL" required="required">

            <div class="btn-box">
              <a class="modal-btn" id="myBtn2">Start Here</a>
            </div>

            <!--p class="sm-text">
                    By clicking "START HERE" you are accepting <br>
                    lorem ipsum dolor sit amet
                </p-->
          </div>
        </div>
      </div>

    </div>

  </div>

  <!-- The Modal 2 -->
  <div id="myModal2" class="modal">

    <!-- Modal content -->
    <div class="modal-content">

      <div class="mgl-row">
        <div class="mgl-col-3">
          <div class="content">
            <img src="https://www.rsisecurity.com/wp-content/uploads/2022/03/rsi-logo.svg" alt="rsi logo" class="rsi-logo">

            <h3>
              01 of 03
            </h3>
            <h2>
              Checking Network Vulnerability
            </h2>
            <!--p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
                </p-->
            <div class="mgl-row j-center mt-50">
              <div class="progress-line red-bg"></div>
              <div class="progress-line"></div>
              <div class="progress-line"></div>
            </div>
          </div>
        </div>
      </div>


    </div>

  </div>


  <!-- The Modal 3 -->
  <div id="myModal3" class="modal">

    <!-- Modal content -->
    <div class="modal-content">

      <div class="mgl-row">
        <div class="mgl-col-3">
          <div class="content">
            <img src="https://www.rsisecurity.com/wp-content/uploads/2022/03/rsi-logo.svg" alt="rsi logo" class="rsi-logo pb-0">

            <h3 class="mtop-002">
              02 of 03
            </h3>
            <h2 class="mobile-custom-9372">
              Scanning Dark Web Discovery
            </h2>
            <!--p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
                </p-->
            <div class="mgl-row j-center mt-50">
              <div class="progress-line red-bg"></div>
              <div class="progress-line red-bg"></div>
              <div class="progress-line"></div>
            </div>
          </div>
        </div>
      </div>



    </div>

  </div>


  <!-- The Modal 4 -->
  <div id="myModal4" class="modal">

    <!-- Modal content -->
    <div class="modal-content">

      <div class="mgl-row">
        <div class="mgl-col-3">
          <div class="content">
            <img src="https://www.rsisecurity.com/wp-content/uploads/2022/03/rsi-logo.svg" alt="rsi logo" class="rsi-logo">

            <h3>
              03 of 03
            </h3>
            <h2>
              Web Vulnerability & Generating IP Threat Analysis
            </h2>
            <!--p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
                </p-->
            <div class="mgl-row j-center mt-50">
              <div class="progress-line red-bg"></div>
              <div class="progress-line red-bg"></div>
              <div class="progress-line red-bg"></div>
            </div>
          </div>
        </div>
      </div>



    </div>

  </div>

  <!-- The Modal 5 -->
  <div id="myModal5" class="modal">

    <!-- Modal content -->
    <div class="modal-content">
      <span class="close">&times;</span>

      <div class="mgl-row">
        <div class="mgl-col-3" style="margin-top:0px;">
          <div class="content">
            <img src="https://www.rsisecurity.com/wp-content/uploads/2022/03/logo-white.svg" alt="rsi logo" class="rsi-logo pb-4">

            <h2>
              Generate your FREE <span>Cyber Risk Assessment</span>
            </h2>
            <p>
              Where should we send it to?
            </p>
            <input name="First Name" id="First Name" placeholder="First Name" required="required">
            <input name="Last Name" id="Last Name" placeholder="Last Name" required="required">
            <br>
            <input name="Company" id="Company" placeholder="Company" required="required">
            <input name="Title" id="Title" placeholder="Job Title" required="required">
            <br>
            <input name="email" id="email" placeholder="Email" required="required">
            <input name="Phone" id="Phone" placeholder="Phone" required="required">
            <div class="btn-box">
              <button type="submit" class="modal-btn">Send Report</button>

            </div>
            <p class="sm-text">
              After submiting this form, please allow up to 48 hours to receive your comprehensive report via email. <br> All information obtained through our website will be utilized internally and will not be sold to any 3rd party entity.
            </p>
          </div>
        </div>
      </div>



    </div>

  </div>
</form>

Loading button after full of required fields

I have a form containing email and password fields, both are required and I have this button

... -> input 
<button type="submit" 
   x-data="{ isClicked: false }" 
    @click="isClicked = true;"
    x-bind:disabled="isClicked">
    <span x-show="isClicked">
        loading ...
    </span>
    <span x-show="!isClicked" class="w-full text">
        Submit
    </span>
</button>
</form>

When I click on the button I get the loading event that is required fields

How can I make the button loading after fill of both input

pass secure file to pdf.js/viewer.html with php

I am experimenting with the pdf.js examples, and in particular the viewer.html/viewer.js. I am trying to access a URL outside of the webroot. My PHP installation has access to a specific folder outside webroot where I store pdf files. In PHP I stream these files to the browser for download, which works fine. However, I would like to also stream the file to the viewer directly. Is that possible?

So, for example, my URL would be /web/viewer.html?file=12345.pdf for a file that is accessible to the web browser.
However, if I want to stream this from outside the root, the URL may look like this: /web/viewer.html?file=fetch.php?id=12345

Any idea how I should go about this, as the viewer seems to fetch the filename directly.

One idea I explored is to create a temporary copy within webroot. Pass that file to the viewer and delete the file after a set period to ensure it was loaded. That seems awfully inefficient, so somehow passing the file directly to the viewer so it can be used without creating a temp copy seems to be a better approach, if possible. Any ideas are much appreciated.

Use a variable as a key in an object lookup JavaScript [duplicate]

I am creating a personal website using react.

I have an object containing urls to my projects that looks like this:

export const url = {
    MintableToken: 'https://...',
    SharedWallet: 'https://...',
    SupplyChain: 'https://...',
    HouseMarketplace: 'https://...',
    GithubFinder: 'https://...',
    SupportTickets: 'https://...',
    Feedback: 'https://...',
};

I then have a state variable called contents which changes based on which filters the user sets but will contain some of the above names like ‘MintableToken and Feedback’. I am mapping through content to output a list of different links to follow and would like to access the link based on which names are in my content state. I want to do something like this to fetch the link that corresponds to the project name being output by the mapping, but am not sure of the right syntax (see href):

{content.map((item, id) => ( 
                  <div className="map">
                    <a key={id} href={`url.${item}`} target='_blank' rel='noreferrer' >
                    {item}
                    </a>
                    </div>
                ))}

Any help is greatly appreciated

Javascript closure doesn’t capture var variables

(function() {
  var debounce = function(func, delay) {
    var inDebounce;
    return function() {
      var context = this;
      var args = arguments;
      clearTimeout(inDebounce);
      inDebounce = setTimeout(function() {
        func.apply(context, args);
      }, delay);
    }
  }
  var scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
  var quarterHeight = scrollHeight / 4;
  var quarters = 0;
  var scrollDistance, divisible, percent;
  document.addEventListener("scroll", debounce(function() {
    scrollDistance = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
    divisible = Math.trunc(scrollDistance / quarterHeight);
    if (quarters < divisible) {
      scrollPercent = divisible * 25;
      heap.track('Scroll Depth', {
        percent: scrollPercent
      });
      quarters++;
    }
  }, 100));
}());

Inside the event listender, scrollHeight is always 0 when I do a console print out. Why is that? I tested it in Chrome. It’s as if the closure is not capturing scrollHeight.

When I move the line inside the closure, it works.

creating functionality for element to stop “setInterval” function (triggered by another element)

I have created an automatic slideshow – which starts after clicking “menu item”. I’m looking for a way to “turn it off”, when clicking different “menu item”. The whole problem can be abstracted to a simple example:

Constructing functionality for “stop” <li> (that would probably utilize stopInterval). I can’t come up with a solution, would anyone have an idea ?

const li1 = document.getElementById("li1")

li1.addEventListener("click", slideShowAbstract)

function slideShowAbstract(e) {

    const y = setInterval(()=> console.log("playing"), 2000)

    }
ul {
    display: flex;
    justify-content: center;
    list-style-type: none;
  }
  
li {
    margin: 1rem;
}

li:hover {
    cursor: pointer;
}
            <ul>
                <li id="li1">play</li>
                <li id="li2">stop</li>
            </ul>

change all the elements of my array repeating the last one I added

when I try to add the new element to the array it changes the rest of the elements by repeating the last one I added
I’m learning to program in java script and I found this error not because it occurs can someone explain it to me


input=`^>v<`
input=input.split("")
var coordinates=[0,0]
var positions=[]
y=0
v=0

for (x in input){
    v+=1
    x=input[x]
  
    
     if (x=="^"){
        coordinates[1]+=1
     }
     if (x=="v"){
        coordinates[1]-=1
     }  
     if (x==">"){
        coordinates[0]+=1
     }
     if (x=="<"){
        coordinates[0]-=1
     }
    boolean=positions.indexOf(coordinates)
    positions.push(coordinates)
    console.log(coordinates)
      }
   
    
     
     
    console.log(positions)

output


[ [ 0, 1 ] ]
[ [ 1, 1 ], [ 1, 1 ] ]
[ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ] ]
[ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
[ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]

Class type does not support classes with static methods

I tried to map classes to strings. Something like:

this.add(ClassName, 'my string');

for this I created a custom type:

type NoConstructor<T> = Pick<T, keyof T>;

this works as long as a class has no static methods. As soon as a class has static methods, I get an error by TypeScript:

Argument of type ‘Function’ is not assignable to parameter of type ‘NoConstructor’.
Type ‘Function’ is missing the following properties from type ‘NoConstructor’: getInputs, getOutputs

Why do static methods on the class influence my custom type? To me this doesn’t make sense. Can anyone elaborate why this is the case and how to fix this code example.

Example on typescriptlang.org/play:

export abstract class Device {
    public getStatus(): string {
        return 'foo';
    }

    public static getInputs(): {[key: string]: number} {
        return {};
    }

    public static getOutputs(): {[key: string]: number} {
        return {};
    }
}

class DeviceA extends Device {

}

type NoConstructor<T> = Pick<T, keyof T>;

export default class DeviceUpdater
{
    private readonly map: Map<NoConstructor<typeof Device>, string> = new Map();

    public add(deviceType: NoConstructor<typeof Device>, updater: string) {
        this.map.set(deviceType, updater);
    }

    public update(device: Device): void {
        const result = this.map.get(device.constructor);
        if (result === undefined) {
            throw new Error(`Cannot update device of type '${device.constructor.name}': no updater found`);
        }

        console.log(result);
    }
}

const deviceUpdater = new DeviceUpdater();

deviceUpdater.add(DeviceA, 'something');

deviceUpdater.update(new DeviceA());

Generating a unique className from a uuid?

50bdc59e-394c-449b-9808-5a912aa9b202, this is a uuid I tried to use as a className, but it didn’t work, so I tried uuid.slice(20) and it worked, I don’t know what are the restrictions for classNames, but it’s not the dash, because upon doing slice(20) I noticed there was still a dash in the result, but now I am wondering if there’s a short method for generating a unique className from a uuid. Now, if there’s no solution that’s robust, I thought about splitting the uuid into two and inject a className prefix and suffix, but I want to avoid that at all cost.

Jest Store is Mocked — Not detecting it?

I have some code I’ve pulled from another project I had done. I am moving the store here and passing the App as a child component.

Unfortunately I receive this error. I’m not sure why this doesn’t work.

could not find react-redux context value; please ensure the component is wrapped in a <Provider>

      29 |
      30 | function App() {
    > 31 |   const { userData } = useSelector(state => state.user)

utils.js

import { Provider } from 'react-redux'
import store from "../redux/store"

const ReduxProvider = ({ children }) => (
    <Provider store={store}>{children}</Provider>
)

export {
    ReduxProvider
}

App.test.js

import { render } from '@testing-library/react';

import { ReduxProvider } from './utils'
import App from '../App';

test('renders', () => {
  render(
    <ReduxProvider>
      <App />
    </ReduxProvider>
  );
});

window addEventListener keydown not firing

I’m making the 2048 game, but the window.addEventListener(“keydown”, handleInput, {once:true}); does not firing. But if I console.log(e.key), I get the message that I pressed the button, but the tile does not move. Can anyone help?

This is the index.js file that containsthe eventlistener.

import Grid from "./grid.js";
import Tile from "./tile.js";

const gameBoard = document.getElementById('game-board');
const grid = new Grid(gameBoard);

grid.randomEmptyCell().tile = new Tile(gameBoard);
grid.randomEmptyCell().tile = new Tile(gameBoard);
setupInput();

function setupInput() {
  window.addEventListener("keydown", handleInput, { once: true });
}

async function handleInput(e) {
  console.log(e.key);
  switch (e.keyCode) {
    case "ArrowUp":
      if(!canMoveUp()) {
        setupInput();
        return;
      }
      await moveUp()
      break
    case "ArrowDown":
      if(!canMoveDown()) {
        setupInput();
        return;
      }
      await moveDown()
      break
    case "ArrowLeft":
      if(!canMoveLeft()) {
        setupInput();
        return;
      }
      await moveLeft()
      break
    case "ArrowRight":
      if(!canMoveRight()) {
        setupInput();
        return;
      }
      await moveRight()
      break
    default:
      setupInput()
      return
  }

  grid.cells.forEach(cell => cell.merTiles());

  const newTile = new Tile(gameBoard);

  grid.randomEmptyCell().tile = newTile;

  if (!canMoveUp() && !canMoveDown() && !canMoveLeft() && !canMoveRight()) {
    newTile.waitForTransition(true).then(() => {
      alert("You lose!");
    });
  } return
  setupInput();
}

function moveUp() {
  return slideTiles(grid.cellsByColumn);
}

function moveDown() {
  return slideTiles(grid.cellsByColumn.map(column => [...column].reverse()));
}

function moveLeft() {
  return slideTiles(grid.cellsByRow);
}

function moveRight() {
  return slideTiles(grid.cellsByRow.map(row => [...row].reverse()));
}

function slideTiles(cells) {
  return Promise.all(
  cells.flatMap(group => {
    const promises = [];
    for (let i = 1; i < group.length; i++) {
      const cell = group[i];
      if (cell.tile == null) continue;
      let lastValidCell;
      for (let j = i - 1; j >= 0; j--) {
        const moveToCell = group[j];
        if (!moveToCell.canAccept(cell.tile)) break;
        lastValidCell = moveToCell;
      }
      if (lastValidCell != null) {
        promises.push(cell.tile.waitForTransition());
        if (lastValidCell.tile != null) {
          lastValidCell.mergeTile = cell.tile;
        } else {
          lastValidCell.tile = cell.tile;
        }
        cell.tile = null;
      }
    }
    return promises;
  }));
}

function canMoveUp() {
  return canMove(grid.cellsByColumn);
}

function canMoveDown() {
  return canMove(grid.cellsByColumn.map(column => [...column].reverse()));
}

function canMoveLeft() {
  return canMove(grid.cellsByRow);
}

function canMoveRight() {
  return canMove(grid.cellsByRow.map(row => [...row].reverse()));
}

function canMove(cells) {
  return cells.some(group => {
    return group.some((cell, index) => {
      if (index === 0) return false;
      if (cell.tile == null) return false;
      const moveToCell = group[index - 1];
      return moveToCell.canAccept(cell.tile);
    });
  });
}

grid.js

const GRID_SIZE = 4;
const CELL_SIZE = 20;
const CELL_GAP = 2;

export default class Grid {
  #cells

  constructor(gridElement){
    gridElement.style.setProperty('--grid-size', GRID_SIZE);
    gridElement.style.setProperty('--cell-size', `${CELL_SIZE}vmin`);
    gridElement.style.setProperty('--cell-gap', `${CELL_GAP}vmin`);
    this.#cells = createCellElements(gridElement).map((cellElement, index) => {
      return new Cell(
        cellElement,
        index % GRID_SIZE,
        Math.floor(index / GRID_SIZE));
    }); //Function for building the cells
  }

  get cells() {
    return this.#cells;
  }

  get cellsByColumn() {
    return this.#cells.reduce((cellGrid, cell) => {
      cellGrid[cell.x] = cellGrid[cell.x] || []; //if there is no cell for this x, get one
      cellGrid[cell.x][cell.y] = cell;
      return cellGrid;
    }, [])
  }
  get cellsByRow() {
    return this.#cells.reduce((cellGrid, cell) => {
      cellGrid[cell.y] = cellGrid[cell.y] || []; //if there is no cell for this x, get one
      cellGrid[cell.y][cell.x] = cell;
      return cellGrid;
    }, [])
  }

  get #emptyCells() {
    return this.#cells.filter(cell => cell.tile == null);
  }

  randomEmptyCell() {
    const randomIndex = Math.floor(Math.random() * this.#emptyCells.length);
    return this.#emptyCells[randomIndex];
  }
}

class Cell {
  #cellElement;
  #x;
  #y;
  #tile;
  #mergeTile;

  constructor(cellElement, x, y) {
    this.#cellElement = cellElement;
    this.#x = x;
    this.#y = y;
  }

  get x() {
    return this.#x;
  }

  get y() {
    return this.#y;
  }

  get tile() {
    return this.#tile;
  }

  set tile(value) {
    this.#tile = value;
    if (value == null) return;
    this.#tile.x = this.#x;
    this.#tile.y = this.#y;
  }

  get mergeTile() {
    return this.#mergeTile;
  }

  set mergeTile(value) {
    this.#mergeTile = value;
    if (value == null) return;
    this.#mergeTile.x = this.#x;
    this.#mergeTile.y = this.#y;
  }

  canAccept(tile) {
    return
      (this.tile == null ||
      (this.mergeTile == null && this.tile.value === tile.value)
    );
  }

  mergeTiles() {
    if (this.tile == null || this.mergeTile == null) return;
    this.tile.value = this.tile.value + this.mergeTile.value;
    this.mergeTile.remove();
    this.mergeTile = null;
  }
}

function createCellElements(gridElement) {
  const cells = [];
  for (let i = 0; i < GRID_SIZE * GRID_SIZE; i++) {
    const cell = document.createElement("div");
    cell.classList.add("cell");
    cells.push(cell);
    gridElement.append(cell); 
  }
  return cells;
}

    enter code here
    enter code here

tile.js

export default class Tile {
  #tileElement;
  #x;
  #y;
  #value;

  constructor(tileContainer, value = Math.random() > .5 ? 2 : 4) {
    this.#tileElement = document.createElement('div');
    this.#tileElement.classList.add('tile');
    tileContainer.append(this.#tileElement);
    this.value = value;
  }

  get value() {
    return this.#value;
  }

  set value(v) {
    this.#value = v;
    this.#tileElement.textContent = v;
    const power = Math.log2(v);
    const backgroundLightness = 100 - power * 9;
    this.#tileElement.style.setProperty("--background-lightness", `${backgroundLightness}%`);
    this.#tileElement.style.setProperty("--text-lightness", `${backgroundLightness <= 50 ? 90 : 10}%`);
  }

  set x(value) {
    this.#x = value;
    this.#tileElement.style.setProperty("--x", value);
  }

  set y(value) {
    this.#y = value;
    this.#tileElement.style.setProperty("--y", value);
  }

  remove() {
    this.#tileElement.remove();
  }

  waitForTransition(animation = false) {
    return new Promise(resolve => {
      this.#tileElement.addEventListener(animation ? "animationend" : "transitioned", resolve, {once: true})
  });
  }
}

Conditionally render a component React

In my application, I want to conditionally render 2 different Tooltip from recharts library depending if level.value != "A"

As seen below, I try to achieve this by using a ternary operator, as modeled in this article https://flexiple.com/react/conditional-rendering-in-react/. However, now no Tooltip shows up if the level is A or not. Also when I console.log(level.value != "A") it is evaluating correctly.

return(
    <>
//other code
        <div>
           {(level.value != "deployment") ? (
             <Tooltip labelStyle={{ color: "black" }} />
           ) : (
            <Tooltip content = {<CustomTooltip/> } labelStyle={{ color: "black" }} />
           ) }            
        </div>   
    </>
);

Cross-site request with credentials not working

I have a Nextjs app hosted on Vercel and a Nestjs API hosted on Railway (two different domains), and I am trying to make cross-site requests work. I have set up CORS and am no longer getting blocked by it. However, credentials are not being passed in the request (using axios)

Here is my axios instance used to make the call to the api

export const api = axios.create({
    baseURL: apiBaseURL,
    responseType: "json",
    withCredentials: true,
});

In the backend, I am setting the token cookie

res.setCookie(
            "token",
            this.jwtService.sign({ id: user.id, email: user.email }),
            {
                path: "/",
                secure: true,
                sameSite: "none",
                httpOnly: true,
            }
);

The token cookie is later used to authenticate the user’s request and is set when the user authenticates with Google OAuth. The user chooses his account, and is redirected to the /auth/redirect API endpoint (Railway) which then sets the cookie and redirects to the front-end (Vercel)

My CORS configuration

app.enableCors({
    origin: ["http://localhost:3000", "https://my-app.vercel.app"],
    credentials: true,
});

Everytime the Front-end tries to call a protected API endpoint, the cookies are not being sent.

I am using the fastify-adapter for Nestjs.