nestjs Header decorator conflicting with js native header

I am new to nestjs and I was trying to use the @Headers() decorator to get access to the headers of the request. here is the code:

import { Body, Controller, Post } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Post()
  public createUser(@Body('email') email: string, @Headers() reqHeaders: any) {
    return 'You sent a request to create a user';
  }
}

but I am getting the below error from typescript:

Value of type '{ new (init?: HeadersInit): Headers; prototype: Headers; }' is not callable. Did you mean to include 'new'?ts(2348)

It seems that typescript is confusing js native headers with the Headers decorator of nestjs. Or maybe the problem is something else?

I would appreciate any help with fixing this typescript error.
thanks.

Why is my JWT cookie disappearing after login redirect in Node.js and Express?

I’m working on a Node.js/Express app with JWT-based authentication. After logging in, I’m setting a cookie with the JWT token, but the cookie disappears once I redirect the user to the home page. Here’s the setup:

Backend: Using cookie-parser to manage cookies and setting the cookie with res.cookie in the authenticate_user route.
Frontend: Making a fetch request with { credentials: “include” } for both login and subsequent authenticated requests.
CORS: Configured with credentials: true and origin: true (also tried setting the specific origin URL).
Issue: The cookie is present on login.html after logging in, but it disappears when I redirect to index.html.

**It works fine when I use Insomnia but in webpage my cookie just disappear
**

users.js

const Users = require("../models/User");
const bcrypt = require('bcrypt');
const create_token = require("../utils/createJWT_Token");
const jwt = require("jsonwebtoken");
const MAX_AGE = 60 * 60 * 24; // Token expiration time (1 day)

// Get User
const get_user = async (req, res) => {
    const token = req.cookies.user_auth;
    console.log(req.cookies.user_auth)
    if (!token) {
        return res.status(401).json({ message: "No token provided" });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRECT_KEY);
        console.log(decoded); // You should have the decoded payload here, e.g., { username: "someUser" }
        // Proceed with the logic (e.g., fetch user from DB)
        const user = await Users.findOne({ username: decoded.user_id });
        res.status(200).json({ user });
    } catch (error) {
        res.status(401).json({ message: "Invalid token" });
    }



};


// Create User
const create_user = async (req, res) => {
    const { username, password } = req.body;
    
    try {
        // Hash the password before saving
        const hashedPassword = await bcrypt.hash(password, 10);

        // Create new user
        const newUser = new Users({
            username,
            password: hashedPassword
        });

        // Save the user
        const user = await newUser.save();
        console.log(user);

        // Generate token and set cookie
        const token = create_token(user.username, MAX_AGE);
        res.cookie("user_auth", token, {
            httpOnly: true,
            maxAge: MAX_AGE * 1000,
            sameSite: "Lax", // or "None" if testing on HTTPS
            path: "/" // ensure it's available to all routes
          });
        res.status(201).json({ message: "User created successfully", user });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

// Authenticate User
const authenticate_user = async (req, res) => {
    const { username, password } = req.body;

    try {
        const user = await Users.findOne({ username });
        if (!user) return res.status(404).json({ message: "Username not registered" });

        const validate = await bcrypt.compare(password, user.password);
        if (!validate) return res.status(401).json({ message: "Wrong credentials" });

        // Generate token and set cookie
        const token = create_token(user.username, MAX_AGE);
        res.cookie("user_auth", token, {
            httpOnly: true,
            maxAge: MAX_AGE * 1000,
            sameSite: "Lax", // or "None" if testing on HTTPS
            path: "/" // ensure it's available to all routes
          });
        res.status(200).json({ message: "Success" });
    } catch (e) {
        res.status(500).json({ message: e.message });
    }
};

// Logout User
const logout_user = (req, res) => {
    res.cookie("user_auth", "", { maxAge: 1 });
    res.redirect("/");
};

module.exports = {
    get_user,
    create_user,
    authenticate_user,
    logout_user
};

userRoute.js

const {Router} = require("express");
const authenticate = require("../middleware/authMiddleware");
const {
    get_user,
    create_user,
    authenticate_user,
    logout_user
} = require("../controllers/users");
const router = Router();

router.route("/get-user").get(get_user);
router.route("/create-user").post(create_user);
router.route("/authenticate_user").post(authenticate_user);
router.route("/logout_user").post(logout_user);

router.route("/auth-status").get(authenticate, (req, res) => {
    res.status(200).json({ message: "Authenticated" });
});
module.exports = router;

server.js

const dotenv = require("dotenv");
dotenv.config({});
const express= require("express");
const app = express();
const port = process.env.PORT || 8000;
const mapRoute = require("./routes/maps");
const userRoute = require("./routes/users");
const database = require("./database/connect");
const cors = require("cors");
const authenticate = require("./middleware/authMiddleware");
const cookieParser = require("cookie-parser");


// Middleware
app.use(express.json());
const corsConfig = {
    credentials: true,
    origin: true,
};
app.use(cors(corsConfig));
app.use(cookieParser());

// Routes
app.use("/api/users", userRoute);
app.use("/api/map",authenticate, mapRoute);

app.listen(port, () => {

    database(process.env.MONGO_URI);
    console.log(`Server Running on PORT: ${port}`)

})

Login.js

const apiUrl = "http://localhost:4000";


document.getElementById("loginForm").addEventListener("submit", async(e) => {
    e.preventDefault();
    const username = document.getElementById("loginUsername").value;
    const password = document.getElementById("loginPassword").value;

    try{
        const response = await fetch(`${apiUrl}/api/users/authenticate_user`, {
            method: "POST",
            credentials: "include",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        })
        const result = await response.json()
        if(result.message === "Success"){
            // location.href = 'index.html';
            console.log(document.cookie);
        }
    } catch (e) {
        console.log("Helo")
    }
})

script.js for index page

const apiUrl = "http://localhost:4000";


// 

document.addEventListener("DOMContentLoaded", async() => {
  try{
    const response = await fetch(`${apiUrl}/api/users/get-user`, {
      method: "GET",
      credentials: "include",
      headers: {
          'Content-Type': 'application/json'
      }
  })
  console.log(response)
  } catch(e){
    console.log(e);
  }
})

cookie just gone in index page

I try every chatgpt solutionyour text

Google Annotation chart Invalid date, or date and time error

I am having problem in formatting the date column for Google Annotation chart. I am following this link https://developers.google.com/chart/interactive/docs/gallery/annotationchart

My Data for Annotation chart

 var init_data = [["Week","A","A Title","A Annot","B","B Title","B Annot"],
["2022-05-01T18:30:00.000Z",10,"A","AAA",1984,"B","BBB"],
["2022-05-08T18:30:00.000Z",36,"A","AAA",150,"B","BBB"],
["2022-05-15T18:30:00.000Z",30,"A","AAA",199,"B","BBB"],
["2022-05-22T18:30:00.000Z",33,"A","AAA",184,"B","BBB"],
["2022-05-29T18:30:00.000Z",20,"A","AAA",161,"B","BBB"],
["2022-06-05T18:30:00.000Z",37,"A","AAA",172,"B","BBB"],
["2022-06-12T18:30:00.000Z",22,"A","AAA",151,"B","BBB"]]

I using below function to convert to mm/dd/yyyy format

function convertdate(date) {
        date = new Date(date);
        //console.log(date);
        let year = date.getFullYear();
        let month = (1 + date.getMonth()).toString().padStart(2, '0');
        let day = date.getDate().toString().padStart(2, '0');         
        return month + '/' + day + '/' + year;
        }

Applying above function my data look like


var data = [['Week','A','A Title','A Annot','B','B Title','B Annot'],
['05/01/2022',10,'A','AAA',1984,'B','BBB'],
['05/08/2022',36,'A','AAA',150,'B','BBB'],
['05/15/2022',30,'A','AAA',199,'B','BBB'],
['05/22/2022',33,'A','AAA',184,'B','BBB'],
['05/29/2022',20,'A','AAA',161,'B','BBB'],
['06/05/2022',37,'A','AAA',172,'B','BBB'],
['06/12/2022',22,'A','AAA',151,'B','BBB']]

And I am passing above data to Array to DataTable function

var chart_data = google.visualization.arrayToDataTable(data);
          var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

          var options = {
            displayAnnotations: true
          };

          chart.draw(chart_data, options);

It throws error in the browser(Google)

First column must contain date, or date and time.

I tried uing new Date() it gives me the date format like

Mon Oct 09 2023 00:00:00 GMT+0530 (India Standard Time) // This throws same error as well

How to format the date column for Google Annotation chart.

Shrink div to content when text break lines with CSS or Javascript/JQuery

(https://i.sstatic.net/nSchqcaP.png)](https://i.sstatic.net/77sH1HeK.png)

Hello all,
first sorry i’m a neebie 😉
My question is: i have a 3 columns block and would like a commun space between them. I can’t force the width of the elements as i don’t know it. I could make 3 colums of 33% width but in this case the empty space will not be equal because the first title is smaller than the other ones.
My problem is that it’s OK when the text is on oneline but when it break on 2 lines, the space is no longer equal (as you can see of pictures).

I thinked i could do this by css (for exemple by fit-content) but with no result. If found some old js but the size don’t shrink or expand if we resize the browser window, this only work on load. So i ask me if in 2024 there will be a better solution?
Thank you for your help and sorry for my english 😉
regards,
Jerome

Scroll Jumping Up and Down When Attempted To Be Smooth

I’m trying to implement smooth scrolling for my entire page, but I’m experiencing an issue where the scrolling “snaps” up and down rather than moving smoothly. It seems to jump unpredictably instead of easing nicely as expected.

What I’ve Done:

I’ve added scroll-behavior: smooth in my global styles using styled-components.
I’ve set overflow-y: scroll for my main container to ensure scrolling works as intended.
I’ve made it important: scroll-behavior: smooth !important;

GlobalStyles.js:

import { createGlobalStyle } from 'styled-components';

const GlobalStyles = createGlobalStyle`
  /* Apply box-sizing to all elements for better layout control */
  *, *::before, *::after {
    box-sizing: border-box;
  }

  /* Ensure smooth scrolling across the entire page */
  html {
    scroll-behavior: smooth !important;
  }

  body {
    margin: 0;
    padding: 0;
    font-family: 'Poppins', sans-serif;
    background-color: #f9f9f9;
    color: #333;
    line-height: 1.6;
  }

  /* Styles for the scroll container */
  #container {
    overflow-y: scroll;
  }

  /* Fixed positioning for the topTab with white text */
  .topTab {
    bottom: 0;
    position: fixed;
    font-size: 25px;
    color: white;
  }

  /* Styling for page sections */
  .pg {
    font-size: 100px;
    height: 100vh;
    background-color: blue;
    text-align: center;
  }

  /* Styling for links */
  a {
    color: white;
    text-decoration: none;
  }
`;

export default GlobalStyles;

Video of the problem attached here: https://streamable.com/0ykmf5

Why is my Carousel not working and the taking me to the top of the page

I’m struggling here with my code, I’ve been trying to build a carousel for my website and there are 2 issues, the first one is the carousel buttons are not working, they just take me to the top of the page which I tried countering with JS, secondly is the carousel isn’t working, the slides aren’t changing as they should.

Here is my scss

.customer-reviews{
  background: linear-gradient(
    304deg,
    rgba(18, 104, 94, 1) 28%,
    rgba(113, 53, 194, 1) 100%
  );
  color:white;
  width:100%;
  text-align:center;

  .container{
    padding-top:80px;
    padding-bottom:80px;
    margin: 0 auto;
    overflow: hidden;
    width:800px;
  }

  .carousel{
    display:flex;
    flex-direction:row;
    align-items:center;
    margin:40px;
    transition: transform 0.3s ease;
    gap:15%;
    
  }
  .carousel-slide{
    flex: 0 0 100%;
    width:650px;
  }
  .control{
    position:absolute;
    display:inline-block;
    text-align:center;
    align-content:center;
    width:48px;
    height:48px;
    font-size:24px;
    background-color:white;
    color:#12685E;
    border-radius:5px;
  }
  .prev{
    left:5%;
  }
  .next{
    right:5%;
  }
  .carousel{
    display:flex;
    flex-direction:column;
    align-items:center;
    margin:40px;
  }
  .carousel-item{
    width:60%;
  }
  #carousel {
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: row;
  }
  
  .carousel-container {
    display: flex;
    transition: transform 0.5s ease;
    width: 100%;
  }
  
  a{
      text-decoration: none;
      color:white;
  }
  ul li {
      list-style-type: none;
  }
  ul {
      padding: 0;
      margin: 0;
  }
}

Here is my html:

<div class="customer-reviews">
    <div class="container page-width">
        <div class="heading">
            <h2>What our customers have to say</h2>
        </div>
        <a href="#" class="control prev"><</a>
        <a href="#" class="control next">></a>
        <div class="carousel" id="carousel">
            <ul class="carousel-container">
                {% if site.data.customer-reviews %}
                    {% assign cr = site.data.customer-reviews %}
                    {% for entry in cr %}
                        {% assign key = entry | first %}
                        <li class="carousel-slide">
                            <div class="review">
                                <p>{{ cr[key].review }}</p>
                            </div>
                            <div class="author">
                                <h5>{{ cr[key].title }}</h5>
                            </div>
                            <div class="description">
                                <h6>{{ cr[key].description }}</h6>
                            </div>
                        </li>
                    {% endfor %}
                {% endif %}
            </ul>
        </div>
    </div>
</div>

here is my javascript:

jquery(document).ready(function($) {

    let slideCount = $('#carousel ul li').length;
    let slideWidth = $('#carousel ul li').outerWidth();
    let slideHeight = $('#carousel ul li').height();
    let sliderUlWidth = slideCount * slideWidth;

    $('#carousel').css({ width: slideWidth, height: slideHeight });
    $('#carousel ul').css({ width: sliderUlWidth, marginLeft: -slideWidth });

    $('#carousel ul li:last-child').prependTo('#carousel ul');

    function moveLeft() {
    $('#carousel').animate({
        left: + slideWidth
    }, 200, function() {
        $('#carousel ul li:last-child').prependTo('#carousel ul');
        $('#carousel ul').css('left', '');
    });
    }  

    function moveRight() {
        $('#carousel').animate({
            left: -slideWidth
        }, 200, function() {
            $('#carousel ul li:first-child').appendTo('#carousel ul');
            $('#carousel ul').css('left', '');
        });
    }

    $('a.prev').on('click', function(event) {
        event.preventDefault(); 
        moveLeft();
    });
    
    $('a.next').on('click', function(event) {
        event.preventDefault();
        moveRight();
    });
    
 });

Technically a form within a form

I have a form for users to select their gender but I would like to add an input so that the user may add a gender to the MYSQL database and auto refresh the form to include their new gender for a selection.

So, if the MYSQL database has male and female already but the user wants to add non-binary to the MYSQL database, they can type ‘non-binary’ into an input field and click to have it added to the MYSQL database and auto refresh options to list male, female, and non-binary without submitting the actual form.

Before User Input

<p>
<label>Male</label>
<input type="radio" name="Gender" value="male">
</p>
<p>
<label>Female</label>
<input type="radio" name="Gender" value="female">
</p>
<p>
<label>Add A Gender</label>
<input id="myText" name="newgender" type="text" AUTOCOMPLETE=OFF></input>
<button id="mySubmit">Add</button>
</p>

After User Input

<p>
<label>Male</label>
<input type="radio" name="Gender" value="male">
</p>
<p>
<label>Female</label>
<input type="radio" name="Gender" value="female">
</p>
<p>
<label>Non-binary</label>
<input type="radio" name="Gender" value="Non-binary">
</p>
<p>
<label>Add A Gender</label>
<input id="myText" name="newgender" type="text" AUTOCOMPLETE=OFF></input>
<button id="mySubmit">Add</button>
</p>

How to make a mouse-scroll from anywhere on the page, scroll one specific element?

I need to scroll one specific element on the page even when the mouse isn’t hovering over that element…

I would normally put the div that needs scrolling on the top layer with a transparent background but I have a navigation menu that needs to be seen/interacted with on the same page.

In my experience CSS is extremely finicky; one change that is supposed to be aesthetic only ends up altering how the elements interact with each other and it is frustrating. I am hours into this project and I really don’t feel like starting from scratch again just for one bug like this… and having to test if the website works after every CSS addition.

I’ll put a jsfiddle of what my website is pretty much structured like.

html {
  overflow: hidden;
}

.fixed {
  position: fixed;
  background-color: blue;
  width: 50%;
}

.scrollable {
  background-color: red;
  height: 100vh;
  padding-left: 50%;
  overflow-y: scroll;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <div class="fixed">
    <h1>
    Lorem ipsum dolor sit amet
    </h1>
    
  </div>
  <div class="scrollable">
    <ul>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
       <li>_________</li>
     </ul>
   </div>
</body>
</html>

I can scroll anywhere on the red div and it works, but if I scroll on the blue div the red div won’t scroll. Changing the blue div to pointer-events: none; makes it all work (this was the only answer I could find online) except for the fact that I have a navigation bar with pointer events inside the blue div. You would think after being around for centuries HTML would find a simple way to let a fixed element have pointer events AND scroll events!

TL;DR Is there a way to make a scroll anywhere on the screen scroll one specific div? Thanks in advance.

Is it valid to nest forms using shadow DOM in custom web components?

I have a question about custom web components. Custom element for example:

class CustomButton extends HTMLElement {
    connectedCallback() {
        this.root = this.attachShadow({mode: "open"});
        const form = document.createElement("form");
        this.root.append(form);
    }
}
customElements.define("custom-button", CustomButton);

Now I put this custom element which contains own form with some inputs into another form in page

<form>
    <input type="text" name="name">
    <custom-button>Select</custom-button>
    <button type="submit">Submit</button>
</form>

In this case, web this component is universal library component and I have I have no control over where the user puts it.

Normally I can’t put <form> element into another <form> element but what about shadow dom in this case? Is it valid? Can i put anything into shadow dom without having to worry about some specific usage?

Thanks for any response!

How to share images from telegram mini app?

Please tell me what methods are there to allow the user to share content such as images in Telegram mini apps on JS?
The only one I saw in the documentation is shareToStory, but these are only stories and they are not yet available to all users. But I would like the user to be able to send an image to other chats, for example, to their friends.

ps I thought about the navigator.share method, but it is not supported by all browsers yet, and this is not a built-in method from the Telegram team

Expand nodejs socket size

I have a tcp proxy server in nodejs and it uses the net module. Sometimes large packets come through and then the server just crashes. I tried finding out how to expand the socket size online and from chatgpt but i cant find a solution.
How can i fix this?

I already tried this

socket.highWaterMark = 0.25 * 1024 ** 2; // 256KB
socket._server.highWaterMark = 0.25 * 1024 ** 2; // 256KB
socket.bufferSize = 0.25 * 1024 ** 2; // 256KB
socket.writableLength = 0.25 * 1024 ** 2; // 256KB
socket._writableState.highWaterMark = 0.25 * 1024 ** 2; // 256KB
socket._readableState.highWaterMark = 0.25 * 1024 ** 2; // 256KB

Wordle clone with microphone integration: Why is addWord() not working while addKey() functions as expected?

I have a Wordle clone made with Expo React-Native w/ TypeScript. I followed a tutorial on youtube Building a Wordle Game with React Native – Simon Grimm which explained the basic logic of the game, adding the rows and columns, managing the keyboard keys pressing, etc. All this worked great, but my professor wanted me to add a microphone input so that the words could be dictated, instead of typed.

After some tinkering I managed to make the mic work perfectly; it registers a word as a string only if it is a 5 letter word (since the game only works with these types of words anyway) and the word gets passed through as a prop from the OnScreenKeyboard component to the main Game component, where it can then be processed or added to the game’s current state.

Here’s game.tsx, wich handles the game logic, as I said, the words received by the mic in the OnScreenKeyboard.tsx enters the addWord() function, but somehow, it fails to respect the rows that it should insert the words into, it just inserts the word received by mic at the first row every time.

game.tsx

const [rows, setRows] = useState<string[][]>(new Array(ROWS).fill(new Array(5).fill('')));
const [curRow, setCurRow] = useState(0);
const [curCol, _setCurCol] = useState(0);

const [blueLetters, setBlueLetters] = useState<string[]>([]);
const [yellowLetters, setYellowLetters] = useState<string[]>([]);
const [grayLetters, setGrayLetters] = useState<string[]>([]);

// Random word gets generated
const [word, setWord] = useState<string>(words[Math.floor(Math.random() * words.length)]);

const wordLetters = word.split('');

const colStateRef = useRef(curCol);
const setCurCol = (col: number) => {
  colStateRef.current = col;
  _setCurCol(col);
};

// Checks the word, does the flip animation, paints the tiles and keyboard
const checkWord = () => {
  const currentWord = rows[curRow].join('');
  if (currentWord.length < word.length) {
    shakeRow();
    return;
  }
  if (!allWords.includes(currentWord)) {
    shakeRow();
    return;
  }

  flipRow();

  const newBlue: string[] = [];
  const newYellow: string[] = [];
  const newGray: string[] = [];

  currentWord.split('').forEach((letter, index) => {
    if (letter === wordLetters[index]) {
      newBlue.push(letter);
    } else if (wordLetters.includes(letter)) {
      newYellow.push(letter);
    } else {
      newGray.push(letter);
    }
  });
  setBlueLetters([...blueLetters, ...newBlue]);
  setYellowLetters([...yellowLetters, ...newYellow]);
  setGrayLetters([...grayLetters, ...newGray]);

  setTimeout(() => {
    if (currentWord === word) {
      router.push(`/end?win=true&word=${word}&gameField=${JSON.stringify(rows)}`);
    } else if (curRow + 1 >= rows.length) {
      router.push(`/end?win=false&word=${word}&gameField=${JSON.stringify(rows)}`);
    }
  }, 1500);
  setCurRow(curRow + 1);
  setCurCol(0);
};

// Evaluates each keyboard key pulsation
const addKey = (key: string) => {
  console.log('addKey', key);

  const newRows = [...rows.map((row) => [...row])];

  if (key === 'ENTER') {
    checkWord();
  } else if (key === 'BACKSPACE') {
    if (colStateRef.current === 0) {
      newRows[curRow][0] = '';
      setRows(newRows);
      return;
    }
    newRows[curRow][colStateRef.current - 1] = '';
    setCurCol(colStateRef.current - 1);
    setRows(newRows);
    return;
  } else if (colStateRef.current >= newRows[curRow].length) {
    // End of line
    return;
  } else {
    newRows[curRow][colStateRef.current] = key;
    setRows(newRows);
    setCurCol(colStateRef.current + 1);
  }
};

// Recieves the word by mic (Here's the problem)
const addWord = (word: string) => {
  const letters = word.split('');
  const newRows = [...rows.map((row) => [...row])];

  letters.forEach((letter, index) => {
    if (index < 5) {
      newRows[curRow][index] = letter;
    }
  });

  setRows(newRows);
  setCurCol(Math.min(letters.length, 5));
  setTimeout(()=>checkWord(),1000);
};

/* More code, not related to the game logic */

return (
        <View style={styles.container}>
            {keys.map((row, rowIndex) => (
                <View key={`row-${rowIndex}`} style={styles.row}>
                    {row.map((key, keyIndex) => (
                        <Pressable
                            key={`key=${key}`}
                            onPress={() => (key === MICROPHONE ? handleMicrophonePress() : onKeyPressed(key))}
                            style={({pressed}) => [
                                styles.key,
                                {
                                    width: keyWidth,
                                    height: keyHeight,
                                    backgroundColor: '#DDD',
                                },
                                isSpecialKey(key) && {width: keyWidth * 1.5},
                                {
                                    backgroundColor: blueLetters.includes(key)
                                        ? '#6ABDED'
                                        : yellowLetters.includes(key)
                                          ? '#FFE44D'
                                          : grayLetters.includes(key)
                                            ? '#808080'
                                            : key === MICROPHONE && isRecording
                                              ? '#FF4444'
                                              : '#DDD',
                                },
                                pressed && {backgroundColor: '#868686'},
                            ]}
                        >
                            <Text style={[styles.keyText, key === 'ENTER' && {fontSize: 12}, isInLetters(key) && {color: '#FFFFFF'}]}>
                                {isSpecialKey(key) ? (
                                    key === ENTER ? (
                                        'Enter'
                                    ) : (
                                        <Ionicons name="backspace-outline" size={24} color={'black'} />
                                    )
                                ) : key === MICROPHONE ? (
                                    <Ionicons name="mic-outline" size={24} color={isRecording ? 'white' : 'black'} />
                                ) : (
                                    key
                                )}
                            </Text>
                        </Pressable>
                    ))}
                </View>
            ))}
        </View>
    );
};

export default game.tsx;

/* Styling code */


OnScreenKeyboard.tsx

import {Platform, Pressable, StyleSheet, Text, useWindowDimensions, View} from 'react-native';
import React, {useState} from 'react';
import {Ionicons} from '@expo/vector-icons';
import Voice from '@react-native-voice/voice';

type OnScreenKeyboardProps = {
    onKeyPressed: (key: string) => void;
    onWordRecognized: (word: string) => void;
    blueLetters: string[];
    yellowLetters: string[];
    grayLetters: string[];
};

export const ENTER = 'ENTER';
export const BACKSPACE = 'BACKSPACE';
export const MICROPHONE = 'MICROPHONE';

const keys = [
    ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],
    ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', MICROPHONE],
    [ENTER, 'z', 'x', 'c', 'v', 'b', 'n', 'm', BACKSPACE],
];

const OnScreenKeyboard = ({onKeyPressed, onWordRecognized, blueLetters, yellowLetters, grayLetters}: OnScreenKeyboardProps) => {
    const {width} = useWindowDimensions();
    const keyWidth = Platform.OS === 'web' ? 58 : (width - 60) / keys[0].length;
    const keyHeight = 55;
    const [isRecording, setIsRecording] = useState(false);

    const isSpecialKey = (key: string) => [ENTER, BACKSPACE].includes(key);
    const isInLetters = (key: string) => [...blueLetters, ...yellowLetters, ...grayLetters].includes(key);

    React.useEffect(() => {
        Voice.onSpeechResults = onSpeechResults;
        return () => {
            Voice.destroy().then(Voice.removeAllListeners);
        };
    }, []);

    const removeAccents = (word: string) => {
        return word.replace(/á/g, 'a').replace(/é/g, 'e').replace(/í/g, 'i').replace(/ó/g, 'o').replace(/ú/g, 'u');
    };

    const onSpeechResults = (e: any) => {
        if (e.value && e.value[0]) {
            let word = e.value[0].toLowerCase().trim();
            word = removeAccents(word);

            if (word.length === 5) {
                onWordRecognized(word);
            }
        }
        setIsRecording(false);
    };

    const handleMicrophonePress = async () => {
        try {
            if (isRecording) {
                await Voice.stop();
                setIsRecording(false);
            } else {
                setIsRecording(true);
                await Voice.start('es-ES');
            }
        } catch (error) {
            console.error(error);
            setIsRecording(false);
        }
    };

    return (
        <View style={styles.container}>
            {keys.map((row, rowIndex) => (
                <View key={`row-${rowIndex}`} style={styles.row}>
                    {row.map((key, keyIndex) => (
                        <Pressable
                            key={`key=${key}`}
                            onPress={() => (key === MICROPHONE ? handleMicrophonePress() : onKeyPressed(key))}
                            style={({pressed}) => [
                                styles.key,
                                {
                                    width: keyWidth,
                                    height: keyHeight,
                                    backgroundColor: '#DDD',
                                },
                                isSpecialKey(key) && {width: keyWidth * 1.5},
                                {
                                    backgroundColor: blueLetters.includes(key)
                                        ? '#6ABDED'
                                        : yellowLetters.includes(key)
                                          ? '#FFE44D'
                                          : grayLetters.includes(key)
                                            ? '#808080'
                                            : key === MICROPHONE && isRecording
                                              ? '#FF4444'
                                              : '#DDD',
                                },
                                pressed && {backgroundColor: '#868686'},
                            ]}
                        >
                            <Text style={[styles.keyText, key === 'ENTER' && {fontSize: 12}, isInLetters(key) && {color: '#FFFFFF'}]}>
                                {isSpecialKey(key) ? (
                                    key === ENTER ? (
                                        'Enter'
                                    ) : (
                                        <Ionicons name="backspace-outline" size={24} color={'black'} />
                                    )
                                ) : key === MICROPHONE ? (
                                    <Ionicons name="mic-outline" size={24} color={isRecording ? 'white' : 'black'} />
                                ) : (
                                    key
                                )}
                            </Text>
                        </Pressable>
                    ))}
                </View>
            ))}
        </View>
    );
};

export default OnScreenKeyboard;

/* Styling code */

Here’s a demo of the bug playing the game (it’s in Spanish BTW), the expected behaviour would be that the second word gets inserted at the second row, obviously.

I tried a bit of everything to fix this. I also tried to insert the words picked up by the mic into the addKey() function, letter by letter with .split() but this doesn’t work either, which doesn’t make sense to me.

I think the main problem has to do with how the game handles the curRow state, but again, I tried to fix it and just couldn’t do it.

Javascript Fetch POST Request is showing up as a GET request on my backend (and stopping anything from working)

This is my post request. It is used to send the data of the user to a backend php page. I did some debugging and

    const fullusername = "<?php echo $to; ?>";
    const personontheline = sessionStorage.getItem('name');
    fetch('inc/AI2.php', {
        

    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams({
        fullname: fullusername, //variable
        personwhoclicked: personontheline //variable
    }) //continues to fetch errors

This is the backend. It shows that the $_SERVER['REQUEST_METHOD'] is a GET request for some reason. I’m not really good at php or javascript. It doesn’t work at all for some reason and i’ve spent hours trying to troubleshoot it. Its probably something dumb lol.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //do stuff
    }
} else {
    // Handle invalid requests
    echo "Invalid request       ".$_SERVER['REQUEST_METHOD'];
    die();
}

I tried switching the method of the fetch to a GET method, but this slightly fixed the code as my code does not recognize the GET method’s variables

if (isset($_GET['fullname']) AND isset($_GET['personwhoclicked'])) { //work } 
else{ echo "error"; }   

This is what burp suite makes it look like with post requests

This is what burp suite makes it look like with GET requests

Multiple dynamic Swiper JS slides on same page

Let’s say I have a custom CMS which allows me to add multiple slides on a page and each slide will have different options (slides to show at a time, slides to scroll, breakpoints, etc)

To my knowledge Swiper JS does not support data attributes in the slider HTML. It is something that needs to be implemented manually?

Im currently generating multiple slides on a page like this:

<div class="swiper" data-swiper='{"slidesPerView":3,"slidesPerGroup":3,"speed":300}}'>
    <div class="swiper-wrapper">
       <div class="swiper-slide">...</div>
       <div class="swiper-slide">...</div>
       <div class="swiper-slide">...</div>
    </div>
</div>

<div class="swiper" data-swiper='{"slidesPerView":1,"slidesPerGroup":1,"speed":800}}'>
    <div class="swiper-wrapper">
       <div class="swiper-slide">...</div>
       <div class="swiper-slide">...</div>
       <div class="swiper-slide">...</div>
    </div>
</div>

Then I use custom JS:

document.addEventListener('DOMContentLoaded', function () {
  const sliders = document.querySelectorAll('.swiper');

  sliders.forEach(slider => {
    const swiperOptions = JSON.parse(slider.getAttribute('data-swiper'));

    // Initialize Swiper instance
    new Swiper(slider, {
      ...swiperOptions,

This works. However is there a better more official way to handle multiple dynamic slides?

Is there a way to transform images in V8 js engine without transforming it to Uint8Array?

Most js/wasm libraries that transform images, require transforming it to Uint8Array first.

The problem is that image converted to Uint8Array can take x10 more memory than image stored on a drive (10MB jpeg takes ~120MB memory).

And this creates OOM problems with computing based on V8 and limited ram.

So the question, is there no other way to transform images than converting it to Uint8Array?