• maiweb v0.1.0
  • ★
  • Feedback

#qa

1 source tagged with this.

  • Stack Overflow - JavaScript Tagged Feed
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-08-03 13:09

    ↗

    I have a JSON file with a few entries, let's say: [ { "name": "John", "age": 30 }, { "name": "Kevin", "age": 22 } ] Now I have a <select class = "testing"> drop-down list that I append these entries (only the names from JSON file) and I give them the same class="common":...

    I have a JSON file with a few entries, let's say:

    [
        {
          "name": "John",
          "age": 30
        },
        {
          "name": "Kevin",
          "age": 22
        }
    ]
    

    Now I have a <select class = "testing"> drop-down list that I append these entries (only the names from JSON file) and I give them the same class="common":

    jQuery.getJSON('Persons.json', function(data){
      var sel_=jQuery(".testing");
      for (var i=0;i<data.length;i++){
        sel_.append('<option class="common">' + data[i].name + '</option>');
      }
    })
    .fail (function (){
      console.log("An error has occured.");
    })
    

    The problem is that I cannot manage to access these entries from <select class="testing"> because jQuery.getJSON() is an asynchronous function and they are created after I try to access them, because they don't exist yet.

    I don't want to access them inside the function jQuery.getJSON() function. I want this to be separated.

    I found on the Internet something about Promises and Mutations but I only managed to access the first entry (name="John") from <select>:

    function waitForElm(selector) {
            return new Promise(resolve => {
                if (document.querySelector(selector)) {
                    return resolve(document.querySelector(selector));
                }
    
                const observer = new MutationObserver(() => {
                    if (document.querySelector(selector)) {
                        observer.disconnect();
                        resolve(document.querySelector(selector));
                    }
                });
    
                // If you get "parameter 1 is not of type 'Node'" error, see https://stackoverflow.com/a/77855838/492336
                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            });
        }
    
               waitForElm('.common').then((elm) => {
                console.log('Element is ready');
                console.log(elm.textContent);
            });
        

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-08-02 21:00

    ↗

    <div> <div > <h1>first item </h1> <button>buy now</button> </div> <div > <h1>second item </h1> <button>buy now</button> </div> </div> I want to be able to locate the first button based on the text within the div. I tried the following code, but it seems to match both the...

    <div>
        <div >
            <h1>first item </h1>
            <button>buy now</button>
        </div>
        <div >
            <h1>second item </h1>
            <button>buy now</button>
        </div>
    </div>
    

    I want to be able to locate the first button based on the text within the div. I tried the following code, but it seems to match both the inner and outer div and so selects both buttons.

    await page
            .locator('div')
            .filter({has: page.getByRole('heading', {name: 'first item'})})
            .getByRole('button', {name: 'buy now'})
            .click();
    

    playwright ui screenshot

    Is there anyway to locate elements within nested divs based on some property of the inner div without using .nth()?


    Edit:

    It just occurred to me that I can use .last() on the div locator to get the innermost div

    await page.locator('div')
      .filter({has: page.getByRole('heading', {name: 'first item'})})
      .last()
      .getByRole('button', {name: 'buy'})
      .click();
    

    playwright ui 2

    Still, not sure if there's a better way to do this

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-08-02 07:16

    ↗

    How do I align my elements to be aligned how I want it in the photo? I have attached my current CSS and a photo of my page right now as well as a photo of what I want it to look like. Could someone help me align my sliders? @font-face { font-family: JetBrainsMono; src:...

    How do I align my elements to be aligned how I want it in the photo?

    I have attached my current CSS and a photo of my page right now as well as a photo of what I want it to look like.

    Original

    What I Want

    Could someone help me align my sliders?

    @font-face {
        font-family: JetBrainsMono;
        src: url(fonts/JetBrainsMono-Regular.ttf);
    }
    
    header {
        margin-top: -0.65%;
        margin-left: -0.65%;
        height: 7%;
        width: 100%;
        background-color: black;
        position: fixed;
        display: flex;
        align-items: center;
    }
    
    #homeicon {
        width: 3%;
        height: auto;
        margin-left: 3%;
    }
    
    .headertext {
        font-family: JetBrainsMono;
        color: lightgrey;
        font-weight: bold;
        margin-left: 3%;
    }
    
    .headertext:hover {
        color: white;
        cursor: pointer;
    }
    
    .tabcontent {
        display: none;
    }
    
    .maincontent {
        padding-top: 2%;
        padding-left: 2.5%;
    }
    
    .heading {
        font-family: JetBrainsMono;
        color: black;
        font-weight: bold;
        font-size: 250%;
        text-decoration: underline;
    }
    
    #photoarea {
        float: right;
        padding-right: 10%;
    }
    
    .slider {
        writing-mode: vertical-lr;
        direction: rtl;
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-08-01 14:45

    ↗

    I am creating a hangman type word game. I have a list of over 5000 words which I have included in a hidden div in the page. <div id="words" style="display: none;"> word1,word2,word3....word5925,word5926,word5927,word5928,word5929 </div> <script type="text/javascript"...

    I am creating a hangman type word game. I have a list of over 5000 words which I have included in a hidden div in the page.

    <div id="words" style="display: none;">
        word1,word2,word3....word5925,word5926,word5927,word5928,word5929
    </div>
    <script type="text/javascript" src="getwords.js"></script>  
    

    I don't want my users to be able to view the source for the page and see the words, so I have the following code in my script, which loads the words into an array and should remove the words from the page:

    const element = document.getElementById("words");
    word = element.innerHTML;
    const words = word.split(",");
    element.innerText = "abcdefghijklmnopqrstuvwxyz";
    

    This populates the array with the words, but does not replace the text in the "words". I have tried adding the word defer after the script source in the HTML, and using innerHTML but that doesn't work either.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-31 20:17

    ↗

    My Vue App uses Quasar plugin. Quasar includes ripple directive, which my component uses. How can I test v-ripple has been used? <template> <q-item v-ripple>...</q-item> </template> I've been trying this way but it does not work. import { mount } from '@vue/test-utils' const...

    My Vue App uses Quasar plugin. Quasar includes ripple directive, which my component uses.

    How can I test v-ripple has been used?

    <template>
      <q-item v-ripple>...</q-item>
    </template>
    

    I've been trying this way but it does not work.

    import { mount } from '@vue/test-utils'
    
    const vRipple = { beforeMount: () => console.log('Ripple used')}
    mount(myComponent, {
      global: { plugins: [], directives: { Ripple: vRipple } }
    })
    

    This is my Vitest setup.

    import { config } from '@vue/test-utils'
    import { Quasar, LocalStorage } from 'quasar'
    
    config.global.plugins = [[Quasar, { plugins: { LocalStorage } }]
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-31 16:54

    ↗

    I am developing a UPI payment flow in a JSP application. When the page loads, I automatically trigger the UPI deep link. The UPI apps (Google Pay, PhonePe, Paytm, etc.) popup is displayed correctly. At the same time, I have a 7-minute countdown timer running on the same page...

    I am developing a UPI payment flow in a JSP application.

    When the page loads, I automatically trigger the UPI deep link. The UPI apps (Google Pay, PhonePe, Paytm, etc.) popup is displayed correctly.

    At the same time, I have a 7-minute countdown timer running on the same page (timescreen.jsp).

    The problem is that after the UPI popup is shown, but my timescreen.jsp navigates back after popup visible, causing the timer screen to restart instead of continuing.

    I am triggering the deep link inside $(document).ready() like this:

    window.apiInterval = null;
    let sdkp = null;
    let msgid = null;
    
    $(document).ready(function () {
    
        msgid = $('#messageid').val();
        sdkp = $('#sdkparams').val();
    
        if (sdkp && sdkp.trim() !== "") {
                window.open(sdkp, "_self");
        }
    });
    

    sdkp contains a UPI URI similar to:

    upi://pay?pa=...&pn=...&am=...

    Expected behavior:

    1. Open the UPI app directly, or display the UPI app chooser if multiple UPI apps (Google Pay, PhonePe, Paytm, etc.) are installed on the device.

    2. Once the UPI app or app chooser popup is displayed, the browser should remain on the current page (timescreen.jsp). It should not navigate back, reload, or restart the page.

    3. When the user returns from the UPI app, the same timer page should continue counting down from its current state without restarting.

    Actual behavior:

    When the UPI app chooser popup is displayed, the current page (timescreen.jsp) reloads or navigates back unexpectedly.

    Question:

    How can I successfully launch a UPI deep link while keeping the current page and countdown timer intact?

    Note: I cannot use an iframe due to CSP restrictions.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-31 07:55

    ↗

    TL;DR: is it a bad practice to use a stateful JS class? I am building a website using Node.js and Express, using MySQL as my DB. To use the DB I have made a simple CRUD MySQL ORM to retrieve and save data in the DB. Below is an excerpt of the utility class of my MySQL ORM...

    TL;DR: is it a bad practice to use a stateful JS class?

    I am building a website using Node.js and Express, using MySQL as my DB.

    To use the DB I have made a simple CRUD MySQL ORM to retrieve and save data in the DB.

    Below is an excerpt of the utility class of my MySQL ORM which will accept arguments and return queries suitable for MySQL:

    class Utils {
            constructor() {
                    this.operator = "";
                    this.columnStat = "*";
                    this.conditionStat = "";
                    this.conditionList = [];
                    this.limitStat = "LIMIT 1";
                    this.orderByStat = "";
                    this.queryStat = "";
                    this.pHolder = "";
                    this.pDataList = [];
            }
    
    }
    

    The above class saves all the data like operator (SELECT or INSERT), conditionList in the internal state, and uses it throughout the class.

    Is there any chances of conflict by using a stateful class in a single threaded Node.js?

    If two users tried to retrieve data at the same time, and changed the internal class properties, does it cause an error?

    Is it better to just create a stateless class?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-30 13:18

    ↗

    I want to open my game on the user´s device when the user visits my website and when the user has already installed my game on his mobile iOS/Android device. How can I open my game on the user´s device when the user visits my website? I have tried it with this code on my...

    I want to open my game on the user´s device when the user visits my website and when the user has already installed my game on his mobile iOS/Android device. How can I open my game on the user´s device when the user visits my website?

    I have tried it with this code on my website but it´s not working. My game is not opening on the iOS/Android device. Is it necessary to change something in my iOS project and Android project settings so that the game could get opened from my website?

    <script>
        (function() {
            
            const CONFIG = {
                
                appSchema: "nameofmyapp://app",
      
                
                playStore: "https://play.google.com/store/apps/details?id=com.company.nameofmyapp“,
                appStore: "https://apps.apple.com/app/id…“,   
                desktopFallback: "https://www.testwebsite.com"
            };
    
            const userAgent = navigator.userAgent || navigator.vendor || window.opera;
            let redirectUrl = CONFIG.desktopFallback;
            let isMobile = false;
    
            
            if (/android/i.test(userAgent)) {
                redirectUrl = CONFIG.playStore;
                isMobile = true;
            } else if ((/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) || (/Macintosh/.test(userAgent) && navigator.maxTouchPoints && navigator.maxTouchPoints > 1 && !window.MSStream)) {
                redirectUrl = CONFIG.appStore;
                isMobile = true;
            }
    
            
            if (isMobile) {
                
                window.location.href = CONFIG.appSchema;
    
                
                setTimeout(function() {
                    window.location.href = redirectUrl;
                }, 1500);
            } else {
                
                window.location.href = redirectUrl;
            }
        })();
    </script>
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-30 09:26

    ↗

    I have a CourseContext.jsx file that exports two things: CourseContext: the context created with createContext(). CourseContextProvider: a provider component that supplies the context value to all of its children. In index.js, I wrapped the App component with...

    I have a CourseContext.jsx file that exports two things:

    1. CourseContext: the context created with createContext().

    2. CourseContextProvider: a provider component that supplies the context value to all of its children.

    In index.js, I wrapped the App component with CourseContextProvider:

    <CourseContextProvider>
      <App />
    </CourseContextProvider>
    

    This means that App and all of its child components should have access to the context.

    Inside App.jsx, I imported useContext:

    import { useContext } from "react";
    

    Then I tried to access the context:

    const c = useContext(CourseContext);
    

    However, c is undefined instead of containing the expected context value.

    The nearest context provider in the above tree is CourseContextProvider wrapping /App.

    --Folder structure: All the files exist in the same directory

    // ============== index.js ================== //
    
    import React from 'react'
    import ReactDOM from 'react-dom/client'
    import App from './App.jsx'
    import CourseContextProvider from './CourseContext.jsx'
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <CourseContextProvider>
        <App />
      </CourseContextProvider>
    )
    
    
    //================ App.jsx ============== //
    import React from 'react';
    import { useState, useContext } from 'react'
    import ActiveCourses from './ActiveCourses.jsx'
    import CourseContext from './CourseContext.jsx'
    
    function App() {
      const c = useContext(CourseContext)
      console.log(`---${c}`)
      return (
    
        <div>
          <h1>Courses</h1>
          {c}
          <ActiveCourses />
        </div>
      )
    }
    
    export default App
    
    // ============== CourseContext.jsx ============= //
    
    import { useState, useContext, createContext } from 'react'
    
    export const CourseContext = createContext('default')
    
    function CourseContextProvider({ children }) {
      const activeCourses = [
        { courseId: 1, title: 'english', status:'active' },
        { courseId: 2, title: 'computer', status:'active' },
        { courseId: 3, title: 'marketing', status:'active' },
        { courseId: 4, title: 'geography', status:'active' },
      ]
      const notActiveCourses = [
        { courseId: 5, title: 'communicatoin', status:'notActive' },
        { courseId: 6, title: 'management', status:'notAactive' },
        { courseId: 7, title: 'urdu', status:'notAactive' },
      ]
    
      const list = { activeCourses, notActiveCourses }
    
      return (
        <CourseContext value={list}>
          { children } 
        </CourseContext>
      )
    }
    
    export default CourseContextProvider
    
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-30 07:18

    ↗

    So I have an Excel workbook that stores multiple sheets of data, and I've been using basic HTML, CSS and JS code to make charts out of the data, which is read using the XLSX library for Javascript, and displaying them on a website. The problem is that this file is stored...

    So I have an Excel workbook that stores multiple sheets of data, and I've been using basic HTML, CSS and JS code to make charts out of the data, which is read using the XLSX library for Javascript, and displaying them on a website.

    The problem is that this file is stored locally on my computer, and I need it to be stored somewhere where it can still be accessed by Javascript functions while also being somewhere it can be updated by users with no code experience (i.e. office workers that just know how to use Excel).

    Currently, as I said, the code is using a fetch function to get the file as shown:

    const workbook = XLSX.read(await (await fetch("./File.xlsx")).arrayBuffer());
    

    This works wonderfully but I just wanted to know if there was a quick and free way to store this data such that it can be accessed even when I host it using Netlify. I've tried using Google Sheets to store it but I can't get the authentication for the file to work.

    Like I said, I'm only using the basic HTML, CSS and JS functionalities, and I'd like not to add too many complex libraries or change my current code too much, so any alternative to getting the fetch line above to work would be the most appreciated. Any suggestions are welcome though.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-30 05:02

    ↗

    I'm creating a single-page web app, currently using oidc-client-ts and AWS Cognito for authentication, with static hosting e.g. by AWS CloudFront. (External users need to log in because OIDC tokens are needed for accessing backend APIs.) However internal users shouldn't need...

    I'm creating a single-page web app, currently using oidc-client-ts and AWS Cognito for authentication, with static hosting e.g. by AWS CloudFront. (External users need to log in because OIDC tokens are needed for accessing backend APIs.) However internal users shouldn't need to sign up and log in; the backend APIs can simply whitelist internal IP ranges.

    How can a SPA let some users opt to bypass authentication depending on their IPs?

    Ideally, I'd like all users to be able to share the links among each other (e.g., using query terms to arrive at various specific content within the app). I'm not sure whether it will be necessary to build and host two different versions of the SPA, either using a different domain for internal users, or on the same domain but serving different page versions depending on requester IP (although some clients/devices may alternate between access from both the internal network and from external networks).

    For external users (unless there is already a current token in local storage), the javascript needs to redirect the client to the identity provider (to perform a signup and/or login flow and be redirected back with token) before displaying content. For internal users, I'd prefer to make that redirect optional (since inconveniencing them to create and remember Cognito credentials is potentially redundant), but the javascript would need to know to defer the redirect.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-29 21:36

    ↗

    I'm making some JavaScript for a collapsible which expands on click using max-height and the active class, but I have no idea what's wrong with my code, I put my <script src="/main.js"> after </body> I'm not sure if that's the fix. But my collapsible isn't working. let...

    I'm making some JavaScript for a collapsible which expands on click using max-height and the active class, but I have no idea what's wrong with my code, I put my <script src="/main.js"> after </body> I'm not sure if that's the fix.

    But my collapsible isn't working.

    let headers = document.querySelectorAll(".update-header")
    
    headers.forEach((header) => {
      header.addEventListener('click', function() {
        let updateContent = this.closest(".update-content");
        updateContent.classList.toggle('active');
      });
    });
    .update-header {
      padding: 1px;
      box-sizing: border-box;
      background-image: var(--yellow-button);
      width: 100%;
      font-family: var(--content);
      font-size: small;
      font-weight: bolder;
      color: var(--color);
    
      &:hover {
        cursor: url(icons/cursor2.png), auto;
      }
    
      & strong {
        margin-block: 0;
    
        &::before {
          content: url('icons/after.png');
          padding-right: 5px;
        }
      }
    }
    
    .update-content {
      box-shadow: inset 0 2px 4px #7e4b1c;
      border-width: 2px 0 0 0;
      border-style: dashed;
      border-color: var(--border-color);
      padding: 3px;
      background-color: var(--bg-yellow);
      margin-block: 0;
      font-family: var(--content);
      font-size: small;
      height: fit-content;
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.5s ease-out;
    
      &.active {
        max-height: 500px;
      }
    }
    <div class="update">
      <div class="update-header"> <strong>??? 2026</strong></div>
      <p class="update-content"> placeholder </p>
    </div>

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-29 14:19

    ↗

    I use MapLibre+three.js + 3d-tiles-renderer to load 3d tiles. I tried the code as the sample. The sample's 3d tiles source is from Amazon. I change the 3d tiles source to "https://tile.googleapis.com/v1/3dtiles/root.json". It has a console error saying installHook.js:1 Error:...

    I use MapLibre+three.js + 3d-tiles-renderer to load 3d tiles. I tried the code as the sample. The sample's 3d tiles source is from Amazon. I change the 3d tiles source to "https://tile.googleapis.com/v1/3dtiles/root.json". It has a console error saying

    installHook.js:1 Error: Invalid LngLat latitude value: must be between -90 and 90"

    My code below is as in this CodePen demo

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Add 3D tiles using three.js</title>
        <meta property="og:description" content="Use a custom style layer with three.js to add 3D tiles to the map." />
        <meta property="og:category" content="3D Models & Buildings" />
        <meta property="og:created" content="2026-03-03" />
        <meta charset='utf-8'>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel='stylesheet' href='https://unpkg.com/maplibre-gl@6.0.0/dist/maplibre-gl.css' />
    
        <style>
            body { margin: 0; padding: 0; }
            html, body, #map { height: 100%; }
        </style>
    </head>
    <body>
    <script type="importmap">
        {
            "imports": {
            "three": "https://cdn.jsdelivr.net/npm/three@0.183.0/build/three.module.js",
            "three/examples/jsm/": "https://cdn.jsdelivr.net/npm/three@0.183.0/examples/jsm/",
            "3d-tiles-renderer": "https://cdn.jsdelivr.net/npm/3d-tiles-renderer@0.4.21/build/index.three.js"
            }
        }
    </script>
    <div id="map"></div>
    
    <script type="module">
        import * as maplibregl from 'https://unpkg.com/maplibre-gl@6.0.0/dist/maplibre-gl.mjs';
    
        import * as THREE from 'three';
        import { TilesRenderer } from "3d-tiles-renderer";
        import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
        import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
        import { KTX2Loader } from "three/examples/jsm/loaders/KTX2Loader.js";
    
        let scene,camera,renderer,mapInstance,tiles,tilesCamera;
    
        const map = new maplibregl.Map({
            container: 'map',
            style: 'https://tiles.openfreemap.org/styles/bright',
            zoom: 1,
            center: [0, 0],
            pitch: 60,
            maxPitch: 80,
            canvasContextAttributes: {antialias: true}
        });
    
        // Convert Cartesian coordinates to latitude and longitude
        function ecefToLngLatAlt(x, y, z) {
            const a = 6378137.0;
            const e2 = 6.69437999014e-3;
            const b = a * Math.sqrt(1 - e2);
            const ep2 = (a * a - b * b) / (b * b);
    
            const p = Math.sqrt(x * x + y * y);
            const th = Math.atan2(a * z, b * p);
            const lon = Math.atan2(y, x);
            const lat = Math.atan2(z + ep2 * b * Math.pow(Math.sin(th), 3), p - e2 * a * Math.pow(Math.cos(th), 3));
            const n = a / Math.sqrt(1 - e2 * Math.sin(lat) * Math.sin(lat));
            const alt = p / Math.cos(lat) - n;
    
            return {
                lng: (lon * 180) / Math.PI,
                lat: (lat * 180) / Math.PI,
                alt,
            };
        };
    
        /**
         * Load 3D model
         * @param {string} url Model URL
         * @param {number} altOffset Model altitude offset (set appropriate value to align with the ground)
         */
        async function load3dtiles(url, altOffset = 0) {
            let localTransform;
    
            function getModelTransform(coord, rotate= [Math.PI / 2, 0, 0]) {
                const modelAsMercatorCoordinate = maplibregl.MercatorCoordinate.fromLngLat([coord[0], coord[1]], coord[2]);
                return {
                    translateX: modelAsMercatorCoordinate.x,
                    translateY: modelAsMercatorCoordinate.y,
                    translateZ: modelAsMercatorCoordinate.z,
                    rotateX: rotate[0],
                    rotateY: rotate[1],
                    rotateZ: rotate[2],
                    scale: modelAsMercatorCoordinate.meterInMercatorCoordinateUnits(),
                };
            }
    
            function updateLocalTransform(modelOrigin= [0, 0, 0]) {
                const modelTransform = getModelTransform(modelOrigin);
                const axisX = new THREE.Vector3(1, 0, 0);
                const axisY = new THREE.Vector3(0, 1, 0);
                const axisZ = new THREE.Vector3(0, 0, 1);
                const rotationX = new THREE.Matrix4().makeRotationAxis(axisX, modelTransform.rotateX);
                const rotationY = new THREE.Matrix4().makeRotationAxis(axisY, modelTransform.rotateY);
                const rotationZ = new THREE.Matrix4().makeRotationAxis(axisZ, modelTransform.rotateZ);
                const scaleVec = new THREE.Vector3(modelTransform.scale, -modelTransform.scale, modelTransform.scale);
                localTransform = new THREE.Matrix4()
                    .makeTranslation(modelTransform.translateX, modelTransform.translateY, modelTransform.translateZ)
                    .scale(scaleVec)
                    .multiply(rotationX)
                    .multiply(rotationY)
                    .multiply(rotationZ);
            }
    
            // Initialize tiles
            function initTiles(url, sceneInst, cameraInst, rendererInst) {
                const gltfLoader = new GLTFLoader();
                const dracoLoader = new DRACOLoader();
                dracoLoader.setDecoderPath("https://unpkg.com/three@0.183.0/examples/jsm/libs/draco/");
                gltfLoader.setDRACOLoader(dracoLoader);
    
                const ktx2Loader = new KTX2Loader();
                ktx2Loader.setTranscoderPath("https://unpkg.com/three@0.183.0/examples/jsm/libs/basis/");
                ktx2Loader.detectSupport(rendererInst);
                gltfLoader.setKTX2Loader(ktx2Loader);
    
                tiles = new TilesRenderer(url);
                tiles.group.name = "tiles";
                sceneInst.add(tiles.group);
    
                tiles.setCamera(cameraInst);
                tiles.setResolutionFromRenderer(cameraInst, rendererInst);
    
                tiles.manager.addHandler(/\.(gltf|glb)$/g, gltfLoader);
    
                let loadedTileSetHandled = false;
                // Adjust model matrix
                const loadTileSet = () => {
                    if (loadedTileSetHandled) {
                        tiles?.removeEventListener("load-tileset", loadTileSet);
                        return;
                    }
    
                    const scale = 1;
                    const sphere = new THREE.Sphere();
                    tiles.getBoundingSphere(sphere);
                    const center = sphere.center.clone();
                    const root = tiles.root;
    
                    let m = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
                    // Get matrix
                    if (root.transform)  m = root.transform;
                    loadedTileSetHandled = true;
    
                    const { lng, lat, alt } = ecefToLngLatAlt(center.x, center.y, center.z);
                    map.jumpTo({ center: [lng, lat], zoom: 18, pitch: 60 });
                    updateLocalTransform([lng, lat, alt + altOffset]);
    
                    const rotationMat3 = new THREE.Matrix3().set(m[0], m[1], m[2], m[8], m[9], m[10], -m[4], -m[5], -m[6]);
                    const rotationMat4 = new THREE.Matrix4().setFromMatrix3(rotationMat3);
                    const moveToOrigin = new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z);
                    const finalMatrix = new THREE.Matrix4().multiplyMatrices(rotationMat4, moveToOrigin);
    
                    tiles.group.matrix.copy(finalMatrix);
                    tiles.group.matrixAutoUpdate = false;
                    tiles.group.updateMatrixWorld(true);
                };
                tiles.addEventListener("load-tileset", loadTileSet);
    
                // Update matrix
                updateLocalTransform();
            }
    
            const customLayer = {
                id: "3d-tiles",
                type: "custom" ,
                renderingMode: "3d" ,
                onAdd(mapArg, gl) {
                    camera = new THREE.PerspectiveCamera() ;
                    scene = new THREE.Scene();
    
                    const ambientLight = new THREE.AmbientLight(0xffffff, 3);
                    scene.add(ambientLight);
    
                    mapInstance = mapArg;
                    const canvas = mapArg.getCanvas();
                    renderer = new THREE.WebGLRenderer({
                        canvas,
                        context: gl,
                        antialias: true,
                    });
                    renderer.autoClear = false;
    
                    tilesCamera = new THREE.PerspectiveCamera();
    
                    initTiles(url, scene, tilesCamera, renderer)
                },
                render(_gl, args) {
                    // Update camera matrix and render
                    if (!camera || !renderer || !scene || !localTransform || !tilesCamera) return;
                    camera.projectionMatrix.fromArray(args.defaultProjectionData.mainMatrix);
                    camera.projectionMatrix.multiply(localTransform);
    
                    const P = new THREE.Matrix4().fromArray(args.projectionMatrix);
                    const invP = P.clone().invert();
                    const V = new THREE.Matrix4().multiplyMatrices(invP, camera.projectionMatrix);
    
                    tilesCamera.projectionMatrix.copy(P);
                    tilesCamera.matrixWorldInverse.copy(V);
                    tilesCamera.matrixWorld.copy(V).invert();
    
                    renderer.resetState();
                    renderer.render(scene, camera);
                    if (tiles) tiles.update();
                    mapInstance?.triggerRepaint();
                },
            };
    
            await map.once('style.load');
            map.addLayer(customLayer);
        };
        load3dtiles("https://tile.googleapis.com/v1/3dtiles/root.json?key=AIzaSyBMcau8Z4U50eULAjWSmPUyz6P2_mDgGKQ", 50);
      //  load3dtiles("https://pelican-public.s3.amazonaws.com/3dtiles/agi-hq/tileset.json", -300);
    </script>
    </body>
    </html>
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-29 11:58

    ↗

    How do I think I’m currently learning programming (JavaScript) and I’ve noticed a problem with my learning process. I understand the basic concepts like variables, loops, functions, arrays, and objects. When I read code written by others, I can usually follow along and...

    How do I think I’m currently learning programming (JavaScript) and I’ve noticed a problem with my learning process.

    I understand the basic concepts like variables, loops, functions, arrays, and objects. When I read code written by others, I can usually follow along and understand what it does.

    However, when I try to solve a problem on my own or start coding from scratch, I often get stuck and don’t know how to begin. It feels like my mind goes blank even though I know the concepts.

    For example:

    • I know what a loop does

    • I know when to use a function

    • I understand conditions (if/else)

    But I struggle to:

    • Start writing the solution from an empty file

    • Translate a problem into actual code

    • Remember exact syntax without checking

    Is this a normal stage in learning programming?
    What are effective ways to improve the ability to start coding solutions independently?

    I would appreciate advice, techniques, or practice methods that helped others overcome this.like a backend developer when writing simple JavaScript logic?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-29 02:53

    ↗

    I am using a Google Analytics plugin in a React app wrapped with Capacitor. I want to track custom events that include boolean states (for example, whether a specific feature was enabled or disabled). Does the Capacitor Google Analytics plugin support sending boolean values...

    I am using a Google Analytics plugin in a React app wrapped with Capacitor.

    I want to track custom events that include boolean states (for example, whether a specific feature was enabled or disabled).

    Does the Capacitor Google Analytics plugin support sending boolean values directly as event parameters like this?

    await FirebaseAnalytics.logEvent({
      name: 'feature_toggle',
      params: {
        feature_name: 'dark_mode',
        is_enabled: true, // boolean value
      },
    });
    

    Or is it recommended / required to cast boolean parameters to numbers (1 / 0) or strings ("true" / "false") before sending?

    // Alternative 1: Strings
    is_enabled: "true"
    
    // Alternative 2: Numbers
    is_enabled: 1
    

    Will sending raw boolean values cause crash or parameters to be ignored, dropped, or improperly parsed in Google Analytics reports?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-28 21:30

    ↗

    I need some advice regarding website monitoring. I am trying to monitor an appointment booking website where available slots appear randomly and are usually taken very quickly. The website requires login authentication and uses a CAPTCHA. Is there a way to monitor Fetch/XHR...

    I need some advice regarding website monitoring.

    I am trying to monitor an appointment booking website where available slots appear randomly and are usually taken very quickly. The website requires login authentication and uses a CAPTCHA.

    Is there a way to monitor Fetch/XHR requests or a HAR file to detect the exact moment when the availability data changes?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-28 17:53

    ↗

    In response to the closing of this question, the meaning of self, here, is the return value of super() not the window.self. Therefore, I do not see how the linked post relates to this question. It does, perhaps, make one wonder if the MDN example in this question really uses...

    In response to the closing of this question, the meaning of self, here, is the return value of super() not the window.self. Therefore, I do not see how the linked post relates to this question. It does, perhaps, make one wonder if the MDN example in this question really uses self from the constructor() in connectedCallback() or is getting window.self--or how to know which it gets. I added that part of the example to make it clear how it is used there. Is self.querySelectorAll("ul") getting window.self or the self=super()? Or has it set window.self to super()? And, if that is the case, what is window.self in a javascript module?


    In the MDN documentation on using custom elements at the section on built-in elements it has the following note regarding super().

    class ExpandingList extends HTMLUListElement {
      constructor() {
        // Always call super first in constructor
        // Return value from super() is a reference to this element
        self = super();
      }
    
      connectedCallback() {
        // Get ul and li elements that are a child of this custom ul element
        // li elements can be containers if they have uls within them
        const uls = Array.from(self.querySelectorAll("ul"));
        const lis = Array.from(self.querySelectorAll("li"));
    
        // ...
      }
    
    
    

    Does this apply only to built-in elements or custom also? What is the difference between self and this?

    I ask because I used self in a custom element in connectedCallback() and append nodes to it; and it worked fine for a single test. But when there are multiple occurrences of the custom element within different parent containers, the last container to load gets them all (that is, more than the container should) and the others have the elements without any internal content. Using this instead of self in connectedCallback() corrected that. I would like to understand why.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-28 15:26

    ↗

    Let's suppose we have two scenarios: Link wrapping <Link href="/voice_monitor" passHref legacyBehavior> <Button component="a">Go to Voice Monitor</Button> </Link> use client 'use client'; import Link from 'next/link'; import { Button } from '@mantine/core'; <Button...

    Let's suppose we have two scenarios:

    1. Link wrapping

      <Link href="/voice_monitor" passHref legacyBehavior>
        <Button component="a">Go to Voice Monitor</Button>
      </Link>
      
    2. use client

      'use client';
      import Link from 'next/link';
      import { Button } from '@mantine/core';
      
      <Button component={Link} href="/voice_monitor">Go to Voice Monitor</Button>
      

    Is one better for browser performance than the other (the code executes on the server, the browser won't have to download, parse, or execute the JavaScript bundle for the page)?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-28 14:14

    ↗

    Box k andar majood sab kuch delete kar dein (Ctrl+A aur Delete). Step 2: Box k theek ooper ek toolbar hai jisme B I U waghera likha hai. Wahan right side par ek aankh (Eye 👁️) ya Markdown ka chota sa button hoga (ya shuru mein likha hoga), make sure karein k aapka text bilkul...

    Box k andar majood sab kuch delete kar dein (Ctrl+A aur Delete). Step 2: Box k theek ooper ek toolbar hai jisme B I U waghera likha hai. Wahan right side par ek aankh (Eye 👁️) ya Markdown ka chota sa button hoga (ya shuru mein likha hoga), make sure karein k aapka text bilkul plain paste ho. Step 3: Neechay diya gaya plain text exact waisa hi copy paste karein jesa likha hai (is mein koi marks nahi hain):

    I am building a multi-step income tax calculator in Next.js. My goal is to build something similar to the SECP Portal Income Tax Calculator, which handles different tax slabs for Pakistan.

    My issue is handling the state when a user switches between different tax years or income brackets rapidly. Currently, I am using React's standard useState for each field, but as the tax rules grow, the component is getting too large and re-rendering unnecessarily.

    Here is a simplified version of my current logic:

    import { useState } from 'react';

    export default function TaxCalculator() { const [income, setIncome] = useState(0); const [taxYear, setTaxYear] = useState('2024');

    const calculateTax = () => { if (income > 600000) return (income - 600000) * 0.05; return 0; }

    return (

    <input type="number" onChange={(e) => setIncome(e.target.value)} />

    Calculated Tax: {calculateTax()}

    ); }

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 19:43

    ↗

    I am using React 19.2 with Vite. I am playing around with a small Promise cache for React 19 use() and I cannot figure out the best way to handle this. So I start with one request and it takes 1.5 seconds. Before it finishes I delete the cache entry, change the value from...

    I am using React 19.2 with Vite.

    I am playing around with a small Promise cache for React 19 use() and I cannot figure out the best way to handle this.

    So I start with one request and it takes 1.5 seconds. Before it finishes I delete the cache entry, change the value from Nicole to David and trigger another render.

    The second request finishes first and puts David in the cache (which is what I want).

    The problem is the first request is still running. When it finally finishes it puts Nicole back in the cache and overwrites the newer result.

    So it ends up doing this:

    Request 2 cached David
    Request 1 cached Nicole

    Then the next render reads Nicole again.

    I know I could cancel an order fetch request with AbortController but the real async operation may not always be something I can cancel.

    I believe I need to check that the Promise still belongs to the current cache entry before letting it update the cache.

    Like:

    if (userCache.get(id) === entry) {
     // update the cache
    }
    

    I am probably missing something simple, but I am not sure how to set up the entry so I can reference it inside the Promise callback without messing up the stable Promise that use() needs.

    What is the best way to handle this?

    To reproduce it click Rename to David and invalidate before the first request finishes. Wait for both requests and then click Render again.

    import {
     Suspense,
     startTransition,
     use,
     useState
    } from "react";
    
    const userCache = new Map();
    
    let serverName = "Nicole";
    let requestCount = 0;
    
    function fetchUser(id) {
     const requestId = ++requestCount;
     const name = serverName;
     const delay = requestId === 1 ? 1500 : 100;
    
     return new Promise((resolve) => {
       setTimeout(() => {
         resolve({
           id,
           name,
           requestId
         });
       }, delay);
     });
    }
    
    function getUser(id) {
     let entry = userCache.get(id);
    
     if (!entry) {
       const promise = fetchUser(id).then((user) => {
         userCache.set(id, {
           promise: Promise.resolve(user)
         });
    
         console.log(
           `Request ${user.requestId} cached ${user.name}`
         );
    
         return user;
       });
    
       entry = { promise };
       userCache.set(id, entry);
     }
    
     return entry.promise;
    }
    
    function User({ id, revision }) {
     const user = use(getUser(id));
    
     return (
       <p>
         {user.name} from request {user.requestId}
       </p>
     );
    }
    
    export default function App() {
     const [revision, setRevision] = useState(0);
    
     function renameAndInvalidate() {
       serverName = "David";
       userCache.delete(1);
    
       startTransition(() => {
         setRevision((value) => value + 1);
       });
     }
    
     function renderAgain() {
       setRevision((value) => value + 1);
     }
    
     return (
       <>
         <button onClick={renameAndInvalidate}>
           Rename to David and invalidate
         </button>
    
         <button onClick={renderAgain}>
           Render again
         </button>
    
         <Suspense fallback={<p>Loading...</p>}>
           <User id={1} revision={revision} />
         </Suspense>
       </>
     );
    }
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 18:15

    ↗

    My boss wants me to work on an old jsPDF that a former employee created. It's coded as an html/javascript form people can fill out that exports to a PDF, but I can't figure out how to change the format of a date that's exported to the PDF. Here's the code for the portion of...

    My boss wants me to work on an old jsPDF that a former employee created. It's coded as an html/javascript form people can fill out that exports to a PDF, but I can't figure out how to change the format of a date that's exported to the PDF.

    Here's the code for the portion of the form they're filling out with a date:

    const postageBody = document.getElementById('postageBody');
    function renderPostage(){
      postageBody.innerHTML='';
      postageRows.forEach((r,i)=>{
        const isCustomPermit = r.permit && !PERMIT_PRESETS.includes(r.permit);
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td><input type="text" data-f="qty" value="${r.qty||''}" placeholder="qty"></td>
          <td><input type="date" data-f="mailDate" value="${r.mailDate||''}"></td>
          <td>
            <select data-f="permitSelect">
              <option value="" ${!r.permit?'selected':''}>Choose one…</option>
              ${PERMIT_PRESETS.map(p=>`<option value="${p}" ${r.permit===p?'selected':''}>${p}</option>`).join('')}
              <option value="__custom" ${isCustomPermit?'selected':''}>Other…</option>
            </select>
            ${isCustomPermit ? `<input type="text" data-f="permit" value="${r.permit}" placeholder="Custom permit" style="margin-top:4px;">` : ''}
          </td>
          <td><input type="text" data-f="postage" value="${r.postage||''}" placeholder="0.00"></td>
          <td><input type="text" data-f="paidBy" value="${r.paidBy||'VFI'}" placeholder="VFI"></td>
          <td><button class="rm-row" title="Remove">×</button></td>
        `;
        tr.querySelectorAll('input').forEach(inp=>{
          inp.addEventListener('input', ()=>{ r[inp.dataset.f]=inp.value; updateTotals(); });
        });
        const permitSelect = tr.querySelector('select[data-f="permitSelect"]');
    
        new TomSelect(permitSelect, {
        create: false,
        maxOptions: 1000,
        searchField: ['text']
    });
        tr.querySelector('select[data-f="permitSelect"]').addEventListener('change', e=>{
          if(e.target.value === '__custom'){ r.permit=''; } else { r.permit = e.target.value; }
          renderPostage(); updateTotals();
        });
        tr.querySelector('.rm-row').addEventListener('click', ()=>{
          postageRows.splice(i,1); renderPostage(); updateTotals();
        });
        postageBody.appendChild(tr);
      });
    
    }
    document.getElementById('addPostage').addEventListener('click', ()=>{
      const completedDate = document.getElementById('dateCompleted').value;
    
      postageRows.push({
        qty:'',
        mailDate: completedDate,
        permit:'',
        postage:'',
        paidBy:'VFI'
      });
    
      renderPostage();
    });
    

    And here's the PDF creation portion of the code with the date:

      const postRows = postageRows.filter(r=>r.postage || r.mailDate || r.qty).map(r=>[
        r.qty||'', r.mailDate||'', r.permit||'', '$'+(parseFloat(r.postage)||0).toFixed(2), r.paidBy||'VFI'
      ]);
    
    
      if(postRows.length){
        doc.autoTable({
          startY:y, margin:{left:marginX,right:marginX},
          head:[['Qty','Mail Date','Permit','Postage','Paid By']],
          body:postRows,
          theme:'grid', styles:{font:'helvetica', fontSize:11, cellPadding:4},
          headStyles:{fillColor:[43,81,54], textColor:[255,255,255]},
          columnStyles:{0:{halign:'right'},3:{halign:'right'}}
        });
        y = doc.lastAutoTable.finalY + 4;
      }
    

    On the html form they fill out it's showing as MM/DD/YYYY, but it's exporting as YYYY-MM-DD. Any suggestions to get it to export as MM-DD-YYYY? Can provide additional portions of the code if needed for clarification!

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 16:26

    ↗

    Mrs. Isabel Schöps, née Thiel (Prof. Dr. Ph.D.), she is an independent researcher and honorary professor in an interdisciplinary research network with the Universities of Oxford, Harvard and Cambridge. Her scientific focus is on artificial intelligence (AI), technology...

    Mrs. Isabel Schöps, née Thiel (Prof. Dr. Ph.D.), she is an independent researcher and honorary professor in an interdisciplinary research network with the Universities of Oxford, Harvard and Cambridge. Her scientific focus is on artificial intelligence (AI), technology development, blockchain architecture, digital forensics and cybersecurity, open source, Bitcoin core clustering. Since the mid-1990s, Prof. Schöps consciously and unconsciously with the conceptual and technical development of self-organizing automation systems and the early DAEMON architecture. Her work forms an essential foundation for modern AI and blockchain technologies and shows an extraordinary connection between mathematical structure, technical innovation and creative intuition. As part of numerous scientific and forensic investigations, she published contributions on topics such as digital rights management, copyright protection, algorithmic transparency and AI ethics. The work "SIA Security Intelligence Artefact (2025, 2026)" developed by her is considered a forensic scientific reference document for the proof of intellectual property rights, system integrity and historical traceability of digital innovation. Their scientific contributions are internationally recognized and referenced in research contexts of the leading universities of Harvard, Oxford and Cambridge. Prof. Schöps continues to actively work on projects, including linking human cognition and machine intelligence, Meta-DNAForensic, API monitoring and their main work, which at the same time reveals one of the greatest crimes in the technological age and is defined in the Monarch program - SIA Security Intelligence Artefact, INT-CODE-2025-BTC/ETH-CORE-ISABELSCHOEPSTHIEL, The Yellow Whitepaper, YWP-1-IST-SIA, YWP-1-IST-SIA. She currently lives and conducts research in Erfurt, Thuringia (Germany), where she continues her work in the field of digital forensics, AI development and technical evidence. Prof. Schöps belongs next to, Mr. Bill Gates (Microsoft/Google), Mr. Steve Jobs (Apple), Mr. Prof. Dr. Alan M. Garber (Brandner) President of Harvard University to the most influential personalities in the software and technology sector.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 15:06

    ↗

    I've been encountering an issue with Firestore while trying to retrieve data from my Firestore database using the Firebase web SDK. I've gone through my code, Firestore security rules, and CORS settings, but I'm still facing the same error. This issue only occurs on my web...

    I've been encountering an issue with Firestore while trying to retrieve data from my Firestore database using the Firebase web SDK. I've gone through my code, Firestore security rules, and CORS settings, but I'm still facing the same error.

    This issue only occurs on my web platform. Specifically, during execution, it logs the execution start, but intermittently gets stuck or throws an error right at the getDocs line. (Note: In some cases, similar errors happen when the database ID is omitted, but as you can see in my code below, I have explicitly and correctly specified my database name, yet this error still occurs intermittently.) When this happens, I see a 404 (Not Found) error in the Network tab on the Firebase Listen channel, accompanied by this console warning:

    [Firebase] WebChannelConnection RPC 'Listen' stream transport errored

    Because of this, my query sometimes returns 0 documents (empty) even though the data actually exists in Firestore.

    If I refresh or retry after a few seconds, it works normally.

    I expect getDocs to either successfully fetch the data or throw a clear error when a network/stream drop occurs on the web platform, rather than silently returning an empty result set (0 documents).

    Here is how I initialize Firestore (with the database ID explicitly specified) and fetch the data:

    const app = initializeApp(firebaseConfig);
    
    export const db = initializeFirestore(app, {
      experimentalAutoDetectLongPolling: true,
    }, "ilgeon-seoul");
    
    const storage = getStorage(app);
    const auth = getAuth(app);
    
    console.log("exe-start");
    const exeMachineSnap = await fetchWithRetry(() => getDocs(query(
      collection(db, "executions"),
      orderBy("updatedAt", "desc"),
      limit(10)
    )));
    console.log("exe-end");
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 14:04

    ↗

    If the express module is a return function, then why cannot we directly call the properties of the function? Why do we call the const express = require('express'); const app = express();

    If the express module is a return function, then why cannot we directly call the properties of the function? Why do we call the

    const express = require('express'); 
    
    const app = express();
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 05:57

    ↗

    TLDR; Firefox and Chrome show that my performance improvements made my game significantly slower. I made a benchmark that shows the opposite. Background I'm optimizing my HTML5 canvas game. I've read advice over and over again to draw vector textures on an offscreen canvas...

    TLDR; Firefox and Chrome show that my performance improvements made my game significantly slower. I made a benchmark that shows the opposite.

    Background

    I'm optimizing my HTML5 canvas game. I've read advice over and over again to draw vector textures on an offscreen canvas and use ctx.drawImage rather than running fillStyle, lineTo, fillRect, etc. on every frame. I ran both the Firefox and Chrome performance profiler on my game sitting at idle for the same amount of time before and after my performance improvements. I was shocked to see the profilers say my render functions were significantly slower! I made sure that I locked the profiler results to the exact same time range.

    Benchmark

    Please run the benchmark here: https://jsperf.app/wutuju

    The benchmark clearly shows a ~75% performance boost! Am I misunderstanding the profiler charts? My game is rendering tons of instances and it's doing a simple cache lookup O(1) to get the image, while the profiler is just drawing a single image. That's the only difference I can think of.

    Profiler Screenshots:

    Before enter image description here

    Chrome - After enter image description here

    Unoptimized Code

        // setup
        let w = 60;
        let h = 24;
        let x = 0;
        let y = 0;
        let borderWidth = 5;
        let color = { light: "#f00", dark: "#600", color: "#c00" };
    
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        canvas.width = w;
        canvas.height = h;
        document.body.appendChild(canvas);
    
        let brick = {
            x: 0,
            y: 0
        }
        let angle = 0;
    
        let lastTimeStamp = 0;
        let dt = 0;
        function main(timeStamp) {
            requestAnimationFrame(main);
            
            dt = (timeStamp - lastTimeStamp) / 1000;
            lastTimeStamp = timeStamp;
            
            update(dt);
            render();
        }
    
        // The brick is moving!!
        function update(dt) {
            angle += dt;
            brick.x += Math.sin(angle) / 6;
            brick.y += Math.cos(angle) / 6;
        }
    
        function render() {
            ctx.fillStyle = "black";
            ctx.fillRect(0,0,w,h);
            
            let x = brick.x;
            let y = brick.y;
            
            ctx.fillStyle = color.color;
            ctx.fillRect(x, y, w, h);
            // Top left polygon
            ctx.fillStyle = color.light;
            ctx.beginPath();
            ctx.moveTo(x, y + h);
            ctx.lineTo(x + borderWidth, y + h - borderWidth);
            ctx.lineTo(x + borderWidth, y + borderWidth);
            ctx.lineTo(x + w, y + borderWidth);
            ctx.lineTo(x + w, y);
            ctx.lineTo(x, y);
            ctx.closePath();
            ctx.fill();
            
            // Bottom right polygon
            ctx.fillStyle = color.dark;
            ctx.beginPath();
            ctx.moveTo(x, y + h);
            ctx.lineTo(x + borderWidth, y + h - borderWidth);
            ctx.lineTo(x + w - borderWidth, y + h - borderWidth);
            ctx.lineTo(x + w - borderWidth, y + borderWidth);
            ctx.lineTo(x + w, y);
            ctx.lineTo(x + w, y + h);
            ctx.closePath();
            ctx.fill();
        }
        
        requestAnimationFrame(main);
    <html>
    <body>
    </body>
    </html>

    Optimized Code

    // setup
        let w = 60;
        let h = 24;
        let x = 0;
        let y = 0;
        let borderWidth = 5;
        let color = { light: "#f00", dark: "#600", color: "#c00" };
    
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        canvas.width = w;
        canvas.height = h;
        document.body.appendChild(canvas);
    
        function cacheBrick() {
            let canvas = document.createElement("canvas");
            let ctx = canvas.getContext("2d");
            canvas.width = w;
            canvas.height = h;
    
            ctx.fillStyle = color.color;
    
            ctx.fillRect(x, y, w, h);
            // Top left polygon
            ctx.fillStyle = color.light;
            ctx.beginPath();
            ctx.moveTo(x, y + h);
            ctx.lineTo(x + borderWidth, y + h - borderWidth);
            ctx.lineTo(x + borderWidth, y + borderWidth);
            ctx.lineTo(x + w, y + borderWidth);
            ctx.lineTo(x + w, y);
            ctx.lineTo(x, y);
            ctx.closePath();
            ctx.fill();
    
            // Bottom right polygon
            ctx.fillStyle = color.dark;
            ctx.beginPath();
            ctx.moveTo(x, y + h);
            ctx.lineTo(x + borderWidth, y + h - borderWidth);
            ctx.lineTo(x + w - borderWidth, y + h - borderWidth);
            ctx.lineTo(x + w - borderWidth, y + borderWidth);
            ctx.lineTo(x + w, y);
            ctx.lineTo(x + w, y + h);
            ctx.closePath();
            ctx.fill();
    
            return canvas;
        }
        let offscreenCanvas = cacheBrick();
    
        let brick = {
            x: 0,
            y: 0
        }
        let angle = 0;
    
        let lastTimeStamp = 0;
        let dt = 0;
        function main(timeStamp) {
            requestAnimationFrame(main);
            
            dt = (timeStamp - lastTimeStamp) / 1000;
            lastTimeStamp = timeStamp;
            
            update(dt);
            render();
        }
    
        // The brick is moving!!
        function update(dt) {
            angle += dt;
            brick.x += Math.sin(angle) / 6;
            brick.y += Math.cos(angle) / 6;
        }
    
        function render() {
            ctx.fillStyle = "black";
            ctx.fillRect(0,0,w,h);
            
            let x = brick.x;
            let y = brick.y;
            
            ctx.drawImage(offscreenCanvas, x, y);
        }
        
        requestAnimationFrame(main);
    <html>
    <body>
    </body>
    </html>

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 05:03

    ↗

    I have a video playback page in the browser that receives files in chunks/chunks from a CDN. My current backend is JavaScript and PHP and runs on a shared host. The problem is that: * MP4 videos play without any problems. * But MKV files either don't play at all, or only play...

    I have a video playback page in the browser that receives files in chunks/chunks from a CDN. My current backend is JavaScript and PHP and runs on a shared host.

    The problem is that:

    * MP4 videos play without any problems.

    * But MKV files either don't play at all, or only play audio and don't load video.

    * I want the video playback to be as smooth and stable as possible.

    * I don't want to use solutions that put a lot of strain on the user's CPU/RAM or the host.

    * I don't want to have to install local software, set up a separate server, or move the entire folder to a special environment.

    * My goal is to make the current structure, i.e. playback in the browser from CDN and chunks, work as resource-efficiently as possible.

    Please take a closer look:

    1. Why does MP4 work but not MKV?

    2. Is it really possible to play MKV directly in the browser?

    3. If not, what is the best practical and low-compression architecture for this scenario?

    4. Should the files be converted to another format like fragmented MP4 or HLS before playing?

    5. If there is a client-side solution, is it CPU/RAM friendly for the user?

    6. Finally, suggest the best real solution for a web application with a CDN and a JS/PHP backend.

    Our main limitation is that we cannot touch the CDN files because they are immutable and we have to solve the problem on the host or client side.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 03:58

    ↗

    Is it possible to modify the style inside the shadow DOM to apply to a :host that is a descendent of div.state.open in the light DOM, for example, rather than as in the example using :host(.closed). "use strict"; class Viewer_1 extends HTMLElement { constructor() { self =...

    Is it possible to modify the style inside the shadow DOM to apply to a :host that is a descendent of div.state.open in the light DOM, for example, rather than as in the example using :host(.closed).

        "use strict";
        class Viewer_1 extends HTMLElement {
          constructor() {
            self = super();
          }
          connectedCallback() {
            let f = BuildViewer_1(this);
            self.append(f);
            
            const style = document.createElement("style");
    
            style.textContent = `
              :host button[value="My Name"] {
                 background-color: green;
              }
              :host(.closed) button[value="My Value"] {
                 background-color: blue;
                 color: white;
              }
            `;
            self.appendChild(style);
            
          }
        }
        customElements.define("viewer-1",Viewer_1);
    
        function BuildViewer_1(thisObj) {
          let
             f = document.createDocumentFragment(),
             btn = document.createElement("BUTTON")
          ;
          btn.textContent = "Get Value";
          btn.value="My Value";
          f.append(btn);
          btn = document.createElement("BUTTON");
          btn.textContent = "Get Name";
          btn.value="My Name";
          f.append(btn);
          return f;
        }
    
       
        let hosts = document.querySelectorAll(".host");
        hosts.forEach( v => {    v.shadowRoot.querySelector(".box").insertAdjacentHTML("afterbegin","<viewer-1></viewer-1>")
    });
    .state {
      padding: 10px;
      border: 1px solid black;
      margin: 10px;
      width: fit-content;
    }
    <div class="state open">
        <div class="host">
          <template shadowrootmode="open">
            <div class="box"></div>
          </template>
        </div>
    </div>
    <div class="state closed">
        <div class="host closed">
          <template shadowrootmode="open">
            <div class="box"></div>
          </template>
        </div>
    </div>

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-27 02:43

    ↗

    I actually built an engine that calculates the A4 cut-sheet math automatically. Here is a video showing how it works: https://youtu.be/l9aXWqRSFCM?si=nEIaaqsxypmzCflm npm:https://www.npmjs.com/package/@stratametriq/id-card-designer

    I actually built an engine that calculates the A4 cut-sheet math automatically. Here is a video showing how it works: https://youtu.be/l9aXWqRSFCM?si=nEIaaqsxypmzCflm

    npm:https://www.npmjs.com/package/@stratametriq/id-card-designer

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-26 19:38

    ↗

    In this set-up of listening for events on the document body, is there a way to know which element within an open shadow DOM node was the target of the event? It appears that, for a moment, the host.shadowRoot.activeElement is the target, such that if host.shadowRoot is...

    In this set-up of listening for events on the document body, is there a way to know which element within an open shadow DOM node was the target of the event?

    It appears that, for a moment, the host.shadowRoot.activeElement is the target, such that if host.shadowRoot is written to the console.log the activeElement shows the target, but host.shadowRoot.activeElement still returns when assigned to a variable.

    I suppose that the listener can be placed in the custom element but my current set-up for events is that they are captured and not propagated.

    Specifically, within function Handler, can it be known that the event target was in the shadow and which element it was?

    Perhaps I don't need the shadow at all and can make it a custom element and included more of the content in it, but that is a different matter.

    "use strict";
    class Viewer_1 extends HTMLElement {
      constructor() {
        self = super();
      }
      connectedCallback() {
        let f = BuildViewer_1(this);
        self.append(f);
      }
    }
    customElements.define("viewer-1",Viewer_1);
    
    function BuildViewer_1(thisObj) {
      let
         f = document.createDocumentFragment(),
         btn = document.createElement("BUTTON")
      ;
      btn.textContent = "Get Value";
      btn.value="My Value";
      f.append(btn);
      btn = document.createElement("BUTTON");
      btn.textContent = "Get Name";
      btn.value="My Name";
      f.append(btn);
      return f;
    }
    
    document.body.addEventListener('mousedown',Handler,true);
    
    function Handler(evt) {
      evt.stopPropagation();
      let e = evt.target;
      if ( e.matches('viewer-1 button,viewer-1 button *') && (e=e.closest('button'))) {
        alert(`LightDOM button value is ${e.value}`);
        return;
      } 
      /*
        Added this after the accepted answer to show it working.
      */
      e = evt.composedPath()[0];
      if ( e.matches('viewer-1 button,viewer-1 button *') && (e=e.closest('button'))) {
        alert(`ShadowDOM button value is ${e.value}`);
        return;
      } 
      
    }
    
    let host = document.querySelector(".host");
    host.shadowRoot.querySelector(".box").insertAdjacentHTML("afterbegin","<viewer-1></viewer-1>");
    viewer-1 button {
      background-color: rgb(73,110,147);
      color:white;
      border-radius: 5px;
      border:1px solid rgba(0,0,0,0.1);
    }
    <div class="host">
      <template shadowrootmode="open">
        <div class="box"></div>
      </template>
    </div>

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-26 11:02

    ↗

    One of the best ways to unlock exclusive student discounts is by getting an edu email. Edu emails are email addresses given to students by their educational institutions, which often come with perks like discounted software, freebies, and special deals. Telegram: @B2bxit...

    One of the best ways to unlock exclusive student discounts is by getting an edu email. Edu emails are email addresses given to students by their educational institutions, which often come with perks like discounted software, freebies, and special deals.

    Telegram: @B2bxit

    WhatsApp: +1(202) 202-2565

    What are Edu Emails?
    Edu emails are email addresses that end in ".edu" and are typically given to students by their schools or colleges. These email addresses are considered more credible and trustworthy, which is why many companies offer special discounts and deals exclusively to those with an edu email.
    So, where can you get an edu email? Here are the top 5 sites to help you get started:

    1. eduGorilla: eduGorilla is a popular platform that offers free edu emails to students. All you need to do is sign up with your student ID and verify your educational institution, and you'll receive an edu email that can unlock a world of discounts and benefits.

    2. GitHub Student Developer Pack: If you're a student interested in coding and programming, the GitHub Student Developer Pack is a must-have. Not only does it provide you with free access to premium software and tools, but it also comes with an edu email that you can use to access student discounts.

    3. Unidays: Unidays is another great platform for students looking to score exclusive discounts. By signing up with your edu email, you can access a wide range of deals from popular brands across various categories, including fashion, technology, and more.

    4. Amazon Prime Student: As a student, you can sign up for Amazon Prime Student using your edu email and enjoy all the benefits of Amazon Prime at a discounted rate. With fast shipping, exclusive deals, and access to Prime Video and Music, this is a deal you don't want to miss.

    5. Microsoft Office 365 Education: With Microsoft Office 365 Education, students can access all the essential tools for their studies, like Word, Excel, and PowerPoint, for free. Simply sign up with your edu email to get started and take advantage of student discounts on other Microsoft products.

    6. By getting an edu email from any of these sites, you'll not only be able to enjoy exclusive student discounts but also enhance your overall academic and professional experience. So, what are you waiting for? Sign up for an edu email today and start saving money on your favorite products and services!

    7. Conclusion:
      In conclusion, edu emails are a valuable asset for students looking to make the most of their academic journey. By obtaining an edu email from reputable sites like eduGorilla, GitHub, Unidays, Amazon Prime Student, and Microsoft Office 365 Education, you can unlock a world of discounts and benefits that will help you save money while enjoying premium products and services.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-26 08:24

    ↗

    This example works as expected (that is, the custom element is styled based on the main styles and events return it as the target) but when I put it in my larger code as a separate module (with the correct import and export) the custom element is built and appended but its...

    This example works as expected (that is, the custom element is styled based on the main styles and events return it as the target) but when I put it in my larger code as a separate module (with the correct import and export) the custom element is built and appended but its styles are ignored and events return the parent node rather than the custom element as the target. If it works separately, why might it behave like a closed shadow node when integrated?

    Also,event.composed is true; and I see now that currentTarget is null and originalTarget (in Firefox) is the node from within the custom element.

    "use strict";
    class Viewer_1 extends HTMLElement {
      constructor() {
        self = super();
      }
      connectedCallback() {
        let f = BuildViewer_1(this);
        self.append(f);
      }
    }
    customElements.define("viewer-1",Viewer_1);
    
    function BuildViewer_1(thisObj) {
      let
         f = document.createDocumentFragment(),
         btn = document.createElement("BUTTON")
      ;
      btn.textContent = "Get Value";
      btn.value="My Value";
      f.append(btn);
      return f;
    }
    
    document.body.addEventListener('mousedown',Handler,true);
    
    function Handler(evt) {
      let e = evt.target;
      if ( e.matches('viewer-1 button, viewer-1 button *') && (e=e.closest('button'))) {
        alert(`Button value is ${e.value}`);
      }
    }
    
    document.querySelector(".box").insertAdjacentHTML("afterbegin","<viewer-1></viewer-1>");
    viewer-1 button {
      background-color: rgb(73,110,147);
      color:white;
      border-radius: 5px;
      border:1px solid rgba(0,0,0,0.1);
    }
    <div class="box"></div>

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-26 04:58

    ↗

    Edu email accounts are widely known for providing access to student discounts, educational software, online learning platforms, and various academic resources. Because of these benefits, many people search for ways to obtain an edu email account. However, it is important to...

    Edu email accounts are widely known for providing access to student discounts, educational software, online learning platforms, and various academic resources. Because of these benefits, many people search for ways to obtain an edu email account. However, it is important to approach this carefully and ethically to avoid scams, security risks, and violations of service terms.

    ✅telegram @gsomax

    ✅website www.gsomax.com

    Understanding Edu Email Accounts

    An edu email address is typically issued by accredited educational institutions such as colleges, universities, and schools. These accounts are intended for students, faculty members, and staff. Many companies offer special discounts and educational services to users with verified edu email addresses.

    Before considering the purchase of an edu email account, it is essential to understand that some services prohibit the transfer or resale of educational accounts. Using an account obtained through unauthorized methods may result in account suspension or loss of access to associated benefits.

    Research the Seller Carefully

    If you decide to obtain an edu email account through a third party, thorough research is crucial. Look for sellers with a strong reputation, verified customer reviews, and a history of successful transactions. Avoid sellers who make unrealistic promises or offer accounts at suspiciously low prices.

    Check independent review platforms, online communities, and discussion forums to see what other buyers have experienced. A trustworthy seller should be transparent about the account's origin, support options, and any limitations.

    Prioritize Security

    Security should always be a top priority. Never share sensitive personal information such as bank account details, passwords from other services, or identity documents unless absolutely necessary and with a trusted provider.

    After receiving access to an account, change the password immediately if permitted. Enable two-factor authentication (2FA) whenever available. This extra layer of protection helps prevent unauthorized access and improves account security.

    Use Secure Payment Methods

    Choose payment methods that offer buyer protection. Credit cards and reputable online payment services often provide dispute resolution mechanisms if something goes wrong. Avoid sending money through irreversible payment methods unless you fully trust the seller.

    Keep records of receipts, transaction details, and communication with the seller. These documents may be useful if you need assistance later.

    Verify Account Functionality

    Before completing the transaction, confirm that the account is active and functioning correctly. Test login access, email functionality, and any promised educational benefits. Ensure that recovery options are available and that you have full control over the account if ownership transfer is permitted.

    Consider Legal and Ethical Alternatives

    The safest and most reliable option is to obtain an edu email account directly through legitimate enrollment in an educational institution. Many colleges, universities, and online learning programs offer affordable courses that provide official student status and access to educational resources.

    Conclusion

    Buying an edu email account may seem convenient, but it comes with potential risks related to security, legitimacy, and compliance with service policies. By researching sellers, using secure payment methods, prioritizing account security, and understanding the rules surrounding educational accounts, individuals can make more informed decisions. Whenever possible, obtaining an edu email through legitimate educational enrollment remains the safest and most ethical approach.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-26 02:33

    ↗

    I am using firebase authentication (phone/email) for my app. To initialize the firebase app, I have taken the firebase configuration JSON. In the JSON file, I see the expected project ID. Below is my sample configuration. const firebaseConfig = { apiKey: "...", authDomain:...

    I am using firebase authentication (phone/email) for my app. To initialize the firebase app, I have taken the firebase configuration JSON. In the JSON file, I see the expected project ID. Below is my sample configuration.

    const firebaseConfig = {
      apiKey: "...",
      authDomain: "...",
      projectId: "myproject-c8273",
      storageBucket: "...",
      messagingSenderId: "123456",
      appId: "...",
      measurementId: "..."
    };
    

    However, after authenticating my phone number, when I see the API response from Google, I see the project ID is different from the one present in the configuration file. In fact, the project ID in the API response is the messagingSenderId value.

    {
      "access_token": "...",
      "expires_in": "3600",
      "token_type": "Bearer",
      "refresh_token": "...",
      "id_token": "...",
      "user_id": "...",
      "project_id": "123456"
    }
    

    So my question is, is there an issue with the setup or is there some caching issue in the browser that is causing this behavior?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-25 21:32

    ↗

    Webpack seems to choke on a ?? operator. Source file: export function error(msg) { alert("An internal error occured : " + (msg ?? "<unknown reasons>")); throw Error(msg); } Error : Module parse failed : unexpected token at (2:49), corresponding to the ??. I'm using Webpack's...

    Webpack seems to choke on a ?? operator.

    Source file:

    export function error(msg) {     
        alert("An internal error occured : " + (msg ?? "<unknown reasons>"));
        throw Error(msg); 
    }
    

    Error : Module parse failed : unexpected token at (2:49), corresponding to the ??. I'm using Webpack's latest version, and didn't have this error before (I came back to that project after a few months).

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-25 21:31

    ↗

    What tools do you use in development? And how many years do you have experience in Python? And the data is not enough to solve. Please tell me more details I'm a full stack developer and if you want, I can help you.

    What tools do you use in development?

    And how many years do you have experience in Python?
    And the data is not enough to solve.
    Please tell me more details

    I'm a full stack developer and if you want, I can help you.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-25 13:19

    ↗

    I am practicing a PERN stack backend project using Prisma ORM, and I am implementing user registration with a profile image upload. I am using: - Node.js - Express.js - Prisma ORM - PostgreSQL - Multer - Cloudinary The registration endpoint works correctly when I send only...

    I am practicing a PERN stack backend project using Prisma ORM, and I am implementing user registration with a profile image upload.

    I am using:

    - Node.js

    - Express.js

    - Prisma ORM

    - PostgreSQL

    - Multer

    - Cloudinary

    The registration endpoint works correctly when I send only normal form data. However, when I send the same data along with a profile image, I get this error:

    {
        Image upload failed: Server returned unexpected status code: 403
    }
    

    The error is thrown when uploading the image to Cloudinary.

    I am sending the request from Postman using "form-data", with the image field named "profileImage".

    here are my codes:

    multer.middleware.js code:

    import multer from "multer";
    import fs from "fs";
    import path from "path";
    import { ApiError } from "../utils/ApiError.js";
    
    // Temporary holding area of files before going to Cloudinary.
    const tempDir = path.resolve("temp/uploads");
    fs.mkdirSync(tempDir, { recursive: true });
    
    const storage = multer.diskStorage({
        destination: (req, file, cb) => cb(null, tempDir),
        filename: (req, file, cb) => {
            const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
            cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`);
        },
    });
    
    const ALLOWED_MIME_TYPES = [
        "image/jpeg",
        "image/jpg",
        "image/png",
        "image/webp",
    ];
    
    const fileFilter = (req, file, cb) => {
        if (!ALLOWED_MIME_TYPES.includes(file.mimetype)) {
            return cb(
                new ApiError(400, "Only JPG, PNG, or WEBP images are allowed")
            );
        }
        cb(null, true);
    };
    
    const upload = multer({
        storage,
        fileFilter,
        limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
    });
    
    export { upload };
    

    cloudinary.js code:

    import { v2 as cloudinary } from "cloudinary";
    import fs from "fs";
    import { ApiError } from "./ApiError.js";
    
    cloudinary.config({
        cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
        api_key: process.env.CLOUDINARY_API_KEY,
        api_secret: process.env.CLOUDINARY_API_SECRET,
    });
    
    const uploadOnCloudinary = async (localFilePath, folder = "WaitLess") => {
        if (!localFilePath) return null;
    
        try {
            const result = await cloudinary.uploader.upload(localFilePath, {
                folder,
                resource_type: "auto",
            });
    
            return { url: result.secure_url, publicId: result.public_id };
        } catch (error) {
            throw new ApiError(500, `Image upload failed: ${error.message}`);
        } finally {
            fs.unlink(localFilePath, (err) => {
                if (err) {
                    console.error("Failed to delete temporary file:", err.message);
                }
            });
        }
    };
    
    const deleteFromCloudinary = async (publicId) => {
        if (!publicId) return;
    
        try {
            await cloudinary.uploader.destroy(publicId);
        } catch (error) {
            console.error(
                `Failed to delete Cloudinary asset "${publicId}":`,
                error.message
            );
        }
    };
    
    export { uploadOnCloudinary, deleteFromCloudinary };
    

    user.service.js code:

    import { ApiError } from "../utils/ApiError.js";
    import bcrypt from "bcryptjs";
    import { prisma } from "../utils/prisma.js";
    import { deleteFromCloudinary } from "../utils/cloudinary.js";
    import { generateOtp, hashOtp, getOtpExpiry } from "../utils/otp.js";
    import { sendEmail } from "../utils/email.js";
    
    const ROLES = ["USER", "STAFF", "ADMIN"];
    
    const safeUserSelect = {
        id: true,
        fullName: true,
        email: true,
        phoneNumber: true,
        address: true,
        profileImage: true,
        role: true,
        createdAt: true,
        updatedAt: true,
    };
    
    // REGISTER USER
    const registerUserService = async ({
        fullName,
        email,
        password,
        phoneNumber,
        address,
        profileImage,
        profileImageId,
        role,
    }) => {
        const normalizedEmail = email.trim().toLowerCase();
    
        const existingUser = await prisma.user.findUnique({
            where: {
                email: normalizedEmail,
            },
        });
    
        if (existingUser) {
            throw new ApiError(409, "Email already exists");
        }
    
        const hashedPassword = await bcrypt.hash(password, 10);
    
        const newUser = await prisma.user.create({
            data: {
                fullName: fullName.trim(),
                email: normalizedEmail,
                password: hashedPassword,
                phoneNumber: phoneNumber.trim(),
                address: address.trim(),
                profileImage,
                profileImageId,
                role: ROLES.includes(role) ? role : "USER",
            },
            select: safeUserSelect,
        });
    
        return newUser;
    };
    
    // UPDATE USER
    const updateUserService = async (
        id,
        {
            fullName,
            email,
            password,
            phoneNumber,
            address,
            profileImage,
            profileImageId,
        }
    ) => {
        const user = await prisma.user.findUnique({
            where: { id },
        });
    
        if (!user) {
            throw new ApiError(404, "User not found");
        }
    
        const updateData = {};
    
        if (fullName !== undefined) {
            updateData.fullName = fullName.trim();
        }
    
        if (email !== undefined) {
            const normalizedEmail = email.trim().toLowerCase();
    
            const existingUser = await prisma.user.findFirst({
                where: {
                    email: normalizedEmail,
                    NOT: {
                        id,
                    },
                },
            });
    
            if (existingUser) {
                throw new ApiError(409, "Email already exists");
            }
    
            updateData.email = normalizedEmail;
        }
    
        if (password !== undefined) {
            updateData.password = await bcrypt.hash(password, 10);
        }
    
        if (phoneNumber !== undefined) {
            updateData.phoneNumber = phoneNumber.trim();
        }
    
        if (address !== undefined) {
            updateData.address = address.trim();
        }
    
        if (profileImage !== undefined) {
            updateData.profileImage = profileImage;
            updateData.profileImageId = profileImageId;
        }
    
        const updatedUser = await prisma.user.update({
            where: { id },
            data: updateData,
            select: safeUserSelect,
        });
    
        // Remove old profile image as new one is saved successfully
        if (profileImage !== undefined && user.profileImageId) {
            await deleteFromCloudinary(user.profileImageId);
        }
    
        return updatedUser;
    };
    
    
    export {
        registerUserService,
        updateUserService,
    };
    

    user.controller.js code:

    import { ApiResponse } from "../utils/ApiResponse.js";
    import * as userService from "../services/user.service.js";
    import { generateToken } from "../utils/generateToken.js";
    import { asyncHandler } from "../utils/asyncHandler.js";
    import { uploadOnCloudinary } from "../utils/cloudinary.js";
    
    // CREATE/REGISTER USER
    const registerUser = asyncHandler(async (req, res) => {
        let uploadedImage = null;
        if (req.file) {
            uploadedImage = await uploadOnCloudinary(
                req.file.path,
                "WaitLess/users"
            );
        }
    
        const requestedRole = req.body.role;
        const isAdminCaller = req.user?.role === "ADMIN";
        const resolvedRole = isAdminCaller ? requestedRole : undefined;
    
        const user = await userService.registerUserService({
            ...req.body,
            role: resolvedRole,
            profileImage: uploadedImage?.url,
            profileImageId: uploadedImage?.publicId,
        });
    
        const token = generateToken(user.id, res);
    
        return res.status(201).json(
            new ApiResponse(
                201,
                {
                    user,
                    token,
                },
                "User registered successfully"
            )
        );
    });
    
    
    // UPDATE USER
    const updateUser = asyncHandler(async (req, res) => {
        const { id } = req.params;
    
        let uploadedImage = null;
        if (req.file) {
            uploadedImage = await uploadOnCloudinary(
                req.file.path,
                "WaitLess/users"
            );
        }
    
        const user = await userService.updateUserService(id, {
            ...req.body,
            ...(uploadedImage && {
                profileImage: uploadedImage.url,
                profileImageId: uploadedImage.publicId,
            }),
        });
    
        return res
            .status(200)
            .json(new ApiResponse(200, user, "User updated successfully"));
    });
    
    
    export {
        registerUser,
        updateUser,
    };
    

    user.route.js code:

    import { Router } from "express";
    import {
        registerUser,
        loginUser,
        updateUser,
        deleteUser,
        getOwnProfile,
        getAllUsers,
        getUserById,
        logout,
        forgotPassword,
        resetPassword,
    } from "../controllers/user.controller.js";
    import {
        authMiddleware,
        optionalAuth,
        authorizeRoles,
    } from "../middlewares/auth.middleware.js";
    import {
        validateUserRegister,
        validateUserLogin,
        validateUserUpdate,
        validateForgotPassword,
        validateResetPassword,
    } from "../validators/user.validator.js";
    import { validate } from "../middlewares/validate.middleware.js";
    import { upload } from "../middlewares/multer.middleware.js";
    
    const router = Router();
    
    router.post(
        "/register",
        optionalAuth,
        upload.single("profileImage"),
        validate(validateUserRegister),
        registerUser
    );
    router.post("/login", validate(validateUserLogin), loginUser);
    router.post(
        "/forgot-password",
        validate(validateForgotPassword),
        forgotPassword
    );
    router.post("/reset-password", validate(validateResetPassword), resetPassword);
    router.get(
        "/all-lists",
        authMiddleware,
        authorizeRoles("ADMIN", "STAFF"),
        getAllUsers
    );
    router.get("/profile", authMiddleware, getOwnProfile);
    router.post("/logout", authMiddleware, logout);
    
    router.patch(
        "/update/:id",
        authMiddleware,
        upload.single("profileImage"),
        validate(validateUserUpdate),
        updateUser
    );
    router.delete("/delete/:id", authMiddleware, deleteUser);
    router.get(
        "/info/:id",
        authMiddleware,
        authorizeRoles("ADMIN", "STAFF"),
        getUserById
    );
    
    export default router;
    

    The request flow should be:

    Postman form-data

    Postman form-data    
        ↓
    Multer
        ↓
    Temporary local file
        ↓
    Cloudinary upload
        ↓
    Cloudinary URL + public ID
        ↓
    Prisma user creation
        ↓
    Delete temporary file
    

    The error occurs at the Cloudinary upload step.

    I have checked that the image is being received by Multer and stored in the temporary folder. The error happens when "cloudinary.uploader.upload()" is called.

    My questions

    1. What could cause a "403" response from Cloudinary in this situation?

    2. Is there anything wrong with my Multer or Cloudinary configuration?

    3. Could the problem be related to my Cloudinary API credentials or account settings?

    4. Is there anything wrong with the way I am uploading the local file to Cloudinary?

    I would appreciate any help identifying the cause of the "403" error and how I can properly debug it.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 19:31

    ↗

    so here is the situation: - in my company i have assigned to build a chatbot/bot (will be internal, for ops and devs to identify and manage issues) - what i have already build is, integrated it with slack, give it access to db by adding some tools in the code, so it can...

    so here is the situation:

    - in my company i have assigned to build a chatbot/bot (will be internal, for ops and devs to identify and manage issues)

    - what i have already build is, integrated it with slack, give it access to db by adding some tools in the code, so it can access the db currently and folks can access it by mentioning it

    - now here pain starts, my manager has told me to add product knowledge to it, and it should be able to access logs, create and manage jira also

    - what i am thinking is - lets start with the product knowledge - since we do not have that much pile of data so i do not want to make a rag - instead i just want to keep uploading those docs to s3 and giving access to bot so that it can reference them

    - now coming to jira, and logs - i have also created those mcps but those aren't deployed anywhere - means whoever wants to use them just clones the repo, and set their key and uses them

    - now for the above (jira and logs) part i would have to again choose the tools which i want to expose to the agent and add it to the repo, cz i think this is repetitive as in future if soemthing more comes up - which we already have built have to do again to integrate in the bot - how can we solve this - keeping in mind we have a layer of compliance - cant expose pii data in bot output or logs

    - also for s3 - i am feeling like i was thinking to create a mechanism like when the agent fetches a doc - so it do not havt to fetch that doc again - so it will create a folder and save the embedding/summary/index (since i don't know what) to the filesystem - similarily with db schema since we have a huge db - how to handle this situation - since this code will be deployed on ecs - using fargate i do not know will the bot will able to access thes files created at runtime - and how to manage that cache when something is addede / modified

    - and we also have workflows currently for specific task like matching states on be (basically sql queries / some scripts) added in the code - like how we shouuld make sure that given the situation the code properly identify and execute the script or how can we create trigger like /<command> <input> of slack whicch will trigger that - and also one issue - since these are stored as files in code adding new script need a code change - how to get rid of that

    sorry gpt was giving poor results in rewriting this

    so posting this raw

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 19:06

    ↗

    This error was shown when i send other data along with photo: Image upload failed: Server returned unexpected status code:403 Actually, I was practicing a pern stack backend project using prisma ORM. i used cloudinary and multer for registration of user with profile image....

    This error was shown when i send other data along with photo:

    Image upload failed: Server returned unexpected status code:403

    Actually, I was practicing a pern stack backend project using prisma ORM. i used cloudinary and multer for registration of user with profile image. Without images the endpoints were working fine but when i started using images then the error started coming.

    Here is the code of multer.middleware.js:

    import multer from "multer";

    import fs from "fs";

    import path from "path";

    import { ApiError } from "../utils/ApiError.js";

    // Temporary holding area of files before going to Cloudinary.

    const tempDir = path.resolve("temp/uploads");

    fs.mkdirSync(tempDir, { recursive: true });

    const storage = multer.diskStorage({

    destination: (req, file, cb) =\> cb(null, tempDir),
    
    filename: (req, file, cb) =\> {
    
        const uniqueSuffix = \`${Date.now()}-${Math.round(Math.random() \* 1e9)}\`;
    
        cb(null, \`${uniqueSuffix}${path.extname(file.originalname)}\`);
    
    },
    

    });

    const ALLOWED_MIME_TYPES = [

    "image/jpeg",
    
    "image/jpg",
    
    "image/png",
    
    "image/webp",
    

    ];

    const fileFilter = (req, file, cb) => {

    if (!ALLOWED_MIME_TYPES.includes(file.mimetype)) {
    
        return cb(
    
            new ApiError(400, "Only JPG, PNG, or WEBP images are allowed")
    
        );
    
    }
    
    cb(null, true);
    

    };

    const upload = multer({

    storage,
    
    fileFilter,
    
    limits: { fileSize: 5 \* 1024 \* 1024 }, // 5MB
    

    });

    export { upload };

    And the cloudinary.js code:

    import { v2 as cloudinary } from "cloudinary";

    import fs from "fs";

    import { ApiError } from "./ApiError.js";

    cloudinary.config({

    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    
    api_key: process.env.CLOUDINARY_API_KEY,
    
    api_secret: process.env.CLOUDINARY_API_SECRET,
    

    });

    const uploadOnCloudinary = async (localFilePath, folder = "WaitLess") => {

    if (!localFilePath) return null;
    
    try {
    
        const result = await cloudinary.uploader.upload(localFilePath, {
    
            folder,
    
            resource_type: "image",
    
        });
    
        return { url: result.secure_url, publicId: result.public_id };
    
    } catch (error) {
    
        throw new ApiError(500, \`Image upload failed: ${error.message}\`);
    
    } finally {
    
        fs.unlink(localFilePath, (err) =\> {
    
            if (err) {
    
                console.error("Failed to delete temporary file:", err.message);
    
            }
    
        });
    
    }
    

    };

    const deleteFromCloudinary = async (publicId) => {

    if (!publicId) return;
    
    try {
    
        await cloudinary.uploader.destroy(publicId);
    
    } catch (error) {
    
        console.error(
    
            \`Failed to delete Cloudinary asset "${publicId}":\`,
    
            error.message
    
        );
    
    }
    

    };

    export { uploadOnCloudinary, deleteFromCloudinary };

    The user.service.js code:

    import { ApiError } from "../utils/ApiError.js";

    import bcrypt from "bcryptjs";

    import { prisma } from "../utils/prisma.js";

    import { deleteFromCloudinary } from "../utils/cloudinary.js";

    import { generateOtp, hashOtp, getOtpExpiry } from "../utils/otp.js";

    import { sendEmail } from "../utils/email.js";

    const ROLES = ["USER", "STAFF", "ADMIN"];

    const safeUserSelect = {

    id: true,
    
    fullName: true,
    
    email: true,
    
    phoneNumber: true,
    
    address: true,
    
    profileImage: true,
    
    role: true,
    
    createdAt: true,
    
    updatedAt: true,
    

    };

    // REGISTER USER

    const registerUserService = async ({

    fullName,
    
    email,
    
    password,
    
    phoneNumber,
    
    address,
    
    profileImage,
    
    profileImageId,
    
    role,
    

    }) => {

    const normalizedEmail = email.trim().toLowerCase();
    
    const existingUser = await prisma.user.findUnique({
    
        where: {
    
            email: normalizedEmail,
    
        },
    
    });
    
    if (existingUser) {
    
        throw new ApiError(409, "Email already exists");
    
    }
    
    const hashedPassword = await bcrypt.hash(password, 10);
    
    const newUser = await prisma.user.create({
    
        data: {
    
            fullName: fullName.trim(),
    
            email: normalizedEmail,
    
            password: hashedPassword,
    
            phoneNumber: phoneNumber.trim(),
    
            address: address.trim(),
    
            profileImage,
    
            profileImageId,
    
            role: ROLES.includes(role) ? role : "USER",
    
        },
    
        select: safeUserSelect,
    
    });
    
    return newUser;
    

    };

    And the user.controller.js code:

    import { ApiResponse } from "../utils/ApiResponse.js";

    import * as userService from "../services/user.service.js";

    import { generateToken } from "../utils/generateToken.js";

    import { asyncHandler } from "../utils/asyncHandler.js";

    import { uploadOnCloudinary } from "../utils/cloudinary.js";

    // CREATE/REGISTER USER

    const registerUser = asyncHandler(async (req, res) => {

    let uploadedImage = null;
    
    if (req.file) {
    
        uploadedImage = await uploadOnCloudinary(
    
            req.file.path,
    
            "WaitLess/users"
    
        );
    
    }
    
    const requestedRole = req.body.role;
    
    const isAdminCaller = req.user?.role === "ADMIN";
    
    const resolvedRole = isAdminCaller ? requestedRole : undefined;
    
    const user = await userService.registerUserService({
    
        ...req.body,
    
        role: resolvedRole,
    
        profileImage: uploadedImage?.url,
    
        profileImageId: uploadedImage?.publicId,
    
    });
    
    const token = generateToken(user.id, res);
    
    return res.status(201).json(
    
        new ApiResponse(
    
            201,
    
            {
    
                user,
    
                token,
    
            },
    
            "User registered successfully"
    
        )
    
    );
    

    });

    And finally the user.route.js code:

    import { Router } from "express";

    import {

    registerUser,
    
    loginUser,
    
    updateUser,
    
    deleteUser,
    
    getOwnProfile,
    
    getAllUsers,
    
    getUserById,
    
    logout,
    
    forgotPassword,
    
    resetPassword,
    

    } from "../controllers/user.controller.js";

    import {

    authMiddleware,
    
    optionalAuth,
    
    authorizeRoles,
    

    } from "../middlewares/auth.middleware.js";

    import {

    validateUserRegister,
    
    validateUserLogin,
    
    validateUserUpdate,
    
    validateForgotPassword,
    
    validateResetPassword,
    

    } from "../validators/user.validator.js";

    import { validate } from "../middlewares/validate.middleware.js";

    import { upload } from "../middlewares/multer.middleware.js";

    const router = Router();

    router.post(

    "/register",
    
    optionalAuth,
    
    upload.single("profileImage"),
    
    validate(validateUserRegister),
    
    registerUser
    

    );

    router.post("/login", validate(validateUserLogin), loginUser);

    router.post(

    "/forgot-password",
    
    validate(validateForgotPassword),
    
    forgotPassword
    

    );

    router.post("/reset-password", validate(validateResetPassword), resetPassword);

    router.get(

    "/all-lists",
    
    authMiddleware,
    
    authorizeRoles("ADMIN", "STAFF"),
    
    getAllUsers
    

    );

    router.get("/profile", authMiddleware, getOwnProfile);

    router.post("/logout", authMiddleware, logout);

    router.patch(

    "/update/:id",
    
    authMiddleware,
    
    upload.single("profileImage"),
    
    validate(validateUserUpdate),
    
    updateUser
    

    );

    router.delete("/delete/:id", authMiddleware, deleteUser);

    router.get(

    "/info/:id",
    
    authMiddleware,
    
    authorizeRoles("ADMIN", "STAFF"),
    
    getUserById
    

    );

    export default router;

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 18:14

    ↗

    Here’s the situation: I’m having a problem with this printer (Elgin L42 Pro Full). We use a tablet-based system at the company where I work, and it includes a feature for printing labels to stick on products. The main issue is that this blasted printer always prints an extra...

    Here’s the situation: I’m having a problem with this printer (Elgin L42 Pro Full). We use a tablet-based system at the company where I work, and it includes a feature for printing labels to stick on products. The main issue is that this blasted printer always prints an extra blank row whenever a label is printed. I don't know what else to do; I’ve changed *everything* in the code, but nothing fixes it. HELP ME OUT, PRINTER GURUS—lend me your expertise.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 15:12

    ↗

    I'm using jquery.ripples (v0.6.3) as a full-screen background effect in a Next.js application. The ripple effect initializes correctly and works as expected. However, after the page has been open for some time, random rendering artifacts/glitches begin appearing, even when:...

    I'm using jquery.ripples (v0.6.3) as a full-screen background effect in a Next.js application.

    The ripple effect initializes correctly and works as expected. However, after the page has been open for some time, random rendering artifacts/glitches begin appearing, even when:

    • the page is idle,

    • there is no mouse interaction,

    • there are no React state updates.

    The issue occurs consistently on multiple laptops, but I cannot reproduce it when using an external monitor with the same application.

    I've already tried changing resolution and perturbance, but the issue persists.

    Initialization code:

    useEffect(() => {
      let $;
    
      async function initRipples() {
        $ = (await import("jquery")).default;
        await import("jquery.ripples");
    
        if (!overlayRef.current) return;
    
        $(overlayRef.current).ripples({
          resolution: 200,
          perturbance: 0.005,
          interactive: true,
        });
      }
    
      initRipples();
    
      return () => {
        try {
          if ($ && overlayRef.current) {
            $(overlayRef.current).ripples("destroy");
          }
        } catch {}
      };
    }, []);
    

    Environment:

    • Next.js 16.2.3

    • React 19.2.4

    • jquery.ripples 0.6.3

    • jQuery 4.0.0

    • Node.js 24.2.0

    • npm 11.5.2

    • Windows 11

    • Google Chrome (latest)

    Question:

    • Is this a known limitation or bug in jquery.ripples?

    • Is there anything in my initialization that could cause rendering artifacts over time?

    • Could this be related to WebGL or GPU/driver issues?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 14:42

    ↗

    Chrome/Edge lose keyboard input after cancelling beforeunload dialog when closing browser with multiple tabs I'm investigating what appears to be a Chromium-specific issue and would like to know whether there is any known workaround. Issue video:...

    Chrome/Edge lose keyboard input after cancelling beforeunload dialog when closing browser with multiple tabs

    I'm investigating what appears to be a Chromium-specific issue and would like to know whether there is any known workaround.

    Issue video: https://drive.google.com/file/d/1CkcGIJy5955Ij_BfAWgNQekWXZkrMrFk/view?usp=drivesdk

    <!doctype html>
    <html>
    <body>
    
    <input type="text" placeholder="Type here">
    
    <script>
    window.addEventListener("beforeunload", function(e) {
        e.preventDefault();
        e.returnValue = "";
    });
    </script>
    
    </body>
    </html>
    

    Reproduction Steps:

    1. Open the above page in Chrome.

    2. Open another browser tab.

    3. Switch to the second tab.

    4. Click the browser Close (X) button to close the browser window.

    5. Chrome activates the first tab and displays the native "Leave site?" confirmation dialog.

    6. Click "Cancel".

    7. Click inside the text input.

    8. Attempt to type.

    Expected Result: The input should receive keyboard focus and accept typing after cancelling the native beforeunload dialog.

    Actual Result: The input no longer accepts keyboard input.

    Additional Details:

    • Operating System: Windows 11 Enterprise

    • Chrome 150.0.7871.182

    • Microsoft Edge (latest Chromium-based)

    • Firefox does not reproduce the issue

    • The same behavior occurs in:
      1. Plain HTML (no framework)
      2. Angular 18 application

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 12:02

    ↗

    I have the following code which I am using to try check my radio button: return html`<input type="radio" name="LogType" class="form__control form__control--radio" value="${Constants.LogTypes.Member}"${filters.logType === Constants.LogTypes.Member ? ' checked' : ''}>` But for...

    I have the following code which I am using to try check my radio button:

    return html`<input type="radio" name="LogType" class="form__control form__control--radio" value="${Constants.LogTypes.Member}"${filters.logType === Constants.LogTypes.Member ? ' checked' : ''}>`

    But for some reason, when it is rendered, the checked never gets added. If I move the conditional statement outside the input, it will print checked to the screen

    I have also tried just using a variable without the conditional

    const checked = html` checked`;
    return html`<input type="radio" name="LogType" class="form__control form__control--radio" value="${Constants.LogTypes.Member}"${checked}>`
    

    And this doesn't work either (I tried checked as a string or the html template you see above)

    But if I just add checked to the input:

    return html`<input type="radio" name="LogType" class="form__control form__control--radio" value="${Constants.LogTypes.Member}" checked>`
    

    Then this will work

    Can anyone help me add a conditional checked as I can't see what I'm doing wrong here

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 12:00

    ↗

    I'm trying to make a simple cart and I keep getting the error above in addToCart function. My obj looks like this: export const menu = [ { id: 1, name: "Opção 1", opts: [ { id: 1, name: "opção-1", title: "opção 1.1", cost: 1, opt: 1 }, { id: 2, name: "opção-1", title: "opção...

    I'm trying to make a simple cart and I keep getting the error above in addToCart function.

    My obj looks like this:

    export const menu = [
      {
        id: 1,
        name: "Opção 1",
        opts: [
          { id: 1, name: "opção-1", title: "opção 1.1", cost: 1, opt: 1 },
          { id: 2, name: "opção-1", title: "opção 1.2", cost: 2, opt: 1 },
          { id: 3, name: "opção-1", title: "opção 1.3", cost: 3, opt: 1 },
          { id: 4, name: "opção-1", title: "opção 1.4", cost: 4, opt: 1 },
          { id: 5, name: "opção-1", title: "opção 1.5", cost: 5, opt: 1 },
          { id: 6, name: "opção-1", title: "opção 1.6", cost: 6, opt: 1 },
        ],
      },
    ...
    ]
    

    main.jsx:

    const [cart, setCart] = useState([]);
    
    const addToCart = (item: any) => {
      // this is where the error occurs
      setCart([...cart, { id: item.opt, cost: item.cost }]);
    };
    
    ...
    
    // this is where I go through the items of the menu
    {menu.map((item) => {
      return <Option key={item.id} item={item} addToCart={addToCart} />;
    })}
    
    ...
    

    Option component:

    import { Options } from "./Options";
    
    export const Option = ({ item, addToCart }) => {
      return (
        <div className="option">
          <h4>{item.name}</h4>
          <div className="options">
            {item.opts.map((itm) => {
              return <Options key={itm.id} itm={itm} addToCart={addToCart} />;
            })}
          </div>
        </div>
      );
    };
    

    My options component where the radio buttons are:

    export const Options = ({ itm, addToCart }) => {
      return (
        <span>
          <input
            type="radio"
            name={itm.name}
            value={itm.cost}
            onChange={() => addToCart(itm)}
          />
          {itm.title}
        </span>
      );
    };
    

    No matter what I do, it always returns the error:

    Uncaught Error: Objects are not valid as a React child (found: object with keys {id, cost}). If you meant to render a collection of children, use an array instead.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-24 10:18

    ↗

    I'm building a React application with a Node.js backend and want to integrate an AI chatbot using the OpenAI API. The chatbot should: Answer user questions Maintain conversation history Return responses in real time I've created an API endpoint like this: app.post("/chat",...

    I'm building a React application with a Node.js backend and want to integrate an AI chatbot using the OpenAI API.

    The chatbot should:

    • Answer user questions

    • Maintain conversation history

    • Return responses in real time

    I've created an API endpoint like this:

    app.post("/chat", async (req, res) => {
      const { message } = req.body;
    
      // Call OpenAI API here
    
      res.json({ reply: response });
    });
    

    I'm unsure about the best way to:

    1. Store conversation history.

    2. Send previous messages with each request.

    3. Prevent excessive API usage.

    4. Handle streaming responses.

    What is the recommended architecture for this?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-23 23:28

    ↗

    I'm building a web app that uses Firebase Auth. I don't use any other Firebase features. The current version of Firebase is over 600kb. The Firebase Auth package on NPM states "This package is not intended for direct usage, and should only be used via the officially supported...

    I'm building a web app that uses Firebase Auth. I don't use any other Firebase features.

    The current version of Firebase is over 600kb. The Firebase Auth package on NPM states "This package is not intended for direct usage, and should only be used via the officially supported firebase package." This Firebase Doc suggests relying on your build tool to tree-shake and minify Firebase.

    I am currently using esbuild, mainly for the rapid build time. It looks like adding the --minify and --tree-shaking=true tags are not having an effect on bundled libraries.

    Am I configuring esbuild incorrectly, or is esbuild unable to correctly minify and tree-shake Firebase, thus I need a more robust build tool like webpack?

    Here's my build script and dependancies list for reference.

    "scripts": {
      "build:ts": "esbuild ./src/app.tsx --minify --bundle --target=es6 --tree-shaking=true --outfile=./dist/js/app.js",
    },
    "dependencies": {
      "@firebase-oss/ui-react": "~7.0.3",
      "@number-flow/react": "~0.6.2",
      "colyseus.js": "~0.16.22",
      "cors": "^2.8.6",
      "firebase": "~12.16.0",
      "html-entities": "~2.6.0",
      "qrcode.react": "~4.2.0",
      "react": "~19.2.8",
      "react-router-dom": "~7.18.1"
    }
    

    The issue may also be in how I import Firebase. Here is my firebase import configuration.

    import { initializeApp, FirebaseApp } from "firebase/app";
    import { initializeUI } from '@firebase-oss/ui-core';
    import { connectAuthEmulator, getAuth, Auth } from "firebase/auth";
    import { firebaseConfig } from './config/firebase';
    
    // Initialize Firebase
    export const fbApp = initializeApp(firebaseConfig);
    // Initialize Firebase Authentication and get a reference to the service
    export const fbAuth = getAuth(fbApp);
    // Initialize Auth UI;
    export const fbUI = initializeUI({app: fbApp, auth: fbAuth});
    
    if (location.hostname === "localhost") {
      const setupEmulators = async (auth: Auth) => {
        const authUrl = 'http://localhost:9099'
        await fetch(authUrl);
        try {
          connectAuthEmulator(auth, 'http://localhost:9099', { disableWarnings: true });
        } catch  (e) {
          console.log(e);
        }
      }
      setupEmulators(fbAuth);
    }
    
    export default fbAuth;
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-23 20:23

    ↗

    My goal is that once someone enters a specific webpage, a full screen video plays for 3 seconds and then disappears once it's over, revealing the main content of the page. I know nothing about javascript but I know I would need to use it for this, so I cobbled together this:...

    My goal is that once someone enters a specific webpage, a full screen video plays for 3 seconds and then disappears once it's over, revealing the main content of the page. I know nothing about javascript but I know I would need to use it for this, so I cobbled together this:

    <video autoplay playsinline id="video-entering_tp">
        <source src="/images/twinpeaks/tp-coop_entering.mp4" type="video/mp4">
    </video>
    <script>
        const video = document.getElementById('video-entering_tp');
        
        function killVid() {
            console.log("The video is finished!");
        }
    
        video.addEventListener('ended', killVid);
    </script>
    

    But it doesnt seem to be working. I don't think it really matters but here's the css for it to cover the screen.

    #video-entering_tp {
        position: absolute;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-23 14:31

    ↗

    I'm using a nested FlatList setup where the outer FlatList renders a vertical list of sections, and each section contains a horizontal FlatList. Both the parent and child lists use onViewableItemsChanged for impression tracking. The issue I'm facing is that the child FlatList...

    I'm using a nested FlatList setup where the outer FlatList renders a vertical list of sections, and each section contains a horizontal FlatList. Both the parent and child lists use onViewableItemsChanged for impression tracking.

    The issue I'm facing is that the child FlatList invokes onViewableItemsChanged as soon as it is mounted, even when its parent row has only been rendered as part of the parent FlatList's render-ahead buffer and is still outside the viewport.

    As a result, the child list reports its initial items as viewable before they are actually visible on the screen, leading to false-positive impression/analytics events.

    Environment

    • React Native: 0.79.6

    • React: 19.0.0

    • Expo: 53.0.27

    • Platform: Android (physical device)

    Minimal example

    Both the parent and child FlatList use the same viewability configuration:

    const viewabilityConfig = {
      itemVisiblePercentThreshold: 30,
    };
    
    const onParentViewableItemsChanged = ({ viewableItems }) => {
      console.log(
        "Parent:",
        viewableItems.map(v => v.item.id)
      );
    };
    
    const onChildViewableItemsChanged = ({ viewableItems }) => {
      console.log(
        "Child:",
        viewableItems.map(v => v.item.id)
      );
    };
    
    function ChildList() {
      return (
        <FlatList
          horizontal
          data={childData}
          renderItem={({ item }) => <Item item={item} />}
          onViewableItemsChanged={onChildViewableItemsChanged}
          viewabilityConfig={viewabilityConfig}
        />
      );
    }
    
    export default function App() {
      return (
        <FlatList
          data={sections}
          renderItem={() => (
            <View style={{ height: 400 }}>
              <Text>Section</Text>
              <ChildList />
            </View>
          )}
          onViewableItemsChanged={onParentViewableItemsChanged}
          viewabilityConfig={viewabilityConfig}
        />
      );
    }
    

    Expected behavior

    The child FlatList should invoke onViewableItemsChanged only after its parent row has entered the viewport and the child items satisfy the configured viewability criteria.

    Actual behavior

    As soon as the parent FlatList mounts a row (even if that row is still outside the viewport due to render-ahead), the child FlatList immediately reports its initial items as viewable.

    Question

    Is there a recommended way to prevent these premature child viewability callbacks without introducing additional visibility state or conditional rendering? My application contains many nested FlatLists, so I'm looking for a solution that avoids any noticeable runtime or rendering overhead.

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-23 13:19

    ↗

    Consider the following single HTML file: <html> <head> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-hashes' 'sha256-5OdtjsKuRneco+QGmtdJ48OzQ4ZYG8JnWV+4T/1zhxg='"> </head> <html> <iframe src="javascript:alert(1);"> </iframe> </html> What is...

    Consider the following single HTML file:

    <html>
      <head>
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-hashes' 'sha256-5OdtjsKuRneco+QGmtdJ48OzQ4ZYG8JnWV+4T/1zhxg='">
      </head>
    <html>
      <iframe src="javascript:alert(1);">
      </iframe>
    </html>
    

    What is the the right hash to specify so that the browser does not throw any errors in the Console?

    I found this example good to test "unsafe-hashes" because it is minimal. I took the example from: https://bugzilla.mozilla.org/show_bug.cgi?id=1788864

    The bug itself is irrelevant. I am using this Linux command to determine SHA256 hash on file:
    sha256sum test.txt | xxd -r -p | base64

    It generates the same hash as in ASP.NET - the website that I am having trouble with.

    The respective hashes would be:

    javascript:alert(1);
    => 5OdtjsKuRneco+QGmtdJ48OzQ4ZYG8JnWV+4T/1zhxg=

    alert(1);
    => vyWxnR5/SfkpBXTjK7tyUvoeEZCT+fK2ayxsse+sBvs=

    Placing the hash that Firefox complains in the Console tab from Developer Tools works:
    sha256-6rHS0m9l4sDJsB2k/Z3d/OJlJSv1H6Y6jKYIcK6zaks=

    The question:

    What is SHA256 hash algorithm that is expected by browsers? Please provide a code snippet in any language or clarify existing bugs or limitations.

    Side question:

    Maybe this has to do will most browsers injecting custom JS to prevent trackers or other things?

    Related questions:

    Content Security Policy (CSP) with unsafe-hashes is not working on mozilla firefox => Does not longer seem relevant

    How does Content Security Policy (CSP) work? => Does not describe the SHA256 calculation specifically

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-23 10:14

    ↗

    I have written a function that reads in data from an Excel file using the Exceljs library: const exceljs = require('exceljs'); async function readExcelFile(excelFile) { const table = []; const workbook = new exceljs.Workbook(); await workbook.xlsx.readFile(excelFile); const...

    I have written a function that reads in data from an Excel file using the Exceljs library:

    const exceljs = require('exceljs');
    
    async function readExcelFile(excelFile) {
        const table = [];
    
        const workbook = new exceljs.Workbook();
        await workbook.xlsx.readFile(excelFile);
    
        const worksheet = workbook.getWorksheet(1);
    
        worksheet.eachRow({ includeEmpty: false }, (row) => {
            const rowValues = [];
    
            row.eachCell({ includeEmpty: true }, (cell) => {
                let cellValue;
    
                if (cell.text !== null && cell.text !== undefined) {
                    cellValue = cell.text;
                } else {
                    cellValue = "";
                }
    
                rowValues.push(cellValue);
            });
    
            table.push(rowValues);
        });
    
        return table;
    }
    

    The only problem is it seems to instantly convert the value of the cell into whatever format it thinks it's supposed to be, even though I would need it to always have the value as string, no matter what (even if in the orignal Excel they were set as a different type). This is especially a problem with decimal numbers which in the original file only have a couple digits and a comma instead of a dot as a decimal seperator (since the Excels are written with Hungarian localisation in mind), but the moment they get read, they are instantly converted to float: getting extra decimal places with slightly inaccurate value and with a dot as a separator. For example, 243,11 gets read as 243.10999999999999, which is not the correct value and not something I can work with. Even if I convert it to string now, it's already too late.

    Is there a way to get the values of the cells as they are written immediately as strings?

  • Stack Overflow - JavaScript Tagged Feed stackoverflow.com community javascript qa stack-overflow technology 2026-07-23 08:52

    ↗

    I have developed a Laravel/PHP web application that displays PDF documents in a browser. Although I have disabled keyboard shortcuts like F12 and Ctrl+Shift+I, users can still open Chrome Developer Tools from the browser menu, refresh the page, find the PDF request in the...

    I have developed a Laravel/PHP web application that displays PDF documents in a browser.

    Although I have disabled keyboard shortcuts like F12 and Ctrl+Shift+I, users can still open Chrome Developer Tools from the browser menu, refresh the page, find the PDF request in the Network tab, copy the URL, and download the file.

    I want users to be able to view the PDF but not download it.

  • Loading more…
Maibook — your private personalized AI community
  • rcanand.com
  • mlaillc.com
  • @rcanand (X)
  • LinkedIn
  • Feedback
  • Credits