can’t access an element ref in react

i’am trying to implement à modal with React, in this modal i want to position the modal relatively to the the element wich trigger it (which is not à parent),
in this set up i can access the the reference to the triggering element like you see here

        console.log(
          "console button triggering modal offset" + event.target.offsetTop
        );

but i can’t access the reference to the modal, this code generate an error

  useEffect(() => {
    console.log("loggin ref width   " + modalRef.current.offsetWidth);
  }, [modalRef]);

when i remove the CSSTransition component every thing is fine,
here is the full code,
i would appreciate any help

import {
  React,
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import ReactDOM from "react-dom";

import "./UserParamModal2.css";
import { CSSTransition } from "react-transition-group";

const UserParamModalOverlay = forwardRef((props, ref) => {
  const content = (
    <div className={`userparammodal ${props.className}`} ref={ref}>
      {props.children}
    </div>
  );
  return ReactDOM.createPortal(
    content,
    document.getElementById("modal-user-param")
  );
});

const UserParamModal2 = forwardRef((props, ref) => {
  const [visible, setVisible] = useState(false);
  const modalRef = useRef();

  useImperativeHandle(ref, () => {
    return {
      toggle(event) {
        console.log(
          "console button triggering modal offset" + event.target.offsetTop
        );
        setVisible((prev) => {
          return !prev;
        });
      },
    };
  });

  useEffect(() => {
    console.log("loggin ref width   " + modalRef.current.offsetWidth);
  }, [modalRef]);

  return (
    <CSSTransition
      in={visible}
      mountOnEnter
      unmountOnExit
      timeout={200}
      classNames="userparammodal"
    >
      <UserParamModalOverlay {...props} ref={modalRef}></UserParamModalOverlay>
    </CSSTransition>
  );
});

export default UserParamModal2;

How to remove the extra white space in the right side of the webpage after creating a side navigation bar

Initially my web page was not having that extra white space but after creating a side navigation bar(hamburger icon for devices having screen size less than 700px) i got the extra white space.

i used the code mentioned below for solving the problem ,but it didn’t work,

* {
  margin: 0px;
  padding: 0px;
}

html, body {
  max-width: 100%;  /*also tried 100vw and 100%*/
  overflow-x: hidden;
}

My Code :-

HTML(with internal Javascript)


<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Eduford</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Nunito:wght@300&display=swap"
      rel="stylesheet"
    />
  </head>
  <body>
    <header>
      <img src="imageslogo.png" class="logo" alt="logo" />
      <nav>
        <div class="nav-links">
          <i class="fa-solid fa-xmark" onclick="close_navbar()"></i>
          <ul>
            <li><a href="#">HOME</a></li>
            <li><a href="#footer">ABOUT</a></li>
            <li><a href="#course">COURSE</a></li>
            <li><a href="#">BLOG</a></li>
            <li><a href="#contact_us">CONTACT</a></li>
          </ul>
        </div>
        <i class="fa-solid fa-bars" onclick="show_navbar()"></i>
      </nav>
      <div class="textbox">
        <h1>World's Biggest University</h1>
        <p>
          Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quaerat non
          libero, neque sint quis reprehenderit aspernatur, id qui perspiciatis
          doloremque, error eius quae velit dicta odio distinctio? Maiores
          reiciendis in libero nihil quidem. Sapiente officiis quos ratione
          temporibus, quibusdam odit repellendus excepturi odio, rerum provident
          facere officia, quis ab maxime.
        </p>
        <a href="#">Learn More</a>
      </div>
    </header>

    <!-- JavaScript for Side NavBar -->
    <script type="text/javascript">
      const nav_links = document.querySelector(".nav-links");
      function show_navbar() {
        nav_links.style.right = "0px";
      }
      function close_navbar() {
        nav_links.style.right = "-400px";}
    </script>
  </body>
</html>

CSS:-

<style>
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
  font-family: "Nunito", sans-serif;
}

html, body {   /*I thought it will work but i didn't :( */
  max-width: 100vw;     /*also tried 100vw and 100%*/
  overflow-x: hidden;
}
.nav-links {
  position: absolute;
  top: 30px;
  right: 30px;
}

.nav-links ul {
  list-style-type: none;
  display: flex;
}

.nav-links ul li::after {
  content: "";
  display: block;
  width: 0%;
  height: 5px;
  background-color: rgb(219, 65, 65);
}

.nav-links ul li:hover::after {
  width: 80%;
  border-radius: 10px;
  margin: auto;
  transition: 0.5s;
}

header {
  min-height: 100vh;
  padding: 20px;
  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.509)),
    url(images/banner.png);
  background-position: center;
  background-size: cover;
}

.nav-links a {
  font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
  text-decoration: none;
  color: white;
  padding: 10px;
}

.textbox {
  color: white;
  display: flex;
  text-align: center;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 90%;
  height: 75vh;
  margin: auto;
}

.textbox h1 {
  font-size: 60px;
  padding-bottom: 20px;
}

.textbox a {
  margin-top: 20px;
  color: white;
  font-weight: 400;
  border: 1px solid white;
  padding: 8px;
  border-radius: 5px;
  text-decoration: none;
}

.textbox a:hover {
  background-color: rgb(219, 65, 65);
  border: 1px solid rgb(219, 65, 65);
  transition: 0.8s;
}

.logo {
  min-width: 150px;
  width: 20%;
}
.fa-solid.fa-bars::before,
.fa-solid.fa-xmark::before {
  display: none;
}

/* Code for small screens or mobile devices */

@media only screen and (max-width: 700px) {
  .textbox h1 {
    font-size: 40px;
    padding-bottom: 20px;
  }

  .fa-solid.fa-bars::before,
  .fa-solid.fa-xmark::before {
    display: block;
  }
  .fa-solid {
    color: white;
    font-size: 25px;
  }
  .fa-bars {
    position: absolute;
    top: 15px;
    right: 30px;
  }
  .fa-xmark {
    margin: 10px 15px;
    z-index: 2;
  }
  .nav-links {
    z-index: 1;
    width: 60vw;
    height: 100vh;
    background-color: rgb(219, 65, 65);
    position: absolute;
    top: 0;
    right: -400px;
    transition: 1s;
  }
  .nav-links ul {
    flex-direction: column;
    padding: 70px 30px;
    font-size: 75%;
  
  }
  .nav-links ul li {
    margin-bottom: 10px;
  }
}

React Native Realm flexible sync progress screen

I have integrated realm flexible sync which download lots of data from realm database after user login and works fine but i want to show progress screen until all data are downloaded on first launch.

As per documentation i have integrated to get progress notification but it only notify when 100% downloaded which is not wise for our app as we want to show actual progress and once download complete start using the app.

Please find below code that i implemented for same as per documentation.

enum ProgressDirection {
    Download = 'download',
    Upload = 'upload',
}

enum ProgressMode {
    ReportIndefinitely = 'reportIndefinitely',
    ForCurrentlyOutstandingWork = 'forCurrentlyOutstandingWork',
}

const AppSync = () => {
    const app = useApp();
    const realm = useRealm();

    useEffect(() => {
        if (__DEV__) {
            Realm.App.Sync.setLogLevel(app, 'debug');
        }

        const progressNotificationCallback = (transferred, transferable) => {
            // Convert decimal to percent with no decimals
            // (e.g. 0.6666... -> 67)
            const percentTransferred = parseFloat((transferred / transferable).toFixed(2)) * 100;
            console.log('percentTransferred', percentTransferred);
        };

        // Listen for changes to connection state
        realm.syncSession?.addProgressNotification(
            ProgressDirection.Download,
            ProgressMode.ForCurrentlyOutstandingWork,
            progressNotificationCallback
        );
        // Remove the connection listener when component unmounts
        return () => {
            realm.syncSession?.removeProgressNotification(progressNotificationCallback);
            if (!realm.isClosed) realm.close();
        };
    }, []);

    ...
}

percentTransferred log showed only when percentTransferred to 100%

My aim is to have progress screen until data get downloaded and once downloaded then render the app part only after it.

I keep getting the error of newUser.save is not a function, Next.js 13 api route

I am aiming to implement an OTP (One-Time Password) request process following a successful signup using the .save().then() method. However, when attempting to execute the code, I encounter a TypeError: ‘newUser.save is not a function’.”

This is my code


export const POST = async (req, res) => {
  const data = await req.json();
  console.log(process.env.NEXT_PUBLIC_APP_TOKEN);
  const sanity = {
    projectId: process.env.NEXT_PUBLIC_APP_KEY,
    dataset: "production",
    token: process.env.NEXT_PUBLIC_APP_TOKEN,
  };

  const clients = createClient(sanity);

  try {
    const users = await clients.fetch(
      `*[_type == 'user' && email == $email] [0]  `,
      {
        email: data.email,
      }
    );

    if (users) {
      return new Response(`User Already Exist`, {
        status: 500,
      });
    }
    const salt = await bcrypt.genSalt();
    const passwordHash = await bcrypt.hash(data.password, salt);
    const newUser = await clients.create({
      _type: "user",
      name: data.name,
      email: data.email,
      phone: data.phone,
      password: passwordHash,
    });

    await newUser.save().then((result) => {
      OtpVerificationEmail(result)
    }).catch((err) => {
      console.log(err)
    })

    // await transporter.sendMail({
    //   ...mailOptions,
    //   subject: "",
    // });

    Cookies.set("user", {
      name: data.name,
      email: data.email,
      phone: data.phone,
    });

    return new Response(JSON.stringify({ data }), {
      status: 201,
    });
  } catch (error) {
    return new Response(`${error}`, {
      status: 500,
    });
  }
};


I tried using .save() function but it is not working on next.js 13

How can I validate if the value is overlapping using Javascript?

I’m trying to check if the the timelineArray[1] and timelineArray[2] got overlapped or not. If its overlapped then add increment by timelineArray[3], if not the value should start with 1.

var timelineArray = [
  ["name1", "384", "456", "30"],
  ["name2", "72", "192", "30"],
  ["name3", "384", "456", "30"],
  ["name4", "384", "456", "15"],
  ["name5", "384", "576", "30"],
  ["name6", "96", "240", "12"]
  ["name7", "384", "456", "12"]
];

I would like loop the array to

  • check if timelineArray[1][1] and timelineArray[1][2] is between timelineArray[0][1] and timelineArray[0][2].
  • If yes means its overlapped, if no then assign new row.
  • Then when comes to name3, it will check if it is overlapped with previous arrays which is name1 and name2. It will validate the whole array.
  • add increment for array that is overlapped

Excepted result I should get is:

  1. name1, no overlap, 1-30
  2. name2, no overlap, 1-30
  3. name3, overlap with name1, 31-60
  4. name4, overlap with name1 and name3 , 61-75
  5. name5, overlap with name1,name3 and name4, 76-105
  6. name6, overlap with name2, 31-42
  7. name7, overlap with name1,name3,name4 and name5, 106-118

    Please help.

How to heuristically discover Javascript input autocomplete key* events

I recently had a requirement to enforce Proper-Case in a HTML input field. CSS Text-Transform: Capitalize was 90% there but didn’t down-case multiple caps. So I wrote the Javascript below.

To my surprise you’ll see that autocomplete input (user clicking one of the autocomplete options) results in keyup and keydown events that are bereft of any “key” properties 🙁 As you can also see in the code, I’m having to search for “key” in the event and if it’s not there I assume it’s an autocomplete.

Is there a better/documented way? Surely an autocomplete is more of a “Paste” event? Does someone have pointers to a specification(s)?

<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
    'use strict';
    
        document.addEventListener("DOMContentLoaded", isDOMIsGood);

        function isDOMIsGood() 
        {
            // Handle autocomplete
            document.body.addEventListener('keyup',
                (e) => {
                    
                    if (e.target.tagName.toUpperCase()  != "INPUT"      || 
                        e.target.type.toUpperCase()     != "TEXT"       ||
                        getComputedStyle(e.target).textTransform.toUpperCase() 
                                                        != "CAPITALIZE" ||
                        (
                        "transform" in e.target.dataset                 &&
                        e.target.dataset.transform.toLowerCase()
                                                        == "standard"   
                        ))                                              
                        return true;
                        
                    if ("key" in e) // not autocomplete
                        return true;

                    e.target.value = e.target.value.toLowerCase();
                    
                    return true;
                }
            );
            // Handle normal keyboard input         
            document.body.addEventListener('keydown',
                (e) => {
                
                    const WORD_DELIMS = ".,& -:";  // Needs work
                    
                    if (e.target.tagName.toUpperCase()  != "INPUT"      || 
                        e.target.type.toUpperCase()     != "TEXT")
                        return true;
                        
                    if (!("key" in e)) // autocomplete
                        return true;
                        
                    if (e.key.length                    >  1            || 
                        e.altKey                                        || 
                        e.ctrlKey                                       || 
                        e.isComposing                                   || 
                        e.metaKey                                       ||
                        e.target.value.length           ==  0           || 
                        e.target.selectionStart         ==  0           || 
                        e.key                           >  "Z"          || 
                        e.key                           <  "A"          ||
                        (
                        "transform" in e.target.dataset                 &&
                        e.target.dataset.transform.toLowerCase()
                                                        == "standard"   
                        )                                               ||
                        getComputedStyle(e.target).textTransform.toUpperCase() 
                                                        != "CAPITALIZE" ||
                        WORD_DELIMS.indexOf(e.target.value.substr(e.target.selectionStart - 1, 1)) != -1)           
                        return true;
                    
                    let   cursorPos         = e.target.selectionStart;
                    
                    e.target.value          = e.target.value.substring(0, cursorPos)        +
                                              String.fromCharCode(e.key.charCodeAt(0) + 32) + 
                                              e.target.value.substring(cursorPos);
                    e.target.selectionStart = ++cursorPos;
                    e.target.selectionEnd   = cursorPos;
                                    
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            );
            // Handle paste          
            document.body.addEventListener("paste", 
                (e) => {
                    const WORD_DELIMS = ".,& -:";   // Needs work
                    
                    if (e.target.tagName.toUpperCase()  != "INPUT"      || 
                        e.target.type.toUpperCase()     != "TEXT"       ||
                        getComputedStyle(e.target).textTransform.toUpperCase() 
                                                        != "CAPITALIZE" ||
                        (
                        "transform" in e.target.dataset                 &&
                        e.target.dataset.transform.toLowerCase()
                                                        == "standard"   
                        ))                                              
                        return true;

                    let paste = (e.clipboardData || window.clipboardData).getData('text');
                    if (paste.length == 0)
                        return true;
                    
                    e.target.value = (e.target.value.substring(0, e.target.selectionStart) + 
                                        paste + e.target.value.substring(e.target.selectionStart)).toLowerCase();

                    e.preventDefault();
                    e.stopPropagation();
                    return true;
                }
                
            );
            // Allow the user, config file, etc set the enforcement level          
            document.getElementById("properRules").addEventListener("click", 
                (e) => {
                    
                    if (e.target.tagName.toLowerCase() == "input" && 
                        e.target.type.toLowerCase()    == "radio" &&
                        e.target.name == "properCase")
                    {
                        var enhanced = document.getElementById("enhanced");
                        enhanced.dataset.transform = e.target.value;
                        
                        if (enhanced.dataset.transform == "none")
                            enhanced.style.textTransform = "none";
                        else
                            enhanced.style.textTransform = "capitalize";
                    }   
                    
                    return true;
                }
            ); 
        }
</script>
<style type="text/css">
input[type=radio]:checked {
    accent-color: lightblue;;
}
</style>
</head>
<body>
<h1>Supplementing CSS Text-Transform: Capitalize</h1>
<h2>How to enforce "Proper Case" on HTML input?</h2>

<p>CSS Text-Transform will upcase each word if all lower case but not downcase multiple consecutive caps</p>
<div id="outer">
    <div>
        <label for="enhanced">Enhanced Capitalize:</label>
        <input id="enhanced" type="text" style="text-transform: capitalize; background-color: lightblue;"
            autocomplete="new-password" autofocus spellcheck="false" >
        <br><br>
    </div>
    <div id="properRules">
      <p>"Proper Case" enforcement level:</p>
      <input type="radio" id="pc1" name="properCase" value="strict" checked=checked >
      <label for="pc1">Strict</label><br>
      <input type="radio" id="pc2" name="properCase" value="standard">
      <label for="pc2">Relaxed</label><br>
      <input type="radio" id="pc3" name="properCase" value="none">
      <label for="pc3">None</label><br>
    </div>
</div>
</body>
</html>

What Error does my Javascript Playwright code have?

I was trying to automate a test for the google search feature where you search the term “Lorem Ipsum” and print the first search result.

const { chromium } = require('playwright');

(async () => {
try {

const browser = await chromium.launch();

const context = await browser.newContext();

const page = await context.newPage();

await page.goto('https://www.google.com');

await page.waitForLoadState('domcontentloaded');

await page.waitForSelector('textarea[name="q"]');

await page.type('textarea[name="q"]', 'Lorem Ipsum');

await page.press('input[name="btnK"]', 'Enter');

await page.waitForTimeout(60000); // Wait for 60 seconds

await page.waitForSelector('[placeholder="Images"]');

const firstResultElement = await page.innerText('//*[@id="center_col"]');

console.log('First search result:', firstResultElement);

await browser.close();

} catch (error) {

console.error('An error occurred:', error);
  }

})();

</code></pre>

How to style function in javascript?

function makeMove(row, col) {
    if (!isGameStarted) return;

    const cell = document.querySelector(`.row:nth-child(${row + 1}) .cell:nth-child(${col + 1})`);
    if (cell.textContent !== "") return;

    if (currentPlayer === 1) {
        cell.textContent = "X";
        gameBoard[row][col] = "X";
    } else if (currentPlayer === 2) {
        cell.textContent = "O";
        gameBoard[row][col] = "O";
    }

    if (checkWin()) {
        const resultDiv = document.getElementById("message");
        resultDiv.textContent = "You won, " + getCurrentPlayerName() + "!";
        isGameStarted = false;
    } else if (checkDraw()) {
        const resultDiv = document.getElementById("message");
        resultDiv.textContent = "It's a draw!";
        isGameStarted = false;
    } else {
        currentPlayer = currentPlayer === 1 ? 2 : 1;
        const resultDiv = document.getElementById("current-player");
        resultDiv.textContent = "It's your turn " + getCurrentPlayerName();
    }
}

I have this part of my code. My question is how can I style getCurrentPlayerName()? “It’s your turn” needs to be by default, but I need to highlight player name. For example, different color and different font size. In my html I just have divs #message and #current-player, I did everything in javascript.

Recover password bypass

in my web application, I have a password recovery functionality. If a wrong security question is provided, the server returns an error message and sets the success flag to false in the JSON response. However, if someone intercepts the response and modifies it to set the error message to null and success to true, they can bypass the security check.

tech :.net mvc

i tried this solution:
Don’t do password recovery in two steps. Ask for the security question alongside the new password, and check the answer to the security question in the server immediately before the password is changed, as a part of the same request/response cycle.

problem faced: it works .but after intercepting it gives message ‘password recovered’ beacause we are changing response sent by server .though password does not actually changes.is there any solution for this?

Could not render UserVideo on WebRTC Video Chat App

I am working on WebRTC Video Chat App here is my code

Here is the Code for SocketContent.js

import React, {createContext, useState, useRef, useEffect} from 'react';
import {io} from 'socket.io-client';
import Peer from 'simple-peer';

const SocketContext =createContext();

const socket = io('http://localhost:5000');

const ContextProvider = ({children}) => {

    const[stream, setStream] = useState();
    const [me , setMe] = useState('');
    const [call, setCall] = useState({});
    const [callAccepted, setCallAccepted] =useState(false);
    const [callEnded, setCallEnded] = useState(false);
    const [name, setName] = useState('')

    const myVideo =useRef();[enter image description here](https://i.stack.imgur.com/5Iepi.jpg)
    const userVideo =useRef();
    const connectionRef =useRef();

    useEffect(()=>{
            navigator.mediaDevices.getUserMedia({video: true, audio: true})
                .then((currentStream) => {
                    setStream(currentStream);
                
                    if(myVideo.current){
                        myVideo.current.srcObject = currentStream;
                    }

                   
                });
                socket.on('me' , (id)=> setMe(id));

                socket.on('calluser', ({from, name: callerName, signal})=>{
                    setCall({isReceivedCall: true, from, name: callerName, signal})
                });
    }, []);



    const answerCall = () => {
        setCallAccepted(true)

        const peer = new Peer({initiator:false, trickle:false, stream})

        peer.on('signal', (data)=>{
            socket.emit('answerCall', { signal: data, to: call.from });
        });
        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream;
        });

        peer.signal(call.signal);

        connectionRef.current = peer;
    }

    const callUser = (id) => {
        const peer = new Peer({initiator:true, trickle:false, stream})
        
        peer.on('signal', (data)=>{
            socket.emit('calluser', {userToCall: id, signalData: data, from:me, name });
        });
        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream;
        });

        socket.on('callaccepted', (signal) =>{
            setCallAccepted(true);

            peer.signal(signal);
        });

        connectionRef.current = peer;
    }

    const leaveCall = () => {
        setCallEnded(true);

        connectionRef.current.destroy();

        window.location.reload();
    }
    return (
        <SocketContext.Provider value = {{
            call,
            callAccepted,
            myVideo,
            userVideo,
            stream,
            name,
            setName,
            callEnded,
            me,
            callUser,
            leaveCall,
            answerCall,

        }}>
            {children}
        </SocketContext.Provider>
    )
}

export {ContextProvider, SocketContext};

However UserVideo is not rendering.

Javascript document.addEventListener is not being called if its used in another package with the same event name

I have this React hook to notify in case the user clicked outside

function useOutsideAlerter(ref: any, callback: () => void) {
    useEffect(() => {
        function handleClickOutside(event: {target: any}) {
            if (!ref?.current?.contains(event.target)) {
                callback();
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [ref, callback]);
}

and its using document.addEventListener to get notified when user click on the DOM object,

the same hook is used in two packages in the same web app, according to this hierarchy:

Website => 1st package => 2nd package

the eventListener is not being triggered in 2nd package, and its being triggered in the first package,

I tried to change from document to window in 1st package and it worked, but I need understand the root cause of this bug if someone can help,

thanks

owl carousel behaving vertically when the page is first loaded

[![][1]][1]
when the page is first visited it would be like this after refresh it behaves normally as horizontal slider,it also react like this in desktop screens after refresh or resize only it behaves properly
[1]: https://i.stack.imgur.com/aOnNW.jpg

                <div class="owl-carousel slider">
                    <div class="item slider-items">
                        <img src="./assets/images/bp5c.png"alt=''>
                    </div>
                    <div class="item slider-items">
                        <img src="./assets/images/bp5r.png"alt=''>
                    </div>
                    <div class="item slider-items">
                        <img src="./assets/images/bp5l.png"alt=''>
                    </div>
                </div>
$(document).ready(function() {
    if ($('.owl-carousel').length) {
    $('.owl-carousel').owlCarousel({
      loop: true,
      items: 1,
      autoWidth: true,
      margin: 10,
      center: true,
      smartSpeed: 1500,
      autoplay: true,
      autoplayTimeout: 3000,
      autoplayHoverPause: true,
      responsive: {
        1000: {
          items: 3,
          margin:94
        },
      }
    });
  }
}