Form keeps reseting even though there are errors why?

So I have provided two code that takes the value from users through html form process using vanilla js for front and node js for backend. so when I add existing value rather than showing errors in the span err blocks it keeps resetting the form. anybody please help.

I want my code to show the server errors in the error field in the html span blocks, but I an getting a form reset rather than showing error.

Front end code

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('signup-form').addEventListener('submit', async function submit(event) {
    event.preventDefault();
    // Clear previous error messages
    const errorFields = ['usernameerr', 'emailerr', 'passworderr', 'confirmPassworderr', 'fileerr'];
    errorFields.forEach(field => document.getElementById(field).textContent = '');

    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const file = document.getElementById('file').files[0];

    // Validate password
    if (password !== confirmPassword) {
      document.getElementById('confirmPassworderr').textContent = 'Passwords do not match';
      return;
    }

    const formData = new FormData();
    formData.append('username', username);
    formData.append('email', email);
    formData.append('password', password);
    formData.append('json', file);

    try {
      const response = await fetch('http://localhost:3000/signup', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();
      console.log('Server response:', result);

      if (response.ok) {
        alert(result.message);
        document.getElementById('signup-form').reset();
      } else {
        // Handle errors from the server
        if (result.user) {
          document.getElementById('usernameerr').textContent = result.user;
        }
        if (result.email) {
          document.getElementById('emailerr').textContent = result.email;
        }
        if (result.fileerr) {
          document.getElementById('fileerr').textContent = result.fileerr;
        }
      }
    } catch (error) {
      console.error('Error during submission:', error);
      alert('An error occurred. Please try again.');
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">

<div class="signup-container">
  <form class="signup-form" id="signup-form">
    <h2>SignUp Form</h2>
    <div class="input-group">
      <label for="username"><i class="fas fa-user"></i></label>
      <input type="text" id="username" placeholder="Enter Username" required>
      <span id="usernameerr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="email"><i class="fas fa-envelope"></i></label>
      <input type="email" id="email" placeholder="Enter Email" required>
      <span id="emailerr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="password"><i class="fas fa-lock"></i></label>
      <input type="password" id="password" placeholder="Create Password" required>
      <span id="passworderr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="confirm-password"><i class="fas fa-lock"></i></label>
      <input type="password" id="confirm-password" placeholder="Retype Password" required>
      <span id="confirmPassworderr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="file"><i class="fas fa-file"></i></label>
      <input type="file" id="file" required>
      <span id="fileerr" class="error"></span>
    </div>
    <div class="reset">
      <a class="back" href="login.html" target="_blank">Already have an account?</a>
    </div>
    <button type="submit">SignUp</button>
  </form>
</div>

Backend code

const mysql = require('mysql2');
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const multer = require('multer');
const path = require('path');
const app = express();

app.use(cors({
    origin: 'http://127.0.0.1:5500', // Replace with your frontend's origin
    methods: ['POST'],
    allowedHeaders: ['Content-Type']
}));

const con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'signup'
});

con.connect(function (err) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully");
});

const upload = multer({
    dest: "upload"
});

app.post('/signup', upload.single('json'), (req, res) => {
    const { username, email, password } = req.body;
    const file = req.file;

    if (!file) {
        return res.status(400).json({ fileerr: 'No file uploaded or incorrect format.' });
    }

    // Check for existing username or email
    const checkQuery = 'SELECT * FROM gui WHERE username = ? OR email = ?';
    con.query(checkQuery, [username, email], (err, result) => {
        if (err) return res.status(500).json({ error: 'Database query error' });

        if (result.length > 0) {
            const existing = result[0];
            if (existing.username === username) {
                return res.status(400).json({ user: 'Username already exists' });
            }
            if (existing.email === email) {
                return res.status(400).json({ email: 'Email already exists' });
            }
        }

        try {
            const fileData = fs.readFileSync(file.path, 'utf-8'); // Synchronous read
            const parsedData = JSON.parse(fileData); // Parse JSON to ensure validity

            // Insert data into the database
            const insertQuery = 'INSERT INTO gui(email, username, password, data) VALUES (?, ?, ?, ?)';
            con.query(insertQuery, [email, username, password, JSON.stringify(parsedData)], (err) => {
                if (err) return res.status(500).json({ error: 'Failed to insert data' });

                return res.status(201).json({ message: 'Signup successful' });
            });
        } catch (error) {
            return res.status(400).json({ error: 'Invalid JSON file or error reading the file' });
        }
    });
});

app.listen(3000, () => {
    console.log('listening on port 3000');
});

Triggering a swipe event with a click

I created a simple horizontal scroll window for viewing reviews. I set up scroll-snap and also added some Java Script so that on clicking one of the chevrons bounding my scroll window the content is scrolled by some amount and then the scroll-snap kicks in, centring the new item.

This works great on my laptop but for some reasons when I view this on my phone (btw in the dev tools simulation of a mobile this works fine as well just not on a real phone – sigh) the nice smooth scroll snap works only when swiping on the scroll window. When I click on the chevron the content is scrolled by some amount and then just stays like this even if the window ends up showing two items at once – the scroll snap does not “finish” the movement.

Of course, one way to solve this would be to do some calculations (in my case converting units etc etc) and always scroll the exact amount needed on chevron click.

But since swiping works fine I was wondering if it possible to trigger a swipe on chevron click which could be a simpler solution.

Mouseleave event triggers exception and click event doesn’t

I want dropdown list to disappear when mouse leaves #navbarHint div element.

let flag2 = true;

document.getElementById('navbarHint').addEventListener('mouseleave', 
function() { 
    flag2 = false;
    menuClick();
});

document.getElementById('navbtn').addEventListener('click', menuClick);
function menuClick()
{
    let menu = document.querySelector('.dropdown:hover .dropdown-content');
    if (flag2)
    {
        menu.style.visibility = 'visible';
        flag2 = false
    }
    else
    {
        menu.style.visibility = 'hidden';
        flag2 = true;
    }
}
#navbarHint
{
    position: absolute;
    height: 8rem;
    width: 100%;
    z-index: 3;
  background-color: grey;
}

.dropdown-content {
    right: 0;
    visibility: hidden;
    position: absolute;
    background-color: #000000;
    min-width: max-content;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    transform: translateX(-3rem) translateY(2.5rem);
    z-index: 2; 
}

.dropdown-content p
{
    margin-inline: 0.25rem;
    margin-block: 0.5rem;
}

#navbtn
{
    width: 3rem;
    height: 3rem;
    z-index: 2;
    background-color: red;
    position: absolute;
    right: 1rem;
    top: 1rem;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Hello, world!</title>
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <meta name="description" content="" />
  <
</head>
<body>
  <div id="navbarHint">
  <div id="navbtn" class="dropdown">
    <div class="dropdown-content">
      <p>Hello World!</p>
    </div>
  </div>
</div>
</body>
</html>

});

So the list should disappear when I leave certain area on the page. But it doesn’t. It raises Uncaught TypeError: Cannot read properties of null (reading 'style') exception, although it works perfectly when menuClick function is called from click event. For some reason it does matter which event is calling the function.

I also tried this with document.getElementById('navbtn').addEventListener('mouseleave', menuClick); – and it doesn’t work as well.

Why are the checkbox ticks not visible in the JPG output, even though they are checked in the PDF?

Why are the checkbox ticks not visible in the JPG output, even though they are checked in the PDF? Is there a way to make sure the ticks are rendered properly when converting the PDF to JPG?

I’ve tried adjusting the rendering options, but I still cannot see the checkbox ticks. Any help would be appreciated!

When converting a PDF to a JPG, there can be issues with rendering certain elements, such as checkbox ticks, due to how the PDF is structured or how the conversion tool handles form fields. Here are a few reasons why checkbox ticks might not be visible in the JPG output and possible solutions:

  1. Form Field vs. Static Content
    Problem: PDF files can contain form elements (like checkboxes) that are interactive, but when converting to an image format (like JPG), these form fields may not render as they appear in a PDF viewer.
    Solution: Ensure that you’re rendering the content as a flattened image, not just extracting the static content. Some PDF-to-image conversion libraries, such as pdf.js, might require explicit instructions to render form fields as part of the page’s content rather than leaving them as form elements.
  2. Rendering Engine Limitations
    Problem: The rendering engine used for converting the PDF to an image may not support rendering form fields correctly or may render them with low priority.
    Solution: Use a more robust PDF-to-image converter that fully supports form field rendering. For example, libraries like poppler-utils (specifically pdftoppm), pdf2image (Python), or Ghostscript are known to handle form elements better and may render checkbox ticks properly.
  3. Check Rendering Settings
    Problem: Some PDF conversion tools may require special settings to render form fields, checkboxes, or annotations.
    Solution: If using pdf.js for rendering, make sure you set the appropriate rendering options to include annotations or form fields. For example, when using pdf.js, you might need to configure the rendering process to ensure form fields are rendered properly:
    javascript
    Copy code
    const options = {
    renderInteractiveForms: true // This ensures that interactive form fields are rendered
    };
    For other tools, check the documentation for similar options to ensure form fields are rendered as part of the output.
  4. Ensure Correct PDF Format
    Problem: If the PDF is not well-structured, or if the checkboxes are vector-based rather than interactive form elements, some conversion tools might not render them as you expect.
    Solution: Make sure that the checkboxes are not part of a form field but are instead drawn as actual images or vector shapes. You can flatten the form fields into the document itself using tools like Adobe Acrobat before conversion.
  5. Use a Full Conversion Process
    Solution: Tools like ImageMagick or Ghostscript can sometimes be better at converting PDFs into high-quality images, including form fields, and preserving the appearance of checkboxes. You can try using these tools with appropriate options to ensure form fields are rendered as part of the JPG:
    Using ImageMagick:
    bash
    Copy code
    convert -density 300 input.pdf -quality 100 output.jpg
    Using Ghostscript:
    bash
    Copy code
    gs -sDEVICE=jpeg -dNOPAUSE -dBATCH -sOutputFile=output.jpg input.pdf
  6. Manually Rendering Checkboxes
    Problem: If the above solutions don’t work, you can extract the checkbox information (such as whether they are checked or not) using pdf-lib or another PDF library, and then manually overlay the ticks onto the JPG after conversion.
    Conclusion:
    To ensure that the checkbox ticks are visible in the JPG output:

Use a more advanced converter that handles interactive form fields.
Adjust rendering options to include form fields.
Ensure that your PDF does not have form elements that are not rendered as part of the content.
Consider flattening or pre-rendering the PDF to ensure form fields are converted to static content before the conversion.
If you’re using pdf.js, make sure you configure it to render interactive form fields as part of the content, or try a different PDF-to-image conversion tool.

Viewing my site on a mobile scales a background image differently to a desktop browser set to the phone’s dimensions svelte

So I have a paragraph and an svg graphic (nearly a rectangle but with ‘wavy’ edges on the top and bottom). I would like the SVG to stretch to fill the width of the screen and completely cover the paragraph’s height (without cropping the wavy edges of the image).

I got this working on desktops and in mobile view in the F12 menu on my desktop, but when viewing the site on my actual mobile the scaling is all wrong. I have an iphone XR which is a preset option in my browser’s sizing menu so the dimensions should be exactly the same.

This is the CSS for the section. intro-para is the overall container and para-content is the text.

.intro-para {
    color: white !important;
    padding: 2vw 5vw 2vw 5vw !important;
    width: 100vw !important;
    max-width: 100% !important;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
}

#introPara::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100%;
    background-image: url('../../static/SVG/Asset 8 pink.svg');
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    transform: scaleX(var(--scaleX)) scaleY(var(--scaleY));
    z-index: -1;
}

.para-content {
    z-index: 3;
    margin: 1vw 0 3vw 0;
    text-align: left;
    width: 100%;
}

And then in the OnMount function I have this JS to find the scaleX and Y variables I used:

    function updateScale() {
        const paraContainer = document.getElementById('introPara');
        const style = window.getComputedStyle(paraContainer, "::before");
        const backgroundImage = style.backgroundImage;

        let imageUrl = backgroundImage.slice(5, -2);
        let imgHeight = 0;
        let imgWidth = 0;
        const img = new Image();
        img.onload = function () {
            imgHeight = img.height;
            imgWidth = img.width;
            const containerHeight = paraContainer.offsetHeight;
            const containerWidth = paraContainer.offsetWidth;

            const scaleX = containerWidth / imgWidth;
            const scaleY = (containerHeight / imgHeight) / 1.5;
            const scale = Math.min(scaleX, scaleY);
            //const scaleY = (containerHeight / imgHeight) * 0.5 + (imgHeight / containerHeight);
            document.documentElement.style.setProperty('--scaleX', scaleX);
            document.documentElement.style.setProperty('--scaleY', scaleY);
        };
        img.src = imageUrl;
    }

    window.addEventListener('resize', updateScale);
    updateScale();

As I said, the desktop version works in every view:

desktop on mobile view

desktop view

However when I look on my phone, I get this:

view on my phone

I’ve looked around on the internet and asked co-pilot if they can spot any issues but it doesn’t really get what I mean and keeps switching between a couple of incorrect suggestions. What can I do to fix this?

Error not found p5.js in Vercel but Vite works fine

Not showing p5,js sketches as Vercel gives an not defined error, in Vite works fine.
Also would like to go to myproject/docs and show the jsdoc documentation.

Load my project, and sketches are not shown…

https://vercel.com/ejgutierrez74s-projects/pacman2024windows

With vite works fine, but in vercel i got an error when i deploy to Vercel

Uncaught ReferenceError: p5 is not defined
    Nn https://pacman2024windows.vercel.app/assets/index-Df26wdtU.js:1776
    An https://pacman2024windows.vercel.app/assets/index-Df26wdtU.js:1
    <anonymous> https://pacman2024windows.vercel.app/assets/index-Df26wdtU.js:1776

As vite in local i want to access my index.html showing some p5.js sketches, and then if i go to myproject/docs show de index of documentation.

Structure of my project;

enter image description here

This is the caling of scripts in index.html in root project:

 <script type="module" src="js/libraries/p5.min.js"></script>
    <!--Carreguem moduls-->

    <!--Carreguem sketch-->
    <script type="module" src="/js/sketch.mjs"></script>
    <script type="module" src="/js/secondsketch.mjs"></script>

I really need help im a teacher in vocational education, and with my students we are stuck.

Thanks

Linked Chart with [email protected] and [email protected]

Does Linked Chart with [email protected] and [email protected] work?
Below is the code I’m trying.

  • Issue: no crosshair and tooltip in the other chart

When hovering over a dot the corresponding dot in the other chart is getting smaller.

I have derived my example from https://chartjs-plugin-crosshair.netlify.app/samples/

Any help would be very much appreciated.

<!DOCTYPE html>
<html>
<title>LinkedChartNEW.html</title>
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>

<main style="width:90vw;">
  <div><canvas id="chart1"></canvas></div>
  <div><canvas id="chart2"></canvas></div>
</main>

<script>
Chart.Tooltip.positioners.cursor =  function(chartElements, coordinates) {
                                        return coordinates;
                                    };
var yMin = -10;
var yMax = +60;
function generateDataset(label, color) {
  var data = [];
  var x = 0;

  while (x <= 30) {
    data.push({ x: x, y: x });
    x++;
  }

  var dataset = {
    backgroundColor: color,
    borderColor: color,
    showLine: true,
    fill: false,
    pointRadius: 8,
    label: label,
    data: data,
  };
  return dataset;
}

const options = {
  plugins: {
    crosshair: {
      sync: {
        enabled: true,
      }
    },
    tooltip: {
      position: 'cursor',
      mode: 'index',
      intersect: false,
    }
  },
  scales: {
    x: {
        type: 'linear',
        position: 'bottom',
    },
    y: {
        min: yMin,
        max: yMax,
        ticks:{ stepSize: 5, }
    }
  },
};

var chart1 = new Chart(document.getElementById("chart1").getContext("2d"), {
  type: "scatter",
  options,
  data: {
    datasets: [
      generateDataset("A", "red"),
    ]
  }
});

var chart2 = new Chart(document.getElementById("chart2").getContext("2d"), {
  type: "scatter",
  options,
  data: {
    datasets: [
      generateDataset("B", "blue"),
    ]
  }
});

</script>
</body>
</html>

Unable to create a tree view in reactjs

I am trying to create a treeview in React.js. But I am not able to set it properly. Below is my code

App.js

import React from "react";
import TreeHierarchy from "./TreeHierarchy"; // Adjust path if necessary

const App = () => {
return (
<div style={{ padding: "20px" }}>
  <h1>Bahria Hierarchy</h1>
  <TreeHierarchy />
</div>
);
};

export default App;

TreeHierarchy.js

import React from "react";
import { TreeView, TreeItem } from "@mui/x-tree-view";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";

// Sample hierarchy
const hierarchy = {
name: "Bahria",
precincts: [
{
  name: "Precinct-1",
  streets: [
    {
      name: "Road 1",
      meters: ["3092000001", "3092000210"],
    },
    {
      name: "Street 21",
      meters: ["3092000012"],
    },
    ],
    },
    ],
 };

// Recursive function to render the hierarchy tree
const TreeHierarchy = () => {
const renderTree = (node, parentId = "") => {
const nodeId = `${parentId}-${node.name || "node"}`;

return (
  <TreeItem key={nodeId} nodeId={nodeId} label={node.name || "Unnamed"}>
    {node.streets &&
      node.streets.map((street, index) =>
        renderTree(street, `${nodeId}-street-${index}`)
      )}
    {node.precincts &&
      node.precincts.map((precinct, index) =>
        renderTree(precinct, `${nodeId}-precinct-${index}`)
      )}
    {node.meters &&
      node.meters.map((meter, index) => (
        <TreeItem
          key={`${nodeId}-meter-${index}`}
          nodeId={`${nodeId}-meter-${index}`}
          label={`Meter: ${meter}`}
        />
      ))}
  </TreeItem>
);
};

return (
<TreeView
  defaultCollapseIcon={<ExpandMoreIcon />}
  defaultExpandIcon={<ChevronRightIcon />}
>
  {renderTree(hierarchy)}
</TreeView>
);
};

export default TreeHierarchy;

Output

enter image description here

When I click on the main node name I am getting below errors

MUI X: The Tree View component requires all items to have a unique `id` property.
Alternatively, you can use the `getItemId` prop to specify a custom id for each item.
Two items were provided with the same id in the `items` prop: "undefined"
Error: MUI X: The Tree View component requires all items to have a unique `id` property.
Alternatively, you can use the `getItemId` prop to specify a custom id for each item.
Two items were provided with the same id in the `items` prop: "undefined"
at http://localhost:3000/static/js/bundle.js:15169:15
at basicStateReducer (http://localhost:3000/static/js/bundle.js:37272:45)
at updateReducer (http://localhost:3000/static/js/bundle.js:37381:26)
at updateState (http://localhost:3000/static/js/bundle.js:37667:14)
at Object.useState (http://localhost:3000/static/js/bundle.js:38464:20)
at Object.useState (http://localhost:3000/static/js/bundle.js:54836:25)
at useTreeView (http://localhost:3000/static/js/bundle.js:16177:64)
at SimpleTreeView (http://localhost:3000/static/js/bundle.js:12473:83)
at renderWithHooks (http://localhost:3000/static/js/bundle.js:37072:22)
at updateForwardRef (http://localhost:3000/static/js/bundle.js:40321:24)

The tree structure is below

Bharia (Parent node)
  => Precinct (value)
      =>streets (value)
         => meters (value)

I am stuck to it and must be missing something. Any help would be highly appreciated.

How to fix my Peaks.js component which works with direct render but not inside a page

I have a React web app using Peaks.js. When I route straight to my AudioWaveForm component through a BrowserRouter route, it works fine, but when I include it in an empty component it breaks. It still shows the audio, and I can play it with keyboard, but clicking on it with mouse blinks the play-line where I clicked, then immediately moves to the very start and then dissappears.

On the working BrowserRouter route, if I prepend my backend url using an env variable (not needed since I have react proxy set), it breaks the waveform for some reason. If I change the empty component to not include the env variable though, it still is broken.

Working Waveform Route

{
    path: '/waveform',
    element: <AudioWaveform audioFile={'media/song_files/test.mp3'} />
  },

Broken Waveform Route

{
    path: '/waveform',
    element: <AudioWaveform audioFile={`${process.env.REACT_APP_BACKAPI}/media/song_files/test.mp3`} />
  },
 

EmptyComponent.tsx (Broken)

const AnalysisPage = () => {
 return (
<div className='w-full h-full'>
    <AudioWaveform audioFile={'/media/song_files/test.mp3`}/>
  </div>
    
  )
} 

export default AnalysisPage

AudioWaveForm.tsx

import React, { useRef, useEffect, useState, useCallback } from 'react';
import Peaks from 'peaks.js';
import type { PeaksInstance } from "peaks.js";

interface AudioWaveformProps {
    audioFile: string | File;
    timestamp?: number | null
}

const AudioWaveform: React.FC<AudioWaveformProps> = ({ audioFile,  timestamp=null }) => {

    const zoomViewRef = useRef<HTMLDivElement | null>(null);
    const overviewRef = useRef<HTMLDivElement | null>(null); 
    const audioRef = useRef<HTMLAudioElement | null>(null);
    const peaksInstance = useRef<PeaksInstance | null>(null);

    const playFromTimestamp = (timestamp: number) => {
      if (audioRef.current) {
        audioRef.current.currentTime = timestamp;
        peaksInstance.current?.player.seek(timestamp);
        if (audioRef.current.paused) {
          audioRef.current.play();
        }
      }
    };

    useEffect(() => {
      if (timestamp) {
        playFromTimestamp(timestamp);
      }
    }, [timestamp]);

    // initialize peaks.js
    useEffect(() => {
        if (audioRef.current && zoomViewRef.current && overviewRef.current) {
            const audioContext = new AudioContext();
      
            const options = {
              zoomview: {
                container: zoomViewRef.current,
                showPlayheadTime: true,
              },
              overview: {
                container: overviewRef.current,
              },
              mediaElement: audioRef.current,
              webAudio: {
                audioContext: audioContext,
                scale: 128,
                multiChannel: false,
              },
            };
      
            Peaks.init(options, function (err, peaks) {
              if (err) {
                console.error('Error initializing Peaks.js:', err);
              } else {
                if (peaks) {
                  peaksInstance.current = peaks;

                  peaks.on('zoomview.click', (event) => {
                    if (audioRef.current) {
                      audioRef.current.currentTime = event.time;
                    }
                  });

                } else {
                  console.error('Error: Peaks is undefined')
                }
                
              }
            });

            return () => {
              if (peaksInstance.current) {
                peaksInstance.current.destroy();
                peaksInstance.current = null;
              }
          };
        }
        
    }, []);

    // Audio playback with space key
    useEffect(() => {
      const handleKeyDown = (event: KeyboardEvent) => {
        if (event.code === "Space" && audioRef.current) {
          event.preventDefault();
      
          const currentTime = peaksInstance.current?.player.getCurrentTime();
          if (currentTime !== undefined) {
            audioRef.current.currentTime = currentTime; 
            if (audioRef.current.paused) {
              audioRef.current.play();
            } else {
              audioRef.current.pause();
            }
          }
        }
      };
  
      document.addEventListener("keydown", handleKeyDown);
  
      return () => {
        document.removeEventListener("keydown", handleKeyDown);
      };
    }, []);


    
  return (
    <div className='w-full h-full'>
        <div className='w-full h-1/2' ref={zoomViewRef}></div>
        <div className='w-full h-1/2' ref={overviewRef}></div>
        <audio
          ref={audioRef} 
          src={typeof audioFile === "string" ? audioFile : URL.createObjectURL(audioFile)}
        ></audio>
    </div>
  )
}

export default AudioWaveform

Auth using JWT not verifying token

I am trying to make a real time chat application using web sockets and am currently working on adding user login and authentication using jwt but it just isn’t working for some reason

app.get("/", (req, res) => {
  const token = req.headers["authorization"]?.split(" ")[1];
  console.log(token);
  if (!token) {
    return res.redirect("/login");
  }

  jwt.verify(token, secret, (err, decode) => {
    if (err) {
      return res.redirect("/login");
    } else {
      res.sendFile(__dirname + "/public/index.html");
    }
  });
});

This what I have been using but instead of rerouting to login page it just sends the index page.
For starters when the user send the initial get / there is no authorization in header so token should be null/undifined right?

and even if there is authorization with wrong token it still let’s the user pass

Please do let me know what I am doing wrong and any suggestion would be appriciated

Slack Bolt – user_status_changed event

I am working with @slack/bolt, trying to get user_status_changed using Socket Mode. I can see messages when they come in but not when a user changes there status. I put my self in away or avalible and I never see that event.

Here just for developing I am waiting for all events. When I join a channel or message or just about anything I see a log. I just cant get the user_status_changed to show so I can use it.

// Listen for all events and log them
app.event(/.*/, async ({ event }) => {
    console.log('Received event:', event);
    if (event.type === 'user_status_changed') {
        const { user } = event;
        const presence = user.profile.presence;
        console.log(`Received user_status_changed event for user ${user.id}: ${presence}`);
        userPresence.set(user.id, presence);
        console.log(`User ${user.id} is now ${presence}`);
    }
    if (event.type === 'message') {
        console.log(`Received message event in channel ${event.channel}: ${event.text}`);
    }
    if (event.type === 'user_change') {
        const { user } = event;
        const presence = user.profile.presence;
        console.log(`Received user_status_changed event for user ${user.id}: ${presence}`);
        userPresence.set(user.id, presence);
        console.log(`User ${user.id} is now ${presence}`);
    }else{ console.log(event.type)}
});

I have gone thru the docs for about 2 hours and havent found any answers to why this isnt working. I’ve even added EVERY SINGLE scope permission to my bot for now to just blanket the issue.

How to dynamically update streak badges and rewards in a progressive web app using vanilla JavaScript efficiently?

Question:
I am building a progressive web app where users earn streak badges and rewards based on their activity. I want to dynamically update the UI when users unlock new badges, but I am concerned about performance due to frequent DOM updates.

Here’s what I want to achieve:

  1. Minimize unnecessary DOM manipulation to ensure smooth performance.
  2. Dynamically update only the elements that have changed (e.g., a new badge or reward).
  3. Ensure the logic remains efficient and clean using vanilla JavaScript (no frameworks).

What I have tried:

function updateStreaks(userProgress) {
    const badgesContainer = document.getElementById("streak-badges");

    streaks.forEach((streak) => {
        if (userProgress >= streak.day && !document.querySelector(`[data-day="${streak.day}"]`)) {
            const badge = document.createElement("div");
            badge.className = "badge";
            badge.setAttribute("data-day", streak.day);

            badge.innerHTML = `
                <h3>${streak.badge}</h3>
                <p>Reward: ${streak.reward}</p>
            `;

            badgesContainer.appendChild(badge);
        }
    });
}

What I expected:
I expected that when the user reaches a certain milestone (e.g., day 7), the corresponding badge would be dynamically added to the DOM without affecting previously added badges. The page should update smoothly without re-rendering the entire list of badges.

url works in browser but not from js fetch

Note that although this question references wikidata, it is really a javascript fetch question. Also, this is not the wikidata api. I’m just trying to load a simple page from a url.

I want to access wikidata using a QID. My code generates a URL like

https://www.wikidata.org/wiki/Q111943988

which works from the browser (try it). But when I try to get it by calling fetch from the js script in my web page I get errors. Here is my code …

      const wdataResp = await fetch("https://www.wikidata.org/wiki/Q111943988",
        {method: "GET",
         mode: 'no-cors',
         headers: {
          'Content-Type': 'application/json',
           'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
                         'AppleWebKit/537.36 (KHTML, like Gecko) ' +
                         'Chrome/131.0.0.0 Safari/537.36'}
        });

It gives this response …

wdataResp: Response
  body: null
  bodyUsed: false
  headers: <weird set of functions here>
  ok:false
  redirected:false
  status:0
  statusText:""
  type:"opaque"
  url:""

Note the ok:false. I don’t think this is a cors problem. I got cors errors from this code and the mode: 'no-cors'
fixed it.

Can someone give me ideas on how to fix this? Thanks in advance.

Algorithm for generating meaningful names

(I am writing through a translator, if the idea of what I wanted to say gets lost, please clarify in the comments.)
How do I implement an algorithm for generating meaningful names?
Let’s say that when creating a user and the algorithm was running, the username was not “AsnaFSff234Sdanfs!123”, but “SweetDreams”. The usual substitution of random words that would be stored in arrays is too heavy. Are there any other ways?
Stack:
js, expressjs, postgres.

I haven’t tried it yet, but the methods I found on the Internet look very expensive.