How to speed up Three.js file when using document.getElementById

I just started using Three.js and created a program which made a globe. When I run this just in the window without using document.getElementById it runs very fast. However, use it in an abridged code below it is incredibly slow.

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/Addons.js';
import getStarField from './getStarfield.js';
import {getFresnelMat} from './getFresnelMat.js';

export function initializeThreeJS(){
var container = document.getElementById('world');

// a scene 

const scene = new THREE.Scene();
scene.background = new THREE.Color( 'gainsboro' );

var camera = new THREE.PerspectiveCamera( 30, container.clientWidth/ container.clientHeight );
    camera.position.set( 2, 5, 10 );
    camera.position.z = 25;


var renderer = new THREE.WebGLRenderer( {antialias: true} );
renderer.setSize( container.clientWidth, container.clientHeight);
renderer.setAnimationLoop( animate );
container.appendChild( renderer.domElement );

const earthGroup = new THREE.Group();
scene.add(earthGroup);

/* 
* Starfield tb implemented
*/

/*
* temporary lighting
*/
var controls = new OrbitControls( camera, renderer.domElement );
    controls.enableDamping = true;

var ambientLight = new THREE.AmbientLight( 'white', 0.5 );
    scene.add( ambientLight );

var light = new THREE.DirectionalLight( 'white', 0.5 );
    light.position.set( 1, 1, 1 );
    scene.add( light );
/* 
* Orbit Controls tb implemented
*/
const loader = new THREE.TextureLoader();
/* 
* Earth Geometry
*/
const geometry = new THREE.IcosahedronGeometry(1, 12);
const material = new THREE.MeshPhongMaterial({
    map: loader.load("./textures/00_earthmap1k.jpg"),
    specularMap: loader.load("./textures/02_earthspec1k.jpg"),
    bumpMap: loader.load("./textures/01_earthbump1k.jpg"),
    bumpScale: 0.04,
  });

const earthMesh = new THREE.Mesh(geometry, material);
earthGroup.add(earthMesh);


/* 
* Function Loop 
*/
function animate() {
    requestAnimationFrame(animate);

    // Rotate the cube
    // Render the scene
    renderer.render(scene, camera);
}

}

Here is the html section as well

<body>
  <div id="container">
    <div id="world" ></div>
</div>
</body>

Is there any way to speed this up or to let me know if I’m using the map function wrong because that seems to be slowing down the program a lot?

Javascript scroll animation of transform3d

I want to try and create this mouse tracking event – which causes a transform effect on the block and contents – and also adds this flash light

I’ve tried creating a basic set of blocks and transform and mouse tracking functions.

enter image description here

https://jsfiddle.net/qzo3ck5m/21/

html

<div class="container">
  <div class="block">Static</div>
  <div class="block moved">Moved</div>
  <div class="block">Static</div>
</div>

js

var myCircle = $(".moved")[0];
setTranslate(-32.277%, 2.465%, 0, myCircle);

function setTranslate(xPos, yPos, zPos, el) {
console.log("test")
el.style.transform = `translate3d(${xPos}, ${yPos}, ${zPos}) scale3d(1, 1, 1) rotateX(20deg) rotateY(10deg) rotateZ(0deg) skew(0deg, 0deg)`;
}

css

.container {
  padding: 40px;
}

.block {
  width: 60px;
  height: 60px;
  background-color: skyblue;
}

.moved {
  background-color: pink;
  will-change: transform;
  transform: translate3d(-32.277%, 12.465%, 0px) scale3d(1, 1, 1) rotateX(20deg) rotateY(10deg) rotateZ(0deg) skew(0deg, 0deg);
}

//mouse tracking

function coordinate(event) {
    let x = event.clientX;
    let y = event.clientY;
    document.getElementById("X").value = x;
    document.getElementById("Y").value = y;
}

How to Ensure Text Stays Below a Stacked X-Axis in LightningChartJS with React-TypeScript?

I am using lightningChartJs

with React-TypeScript, and I want to know,

according to my use case I have a chart with 3 stacked axises, on the x axis.

the first x-Axis is normal, the second is invisible but not with setVisible, the other way , with this snippet

  xAxisNucleus.setTickStrategy(AxisTickStrategies.Numeric, (tickStrategy) =>
    tickStrategy.setTickStyle((ticks) => ticks.setGridStrokeStyle(emptyLine)),
  );

and the third one is normal

enter image description here

the trouble is with the words underneath the middle chart

enter image description here
enter image description here

in different sizes it become on top of the chart as the image above.

how can I add text to behave as if it was the x-axis so that it would always fit underneath it,

full snippet for drawing textbox at position:

  const xAxis = xAxisNucleus;
  const yAxis = chart.getDefaultAxisY();
  hideAxis(xAxis);

  xAxis.setMouseInteractions(false)

  // notes
  const textBox2 = chart
    .addUIElement(UIElementBuilders.TextBox, { x: xAxis, y: yAxis })
    .setOrigin(UIOrigins.RightBottom)
    .setVisible(true)
    .setText('Notes')
    .setTextRotation(270);

  textBox2.setMouseInteractions(false); // preventing from user to drag

  textBox2.setBackground((background) =>
    background.setFillStyle(emptyFill).setStrokeStyle(emptyLine),
  );

  const updatePosition = (textBox: UITextBox & UIElement, chart: ChartXY) => {
    textBox.setPosition({ x: 5.7, y: chartSliders[0] - (chartSliders[1] - chartSliders[0]) * 0.05 }); // value[0] - (value[1] - value[0]) * 0.05
  };
  updatePosition(textBox2, chart);

  chart.axisY.setMouseInteractions(false);
  chart.axisY.setTickStrategy(AxisTickStrategies.Numeric, (tickStrategy) =>
    tickStrategy.setTickStyle((ticks) => ticks.setGridStrokeStyle(emptyLine)),
  );

  // Haguide
  const textBox3 = chart.addUIElement(UIElementBuilders.TextBox, { x: xAxis, y: yAxis })
    .setOrigin(UIOrigins.LeftBottom)
    .setPosition({ x: 4.3, y: chartSliders[0] - (chartSliders[1] - chartSliders[0]) * 0.05 })
    .setVisible(true)
    .setText('HaGuide')
    .setTextRotation(270);

  textBox3.setMouseInteractions(false); // preventing from user to drag

  textBox3.setBackground((background) =>
    background.setFillStyle(emptyFill).setStrokeStyle(emptyLine),
  );
  textBox3.setTextFont((font) => font.setSize(8));
  textBox2.setTextFont((font) => font.setSize(10));

Bug in Chrome with javascript open existing page in new window and then copy text

In my version of Chrome “Version 128.0.6613.85 (Official Build) (64-bit)” I can get it to crash to desktop every time I open an existing page using JavaScript and modify it using “document.write.” I have submitted the issue to Google Chrome via About. Just wondering if its repeatable or can be solved another way.

Create a blankpage.html, say with just the html/head/body tags in, but seems it can be anything. Then from another page run this JavaScript:

var myWin = open("blankpage.html"); 
myWin.document.open();
myWin.document.write("<html><body>Hello</body></html>");
myWin.document.close(); 

Now in the new window that opens, highlight the ‘Hello’ text and do a copy (CTRL+C) on it.
This results in my Chrome Browser crashing to desktop every time. Seems to work ok in Edge.

How to trigger an analytic when component gets re-rendered?

I need to trigger an analytic when a component gets re-rendered because someones searches in the search bar. When someone searches, the component LibraryManager gets re-rendered to address that search value. I need to trigger an analytic when that component gets re-rendered. The best way to trigger that analytic is in the render function but I’m told not to add the trigger to the render function because of side effects. Is there another function I can use to add the analytics trigger in lit?

Unable to implement mfa in Supabase

I am using supabase to implement MFA in my auth but always encounter “Missing Sub Claim error”
Server Logs

I use custom claims during signup to store mfa status and factor ID during mfa enroll during signup so user object becomes
Supabase dashboard

First the user has to sign In successfully to reach the otp page and a session cookie is successfully set in my browser
Frontend Cookie

Then I use this code from backend

//auth.js
export const mfaVerify = async (fId, otp) => {
  try {
    const { data, error } = await supabase.auth.mfa.challengeAndVerify({
      factorId: fId,
      code: otp,
    });

    if (error) {
      console.log("err is", error);
      throw new Error(`MFA Verification failed: ${error.message}`);
    }

    if (!data || !data.access_token) {
      console.log("NO data");
      throw new Error("MFA Verification failed: Missing access token or data");
    }

    return { data, error: null };
  } catch (err) {
    console.log("MFA Verification Error:", err);
    return { data: null, error: err };
  }
};

//authRouter.js
authRouter.post("/mfaVerify", async (req, res, next) => {
  try {
    const { otp, mfaID } = req.body;
    console.log("OTP is", otp);
    console.log("id is", mfaID);
    // const { error } = otpValid({ otp, mfaID });
    // const clientType = req.headers["client-type"];
    // if (error)
    //   return res
    //     .status(400)
    //     .json({ status: "false", message: "Incorrect OTP entered" });
    const resp = await mfaVerify(mfaID, otp);
    console.log("resp is", resp);
    if (resp.error)
      return res
        .status(401)
        .json({ status: false, message: "Incorrect OTP entered" });
    else {
      if (clientType === "react-native") {
        res.status(200).json({
          access_token: resp.data.access_token,
          refresh_token: resp.data.refresh_token,
          expires_in: resp.data.expires_in,
        });
      } else {
        res
          .cookie("access", resp.data.access_token, {
            httpOnly: true, // Ensures the cookie is only accessible via HTTP(S), not JavaScript
            secure: true, // Ensures the cookie is only sent over HTTPS
            maxAge: resp.data.expires_in * 1000, // Sets the cookie expiration time
            sameSite: "lax",
            partitioned: true,
            signed: true,
          })
          .cookie("refresh", resp.data.refresh_token, {
            httpOnly: true, // Accessible only by the web server
            secure: true, // Transmit cookie only over HTTPS
            maxAge: 30 * 24 * 60 * 60 * 1000, // Refresh token typically has a longer lifespan (e.g., 30 days)
            sameSite: "lax", // Prevents CSRF attacks
            partitioned: true, // Ensures cookie isolation
            signed: true, // Prevents tampering with the cookie
          })
          .status(200)
          .json({
            status: true,
            message: "Sign in successfull",
            adminDat: !!resp.data.user.app_metadata.claims_admin,
          });
      }
    }
  } catch (err) {
    console.log(err);
    return res.status(500).json("Internal Server Error");
  }
});

And this code is in frontend

//Auth.ts
export const verifyMyOTP = async (otp: string, mfaID: string, router: any) => {
    try {
        const resp = await axios.post(
            `${String(import.meta.env["VITE_BASE_URL"])}/auth/mfaVerify`,
            { otp, mfaID },
            {
                withCredentials: true,
            }
        );
        if (resp.data && resp.data.status) {
            console.log(resp.data);
            const role = resp.data.adminDat ? "admin" : "user";
            router.navigate({ to: `/${role}/Home` });
            return { status: true, message: "OTP CONFIRMED" };
        } else {
            console.log(resp.data);
            return { status: false, message: "OTP INVALID" };
        }
    } catch (error) {
        if (error.response && error.response.status === 400) {
            console.log("Invalid code");
            return { status: false, message: "Invalid Code" };
        }
    }
};

//AuthCard.tsx

const submitOTP = async () => {
        if (!/^d{6}$/.test(mfaData.otp)) return message.error("Invalid OTP");
        try {
            const res = await verifyMyOTP(mfaData.otp, mfaData.mfaID, router);
            if (res?.status) return message.success(res.message);
        } catch (error) {
            console.log(error);
            message.error("error");
        }
    };
    enter code here

<div className="flex items-center justify-center mt-5 flex-col">
                            <div className="flex flex-col items-center justify-center text-center space-y-2">
                                <div>
                                    <h2 className="font-semibold text-3xl">MFA</h2>
                                </div>
                                <div className="flex flex-row text-sm font-medium text-muted">
                                    <p>
                                        Enter the time sensitive 6 digit code from your
                                        authenticator app
                                    </p>
                                </div>
                            </div>
                            <div className="mt-5 m-7">
                                <Input.OTP length={6} {...sharedProps} />
                            </div>
                            <button
                                onClick={async () => {
                                    await submitOTP();
                                }}
                                disabled={mfaData.otp.length === 6 ? false : true}
                                className="inline-block w-full sm:w-[282px] ml-4 mr-4 rounded bg-blue-400 px-5 py-3 font-medium text-white shadow-md shadow-blue-500/20 hover:bg-blue-500 hover:text-white"
                            >
                                Sign in
                            </button>
                            <p className="text-center text-gray-500 mt-4">
                                Need help? Please contact Support.
                            </p>
                        </div>

Can someone please help me solve my problem or give me some debugging tips to solve this problem

Toggling audio in React without re-rendering component

I have built a game using React (and Matter JS and p5.js). It mainly has 2 variables, score (increments everytime goal is hit) and timer (decrements every second).
I want music to play in the background if user wants. So I have an audio toggle button. But I have to use a state variable to ensure the audio is playing/pausing as required. Such a state update re-renders the component and thus resets the score and timer variables.

Is there any way to toggle the audio in React without using a state variable, avoiding re-rendering the component, or at least some way for React to know that if it gets re-rendered while in the “/game” page, it shouldn’t reset the score and timer?

Here is the part of the code that handles the audio:

            audioButton = p.createImg(audioRef.current.paused ? audioOff : audioOn, "audio button");
            audioButton.position(20, p.height - 50);
            audioButton.size(30, 30);
            audioButton.mouseClicked(() => {
                if (audioRef.current.paused) {
                    audioRef.current.play();
                } else {
                    audioRef.current.pause();
                }
                setPlaying(prevPlaying => !prevPlaying);
                setTimeout(() => {
                    audioButton.elt.src = audioRef.current.paused ? audioOff : audioOn;
                }, 0);
            });

My score and timer are defined as follows:

//GLOBAL VARIABLES
let score = 0;
let timer = 0;

function Game() {  
    score = 0;
    timer = 0;


    /*REST OF THE GAME LOGIC...*/
}

I have already tried making score and timer state variables instead of global variables. There must be some p5.js issue in that case which doesn’t update the score and the timer at ALL (they remain as 0 and 42 respectively).

Any help would be appreciated, thanks!

Tabulator list editor not set value

I’m lost, where is the problem.

I have external source for editor “list”, but I have authorization in headers, so I can’t use built in functionality for external ajax requests.

My values model:

[
    { id: 1, name: 'USA' },
    { id: 2, name: 'Canada' },
]

Definition:

{ field: "country", title: "Country", editor:"list", editorParams: codeListEditor("country"), formatter: "codelist" },

EditorParams:

const codeListEditor = (name: string) => {
  return {
    values: getCodeListEditor(name),
    clearable: true,
    maxWidth: true,
    freetext: false,
    allowEmpty: true,
    listOnEmpty: true,
    filterDelay: 100,
    autocomplete: true,
    multiselect: true,
    filterFunc: (term) => getCodeListEditor(name, term),
    itemFormatter: (label, value, item) => {
      return item.name;
    }
  }
}

Everything works fine, but after select I have undefined value in model.

tabulator.on('cellEdited', () => {
    console.log(cell.getRow().getData()); // Here I have selected value undefined.
});

It’s a problem because it’s object? How can I say what I want set to the model? My codelist formatter do only return value.name, but in formatter is value undefined too.

Formatter:

Tabulator.extendModule("format", "formatters", {
  codelist: (cell) => {
    return cell.getValue()?.name;
  }
});

Is this the correct way of deciding the type of “…rest” prop?

I’ve tried to make the ‘…rest’ prop be of a certain type. Either LinkProps or NavLinkProps.
It works correctly, when $type: "navLink" then it has access to fields specified in NavLinkProps, and when $type: "link" then it doesn’t have access to them anymore. Just as expected. However, i’m still wondering – is this the correct way to implement something like this? Or maybe there are better ways to do it?

import { Link, LinkProps, NavLink, NavLinkProps } from "react-router-dom";
import styled, { css } from "styled-components";

type RegularLinkProps = {
  $type: "link";
} & LinkProps;

type NavigationalLinkProps = {
  $type: "navLink";
} & NavLinkProps;

const StyledCustomLink = styled(Link).attrs<
  { $type: "link" | "navLink" } & (LinkProps | NavLinkProps)
>(({ $type }) => ({
  as: $type === "link" ? Link : NavLink,
}))`
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  position: relative;
  overflow: hidden;
  text-decoration: none;
  transition: color 0.2s, fill 0.2s;
  ${({ $type }) =>
    $type === "navLink" &&
    css`
      padding: 3rem;
    `};
  &::after {
    content: "";
    position: absolute;
    left: -100%;
    top: calc(100% - 2px);
    width: 100%;
    height: 2px;
    background-color: var(--color-dark-grey);
    transition: transform 0.2s;
  }
  &:hover {
    color: var(--color-dark-grey);
    fill: var(--color-dark-grey);
    &::after {
      transform: translateX(100%);
    }
  }
`;
export function CustomLink({
  children,
  $type,
  ...rest
}: RegularLinkProps | NavigationalLinkProps) {
  return (
    <StyledCustomLink $type={$type} {...rest}>
      {children}
    </StyledCustomLink>
  );
}

How does one remove an infinite issues/vulnerabilities loop while setting up a react app/project?

I’ve just started a React project using npx create-react-app project. This installs all the relevant files and dependencies required for a react project but there were some vulnerabilities identified :

      162 vulnerabilities (1 low, 122 moderate, 36 high, 3 critical)

      To address issues that do not require attention, run:     
        npm audit fix

      To address all issues (including breaking changes), run:  
        npm audit fix --force 

However, upon running npm audit fix --force they still raised the following:

      8 vulnerabilities (2 moderate, 6 high)

      To address all issues (including breaking changes), run:  
        npm audit fix --force

Upon running npm audit fix --force again, I’m right back to where I’m started, with:

      162 vulnerabilities (1 low, 122 moderate, 36 high, 3 critical)

      To address issues that do not require attention, run:     
        npm audit fix

      To address all issues (including breaking changes), run:  
        npm audit fix --force 

Is there a way to permanently remove all vulnerabilities or do I just have to live with 8 vulnerabilities instead of 162?

P.S.: I currently have Node.js v21.1.0 and npm v10.2.0. And this project is supposed to be a e-commerce website for an actual business that will have to handle payments so preferably, I don’t want it to break due to some vulnerabilities if I could help it.

How to update nested object state in react , initialize with {} , then json data that I got from api

How to update nested object state in react , initialize with {} , then json data that I got from api.

Why this code is not working:

import React, { useEffect, useState } from 'react';
import { useQuery } from 'react-query';
const App = () => {
  const [testData, setTestData] = useState({});
 
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch("http://localhost:8080/api/v1/recommendations");
        const result = await response.json(); 
        setTestData(result);
      } catch (err) {
        console.error(`Found error while fetching data: ${err}`);
      }
    };

    fetchData();
  }, []); 


  useEffect(() => {

    setTestData(prevState => {
      const updatedData = {
        ...prevState,
        recommendation: {
          ...prevState.recommendation,
          rules: prevState.recommendation.rules.map(rule => {
            if (rule.scenario_name === "data_rule") {
              return {
                ...rule,
                passwhen: {
                  ...rule.passwhen,
                  STATE: "INDIA"
                }
              };
            }
            return rule;
          })
        }
      };
      return updatedData;
    });
  }, []);

  useEffect(() => {
    console.log("data", testData);
  }, [testData]);

  return (
    <div>
      <pre>{JSON.stringify(testData, null, 2)}</pre>
    </div>
  );
};

export default App;


I’m working on a React application where I need to update the state of a nested object. Initially, my state is set to an empty object {}. I fetch JSON data from an API that should populate this nested state.
After fetching the data, I want to update specific keys within this nested object. However, I’m facing issues with my approach. In the provided example, the state isn’t being initialized properly, leading to errors when attempting to update nested properties.
How should I properly initialize and update my nested object state with the fetched JSON data, ensuring that the state update is handled correctly and immutably?

Api Data

{
    "recommendation": {
        "rules": [
            {
                "scenario_name": "duplicate_check",
                "scenario_target_query": "SELECT * FROM beat2020.orders_info",
                "columns": [
                    "ORDERNO"
                ],
                "tgt_lvl_key": [
                    "ORDERNO"
                ],
                "idx": 0
            },
            {
                "scenario_name": "null_check",
                "scenario_target_query": "SELECT ORDERNO, QUANTITY_ORDERED, PRICE_EACH, SALES_PRICE, ORDERDATE, STATUS FROM beat2020.orders_info",
                "columns": [
                    "ORDERNO",
                    "QUANTITY_ORDERED",
                    "PRICE_EACH",
                    "SALES_PRICE",
                    "ORDERDATE",
                    "STATUS"
                ],
                "idx": 1
            },
            {
                "scenario_name": "data_validation",
                "scenario_source_query": "SELECT ORDERNUMBER, QUANTITYORDERED, PRICEEACH, ORDERLINENUMBER, SALES, FORMAT(ORDERDATE, 'MM-DD'), CASE WHEN STATUS IS NULL THEN 1 ELSE 2 END, QTR_ID, MONTH_ID, YEAR_ID, PRODUCTLINE, MSRP, PRODUCTCODE, CUSTOMERNAME, PHONE, ADDRESSLINE1, ADDRESSLINE2, CITY, IF(STATE IS NULL, 'US', STATE), POSTALCODE, COUNTRY, TERRITORY FROM beat2020.orders",
                "scenario_target_query": "SELECT ORDERNO, QUANTITY_ORDERED, PRICE_EACH, ORDERLINENO, SALES_PRICE, ORDERDATE, STATUS, QTR_ID, MONTH_ID, YEAR_ID, PRODUCTLINE, MSRP, PRODUCTCODE, CUSTOMERNAME, PHONE, ADDRESSLINE1, ADDRESSLINE2, CITY, STATE, POSTALCODE, COUNTRY, TERRITORY FROM beat2020.orders_info",
                "columns": [
                    "ORDERNUMBER",
                    "QUANTITYORDERED",
                    "PRICEEACH",
                    "ORDERLINENUMBER",
                    "SALES",
                    "ORDERDATE",
                    "STATUS",
                    "QTR_ID",
                    "MONTH_ID",
                    "YEAR_ID",
                    "PRODUCTLINE",
                    "MSRP",
                    "PRODUCTCODE",
                    "CUSTOMERNAME",
                    "PHONE",
                    "ADDRESSLINE1",
                    "ADDRESSLINE2",
                    "CITY",
                    "STATE",
                    "POSTALCODE",
                    "COUNTRY",
                    "TERRITORY"
                ],
                "src_lvl_key": [
                    "ORDERNUMBER"
                ],
                "tgt_lvl_key": [
                    "ORDERNO"
                ],
                "idx": 2
            },
            {
                "scenario_name": "data_rule",
                "scenario_target_query": "SELECT * FROM beat2020.orders_info",
                "passwhen": {
                    "ORDERDATE": "DATE MM-DD",
                    "STATUS": "IN 1,2",
                    "STATE": "IN US"
                },
                "idx": 3
            }
        ]
    }
}

when i try to use jsPDF and html2canvas to build a pdf from my webpage, it does work, but everything is smaller, if res is 1080×800 the pdf is fine

i’m using the below function
`const saveAsPDF = async () => {
const pdf = new jsPDF({
orientation: ‘p’,
unit: ‘mm’,
format: ‘a4’
});

const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const margin = 15; // Margin around the content

// Function to add the header with the border, logo, and title
const addHeaderToPDF = () => {
  const borderMargin = 5;
  const borderWidth = pageWidth - 2 * borderMargin;
  const borderHeight = pageHeight - 2 * borderMargin;
  const borderRadius = 5; // Rounded corners

  // Draw the rounded border
  pdf.setLineWidth(0.5);
  pdf.setDrawColor(128, 128, 128);
  pdf.roundedRect(borderMargin, borderMargin, borderWidth, borderHeight, borderRadius, borderRadius, 'D');

  // Add the logo
  const logoWidth = 25; // Adjust logo size
  const logoHeight = 10;
  const logoYPosition = borderMargin + 10; // Position logo

  pdf.addImage(ClientLogo, 'PNG', (pageWidth - logoWidth) / 2, logoYPosition, logoWidth, logoHeight);

  // Add the title
  pdf.setFontSize(18);
//   pdf.setFont('helvetica', 'bold');
//   const title = `Onboarding info for ${payload.FIRST_NAME || ''} ${payload.MIDDLE_NAME || ''} ${payload.LAST_NAME || ''}`.trim();
//   pdf.text(title, pageWidth / 2, logoYPosition + logoHeight + 10, { align: 'center' });
};

// Function to add content to PDF
// const addContentToPDF = async (contentId, yPosition) => {
//   const content = document.getElementById(contentId);
//   if (content) {
//     const children = Array.from(content.children);

//     pdf.setFontSize(14);

//     for (const child of children) {
//       const canvas = await html2canvas(child, { scale: 2, useCORS: true });
//       const imgHeight = (canvas.height * (pageWidth - 2 * margin)) / canvas.width;

//       if (yPosition + imgHeight > pageHeight - margin) {
//         pdf.addPage();
//         addHeaderToPDF();
//         yPosition = margin;
//       }

//       const imgData = canvas.toDataURL('image/jpeg', 0.8);
//       const imgWidth = pageWidth - 2 * margin;

//       pdf.addImage(imgData, 'JPEG', margin, yPosition, imgWidth, imgHeight);
//       yPosition += imgHeight;
//     }
//   }
//   return yPosition;
// };
const addContentToPDF = async (contentId, yPosition) => {
  const content = document.getElementById(contentId);
  if (content) {
    const children = Array.from(content.children);
    const spaceAbove = 20; // Space to leave at the top for the logo and header

    pdf.setFontSize(14);

    for (const child of children) {
      const canvas = await html2canvas(child, { scale: 2, useCORS: true });
      const imgHeight = (canvas.height * (pageWidth - 2 * margin)) / canvas.width;
      const imgWidth = pageWidth - 2 * margin;

      // Add space above if it's the first child or if it's a new page
      if (yPosition === margin) {
        yPosition += spaceAbove;
      }

      if (yPosition + imgHeight > pageHeight - margin) {
        pdf.addPage();
        addHeaderToPDF(); // Add header on new page
        yPosition = margin + spaceAbove; // Leave space at the top for the logo
      }

      const imgData = canvas.toDataURL('image/jpeg', 0.8);

      pdf.addImage(imgData, 'JPEG', margin, yPosition, imgWidth, imgHeight);
      yPosition += imgHeight;
    }
  }
  return yPosition;
};


// Function to add multiple sections to the PDF
const addSectionsToPDF = async (sections) => {
  let yPosition = margin+10;

  for (const section of sections) {
    if (section === 'otherReference') {
      pdf.addPage();
      addHeaderToPDF();
      yPosition = margin;
    }
    console.log(section)
    if (section === 'images-content') {
      console.log("inside image")
      pdf.addPage();
      addHeaderToPDF();
      yPosition = margin;
    }
    yPosition = await addContentToPDF(section, yPosition);
    yPosition += margin;
    if (yPosition + margin > pageHeight) {
      pdf.addPage();
      addHeaderToPDF();
      yPosition = margin;
    }
  }
};

addHeaderToPDF();
await addSectionsToPDF(['view-auth-content', 'images-content']);

// Save the PDF
pdf.save(`${payload.FIRST_NAME}_${data.transactionId}.pdf`);

};`

Once i do it in a default screen size the pdf is way small making it difficult to read, if i open console docked to my right side and set the resolution to 1080×800 the pdf is just fine

i have tried re-sizing the page to fit the given resolution and doesnt work well, my pdf is 2-3 pages long
please advise

Next js output: ‘export’ issue

My application is in Next js and my nex.config.js have the following params { output: ‘export’,}
when we are serving static build with nginx reverse proxy then for first time after login all the pages of my application are working fine but when i refresh on particular page then it redirects me to back to login page

i’m expecting is there the issue with how build is server as previously i was not using output export in next.cofig.js and it was directly served on server then this issue was not encountered so from code base may be this is not related.
i have tried to console and check my token after refresh and before too but token is always there in my application

Backend script in Nakama [closed]

I got a job in game company that uses Nakama as backend.
My assignment is to write a script, that will take data from open street map, about buildings by ID, that will be send to this script.

The only thing I have is a link for Nakama backend and login&password.

Problem is:

I don’t know how to do that. It wasn’t in the job description.

Question:

Can somebody send me links, that will push me into the right direction or explain how to add scripts to backend if I only have a link for the dashboard?

I tried looking up answer, but I can’t tell that it helped me