I have started learning to create Routes in react but i am struck with a code where various contents of home page are not in a single component

As I stated that I have learned some basics of routing but there always a path defined "/" for home element whereas in my case I have many components of home page that is giving me a headache. I try to wrap them in app.jsx and then use them as home page but at both "http://localhost:5173" and "http://localhost:5173/about/" locations same app.jsx is rendering.

app.jsx

import Navbar from "./components/Navbar";
import HeroSection from "./components/HeroSection";
import FeatureSection from "./components/FeatureSection";
import Workflow from "./components/Workflow";
import Footer from "./components/Footer";
import Pricing from "./components/Pricing";
import Testimonials from "./components/Testimonials";
import { Outlet } from 'react-router-dom';

const App = () => {
  return (
    <>
      <Navbar />
      <div className="max-w-7xl mx-auto pt-20 px-6">
        <HeroSection />
        <FeatureSection />
        <Workflow />
        <Pricing />
        <Testimonials />
        <Footer />
        <Outlet />
      </div>
    </>
  );
};

export default App;

main.jsx

import React, { Children } from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { RouterProvider, createBrowserRouter } from 'react-router-dom'
import App from "./App"
import About from './components/About'

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: '/about',
        element: <About />,
      }
    ]
  }
])

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
)

I am expecting to create dynamic route as stated

Why Is My Code Producing Unexpected Results Despite Following Documentation?

I’m facing an issue where my code is producing unexpected results, even though I’ve followed the documentation and examples closely. I’ve reviewed my code multiple times and tried various debugging techniques, but I’m still unable to resolve the issue. Has anyone else encountered similar problems, and what strategies or solutions have you found effective in identifying and fixing such discrepancies?

Why Is My Code Producing Unexpected Results Despite Following Documentation?

in JavaScript navigator.clipboard.readText() is returning [object Promise] even though it is awaited [duplicate]

In the following example, highlight and copy “this is text”. That is what should be added to the clipboard. However [object Promise] is added instead. readText() is awaited so this is the incorrect result. How do I make this work?

<html>
This is text

<script>
document.addEventListener('copy', function (e) {
    var result = textCopied();
    e.clipboardData.setData('text/plain', result);
    e.preventDefault();
});

async function textCopied() {
var clipboardContents = await navigator.clipboard.readText();
return clipboardContents 
}
</script>
</html>

How to resovle – “Refused to execute inline script because it violates the following Content Security Policy”

I’m setting up Mixpanel in a simple chrome extension using Vanilla JS. I’m not using NPM but following this docs.

Below is my set-up where I pull in the Mixpanel SDK in the Index.html:

<!DOCTYPE html>
<html lang="en">
<head>

    <script type="text/javascript">
    <!-- Paste this right before your closing </head> tag -->
<script type="text/javascript">
  (function (f, b) { if (!b.__SV) { var e, g, i, h; window.mixpanel = b; b._i = []; b.init = function (e, f, c) { function g(a, d) { var b = d.split("."); 2 == b.length && ((a = a[b[0]]), (d = b[1])); a[d] = function () { a.push([d].concat(Array.prototype.slice.call(arguments, 0))); }; } var a = b; "undefined" !== typeof c ? (a = b[c] = []) : (c = "mixpanel"); a.people = a.people || []; a.toString = function (a) { var d = "mixpanel"; "mixpanel" !== c && (d += "." + c); a || (d += " (stub)"); return d; }; a.people.toString = function () { return a.toString(1) + ".people (stub)"; }; i = "disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking start_batch_senders people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split( " "); for (h = 0; h < i.length; h++) g(a, i[h]); var j = "set set_once union unset remove delete".split(" "); a.get_group = function () { function b(c) { d[c] = function () { call2_args = arguments; call2 = [c].concat(Array.prototype.slice.call(call2_args, 0)); a.push([e, call2]); }; } for ( var d = {}, e = ["get_group"].concat( Array.prototype.slice.call(arguments, 0)), c = 0; c < j.length; c++) b(j[c]); return d; }; b._i.push([e, f, c]); }; b.__SV = 1.2; e = f.createElement("script"); e.type = "text/javascript"; e.async = !0; e.src = "undefined" !== typeof MIXPANEL_CUSTOM_LIB_URL ? MIXPANEL_CUSTOM_LIB_URL : "file:" === f.location.protocol && "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^///) ? "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js" : "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js"; g = f.getElementsByTagName("script")[0]; g.parentNode.insertBefore(e, g); } })(document, window.mixpanel || []);
</script>
</head>
<body>
    <script type="module" src="popup.js"></script>
</body>
</html>

Within my popup.js I reference the below

 //Import Mixpanel SDK
import mixpanel from "mixpanel-browser";
 
// Near entry of your product, init Mixpanel
mixpanel.init("0000", {
  debug: true,
  track_pageview: true,
  persistence: "localStorage",
});

I see the following errors in the console when I check to see if Mixpanel object exist

  index.html:12 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-6VDlGRSSdUDK2nuG1Ys7GZ0tuFVwEcvszIXy9+2ULI4='), or a nonce ('nonce-...') is required to enable inline execution.

index.html:12 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*". Either the 'unsafe-inline' keyword, a hash ('sha256-6VDlGRSSdUDK2nuG1Ys7GZ0tuFVwEcv'), or a nonce ('nonce-...') is required to enable inline execution.

index.html:1 Uncaught TypeError: Failed to resolve module specifier "mixpanel-browser". Relative references must start with either "/", "./", or "../".

how to limit requests made by webworker in angular

Currently in my Angular project we upload batches of files using the webworker. It turns out that the webworker can make up to six requests at a time (depending on the browser from what I’ve read on other forums), however my backend only processes one request at a time, so depending on the processing time to return the response to the frontend ( despite being a promise) ends up exceeding the waiting time.

As a stopgap, I added a 1-second timeout between requests on the frontend so the backend had enough time to process and return the response.

What I would like to know is if I can reduce these simultaneous requests from the webworker? For example, instead of 6 requests at the same time, limit it to 3?

F11 StepInto just goes to next line in VSCode DEV 1.93.0

I am trying to follow the https://github.com/microsoft/vscode/wiki/How-to-Contribute
steps to Build, to Run, and then to Debug.
I built into C:H_Paulvscode1930 It has product.json “nameShort”: “Code – OSS”
and package.json “name”: “code-oss-dev”, “version”: “1.93.0”,

My app (Pencil) has package.json with “main”: “index.js”, part of index.js is

BP1 L90    var mainUrl = "file://" + __dirname + "/app.xhtml";
BP2 L91    mainWindow.loadURL(mainUrl);
BP3 L92    mainWindow.show();

I then enter BP (breakpoint) on those lines.
When it breaks at Line 91, I want to F11 StepInto vscode1930
and then F10 single step to see whats happening to the app’s source code

But F11 just continues with Pencil Line92.

Below are launch.json-s for vscode1930 and for Pencil:

//  vscode1930-launch.txt   from  launch.js   expanded for the compound item.
    {
        "name": "VS Code",
        "stopAll": true,
        "debugStdLib":true,
        "configurations": [
            "Launch VS Code Internal",
            "Attach to Main Process",
            "Attach to Extension Host",
            "Attach to Shared Process",
        ],
        "preLaunchTask": "Ensure Prelaunch Dependencies",
        "presentation": {
            "group": "0_vscode",
            "order": 1
        }
    },
//====================================================
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch VS Code Internal",
            "windows": {
                "runtimeExecutable": "${workspaceFolder}/scripts/code.bat"
            },
            "osx": {
                "runtimeExecutable": "${workspaceFolder}/scripts/code.sh"
            },
            "linux": {
                "runtimeExecutable": "${workspaceFolder}/scripts/code.sh"
            },
            "port": 9222,
            "timeout": 0,
            "env": {
                "VSCODE_EXTHOST_WILL_SEND_SOCKET": null,
                "VSCODE_SKIP_PRELAUNCH": "1"
            },
            "cleanUp": "wholeBrowser",
            "runtimeArgs": [
                "--inspect-brk=5875",
                "--no-cached-data",
                "--crash-reporter-directory=${workspaceFolder}/.profile-oss/crashes",
                // for general runtime freezes: https://github.com/microsoft/vscode/issues/127861#issuecomment-904144910
                "--disable-features=CalculateNativeWinOcclusion",
                "--disable-extension=vscode.vscode-api-tests"
            ],
            "userDataDir": "${userHome}/.vscode-oss-dev",
            "webRoot": "${workspaceFolder}",
            "cascadeTerminateToConfigurations": [
                "Attach to Extension Host"
            ],
            "pauseForSourceMap": false,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ],
            "browserLaunchLocation": "workspace",
            "presentation": {
                "hidden": true,
            },
            // This is read by the vscode-diagnostic-tools extension
            "vscode-diagnostic-tools.debuggerScripts": [
                "${workspaceFolder}/scripts/hot-reload-injected-script.js"
            ]
        },
//=========================================
        {
            "type": "node",
            "request": "attach",
            "name": "Attach to Main Process",
            "timeout": 30000,
            "port": 5875,
            "continueOnAttach": true,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ],
            "presentation": {
                "hidden": true,
            }
        },
//=========================================
        {
            "type": "node",
            "request": "attach",
            "restart": true,
            "name": "Attach to Extension Host",
            "timeout": 0,
            "port": 5870,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js",
                "${workspaceFolder}/extensions/*/out/**/*.js"
            ]
        },
//=========================================
        {
            "type": "node",
            "request": "attach",
            "restart": true,
            "name": "Attach to Shared Process",
            "timeout": 0,
            "port": 5879,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ]
        },
//=========================================
// Pencil launch.json
{
    "justMyCode": false,
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Electron: Main",
            "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
            "windows": {
                "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
            },
            "runtimeArgs": [
                "."
            ],
            "trace": true,            
            "env": {
                "VSCODE_DEBUG_MODE": "true"
            },
            "sourceMaps": true,
            "cwd": "${workspaceFolder}",
            "outputCapture": "std",  
            "outFiles": [ "${workspaceFolder}/out/**/*.js" ],  
            "localRoot": "${workspaceFolder}"
        }
    ]
}

Parsing ‘s in JSON throws bad control character in string literal error

I am using WinDEV Mobile to dynamically build Javascript controls. I have a problem when new lines or * is used within the JSON. When I remove them, the following code works:

const json = `[{"id":1,"data":{"visible":true,"visibleFunction":"","repeatCount":1,"required":"false","readOnly":false},"text":"Some RandomnnWords With a \nnAnd new lines","type":"textbox"}]`;

console.log(JSON.parse(json));

However, when they’re left in there, the error I receieve is the following due to the escaped * characters:

SyntaxError: JSON.parse: bad control character in string literal

I have no control on WinDEV Mobile to alter how this is passed in as it doesn’t support many JSON functions to change this and I need to support the new lines.

I originally tried to do a .replace() to convert any to \ but the issue is, this JSON definition can have Base64 images inside of it which then fails to parse.

Is there anything I can do in Javascript to prevent the unescaping of the n and \?

Merge objects inside an array of objects with duplicates

I have “available” data and want to convert it into “desired”.

I tried to merge all objects inside array using this but its not working coz as you can see for timestamp = 10 we have 2 values of sw_version

const available = [
    {
      "timestamp": 10,
      "sw_version": "AA"
    },
    {
      "timestamp": 10,
      "sw_version": "AB"
    },
    {
      "timestamp": 20,
      "sw_version": "QFX-1.2.5 B"
    },
    {
      "timestamp": 10,
      "pressure": 14.75
    },
    {
      "timestamp": 20,
      "pressure": 14.22
    },
    {
      "timestamp": 10,
      "temperature": 15.96
    },
    {
      "timestamp": 20,
      "temperature": 38.50
    }
  ]

const desired = [
    {
      "timestamp": 10,
      "sw_version": "AA",
      "pressure": 14.75,
      "temperature": 15.96
    },
    {
      "timestamp": 10,
      "sw_version": "AB",
      "pressure": 14.75,
      "temperature": 15.96
    },
    {
      "timestamp": 20,
      "sw_version": "QFX-1.2.5 B",
      "pressure": 14.22,
      "temperature": 38.5
    }
  ]

I am new to javascript and i tried below function

const output = available.reduce((result, item) => {
      const i = result.findIndex((resultItem) => resultItem.timestamp === item.timestamp);
      if (i === -1) {
        result.push(item);
      } else {
        result[i] = { ...result[i], ...item };
      }
      return result;
    }, []);

The output was

[
    {
        "timestamp": 10,
        "sw_version": "AB",
        "pressure": 14.75,
        "temperature": 15.96
    },
    {
        "timestamp": 20,
        "sw_version": "QFX-1.2.5 B",
        "pressure": 14.22,
        "temperature": 38.5
    }
]

As you can see in the desired output i want 2 objects with timestamp = 10 but in the function output its is overwriting the first one and keeping only one object

html canvas isometric tile map rendering

am trying to achieve something like this

desired result

but i always endup tiles are not rendering when reaching to boundries , it should be drawing 200×200 map how ever it only show 17×17

the game am building is similer in idea to travian kingdoms but whole different story and design

here is the code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Isometric Map with Canvas</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
        canvas {
            display: block;
            background-color: #e0e0e0;
        }
    </style>
</head>
<body>
    <canvas id="mapCanvas"></canvas>
    <script src="script.js"></script>
</body>
</html>

const canvas = document.getElementById('mapCanvas');
const ctx = canvas.getContext('2d');

const tileWidth = 128; // Tile width
const tileHeight = 64; // Tile height
const gridSize = 1000; // Large grid size for 1,000,000 tiles (1000x1000)
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let offsetX = canvas.width / 2; // Start with center offset
let offsetY = canvas.height / 2; // Start with center offset
let isDragging = false;
let startX, startY;

// Test data for tiles using colors
const testData = [
    '#76b041', // Grass
    '#557a29', // Forest
    '#c2b280', // Plain
    '#a4a4a4', // Mountain
];

function drawTile(x, y, screenX, screenY, color) {
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.moveTo(screenX, screenY);
    ctx.lineTo(screenX + tileWidth / 2, screenY + tileHeight / 2);
    ctx.lineTo(screenX, screenY + tileHeight);
    ctx.lineTo(screenX - tileWidth / 2, screenY + tileHeight / 2);
    ctx.closePath();
    ctx.fill();
    ctx.strokeStyle = '#000'; // Optional: add border to each tile
    ctx.stroke();

    // Draw the coordinates on the tile
    ctx.fillStyle = '#000';
    ctx.font = '14px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(`(${x}, ${y})`, screenX, screenY + tileHeight / 2);
}

function loadMap() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas

    // Calculate how many tiles we need to draw to cover the screen
    const tilesX = Math.ceil(canvas.width / tileWidth) + 2;
    const tilesY = Math.ceil(canvas.height / tileHeight) + 2;

    for (let x = -tilesX; x <= tilesX; x++) {
        for (let y = -tilesY; y <= tilesY; y++) {
            // Convert grid coordinates to screen coordinates
            const screenX = (x - y) * (tileWidth / 2) + offsetX;
            const screenY = (x + y) * (tileHeight / 2) + offsetY;

            // Draw the tile
            const tileColor = testData[(x + y + gridSize) % testData.length];
            drawTile(x, y, screenX, screenY, tileColor);
        }
    }
}

canvas.addEventListener('mousedown', onMouseDown);
canvas.addEventListener('mousemove', onMouseMove);
canvas.addEventListener('mouseup', onMouseUp);

function onMouseDown(e) {
    isDragging = true;
    startX = e.clientX;
    startY = e.clientY;
}

function onMouseMove(e) {
    if (!isDragging) return;

    const dx = e.clientX - startX;
    const dy = e.clientY - startY;

    offsetX += dx;
    offsetY += dy;

    startX = e.clientX;
    startY = e.clientY;

    loadMap(); // Redraw the map based on the new position
}

function onMouseUp() {
    isDragging = false;
}

// Initial load
loadMap();

// Handle window resizing
window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    loadMap();
});

current result

your help is appreciated thank you in advance

i tried every possible solution with no hope

Why won’t onmouseover=” ” work in this specific area?

I’m trying to make a hamburger menu, I have made the actual hamburger, but want to add a border, or maybe slightly increase the size of each div in the hamburger or some other fancy effect.

When I write function that targets this it doesn’t work, however when i set it to change the body backgroundColor it works, or if i set it to open a prompt it works.

what works:

Display: none;
background-color: 'red';
<div class="nav-ham" onmouseover="prompt()">

What isn’t working:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="nav-ham" onmouseover="hamHover()">
        <div class="ham-bars"></div>
        <div class="ham-bars"></div>
        <div class="ham-bars"></div>
    </div>


<script src="script.js"></script>
</body>
</html>

CSS

body {
    background-color: #F9F7F7;
}

.nav-ham {
    position: absolute;
    top: 0;
    right: 5%;
    width: 50px;
    height: 50px;
}

.ham-bars {
    width: 100%;
    height: 15%;
    border-radius: 10%;
    background-color: #112D4E;
}

.nav-ham :nth-child(1) {
    position: absolute;
    top: 15%;
}

.nav-ham :nth-child(2) {
    position: absolute;
    top: 45%;
}

.nav-ham :nth-child(3) {
    position: absolute;
    top: 75%;
}

JS

function hamHover() {
    document.getElementsByClassName('ham-bars').style.height = '20%';
}

I can only come to the conclusion that I’m making a typo I’m not spotting or i have a fundamental misunderstanding of the language, which is most likely given i only just completed the course last week.

I imagine it’s something basic, but I am new to this so forgive me.

Threlte stopPropagation on click event

Using Threlte i can create two shapes in a file like so :

<T.Mesh on:click={(e) => console.log("little shape") } >
</T.Mesh>

<T.Mesh on:click={(e) => console.log("bigger shape") } >
</T.Mesh>

In order to avoid the second shape to tigger it’s event on a click on the small one, I can add e.stopPropagation() like so :

<T.Mesh on:click={(e) => {console.log("little shape"); e.stopPropagation() }}>
</T.Mesh>

Issue comes when I wants to create a separate component out of my little shape. stopping propagation inside the other file is pointless, and stopImmediatePropagation() isn’t recognized as a function.

App.svelte
<LittleShape
  on:click >
>/LittleShape>

<T.Mesh
   on:click={(e) => {console.log("bigger shape") }} >
</T.Mesh>
LittleShape.svelte
<T.Mesh></T.Mesh>

How can I split my file while preventing propagation

Thanks in advance!

Applying an ‘active’ class to a button isn’t working

I have an image portfolio with filter buttons at the top. When the user selects one of these filters, the button should change colour to show that it is selected. I created a script to handle this, but it’s not working and I’m unsure why it’s not.

HTML:

<div class="dp-projects-button-container" id="dp-projects-button-container" style="margin-bottom: 35px;">

<button id="btn" class="btn active" onclick="filterSelection('all')"> SHOW ALL</button>

<button id="btn" class="btn" onclick="filterSelection('residential_multiunit')"> RESIDENTIAL: MULTI-UNIT</button>

<button id="btn" class="btn" onclick="filterSelection('residential_privatehouses')"> RESIDENTIAL: PRIVATE HOUSES</button>

<button id="btn" class="btn" onclick="filterSelection('offices_fitout')"> OFFICES & FIT-OUT</button>

<button id="btn" class="btn" onclick="filterSelection('sports_leisure')"> SPORTS & LEISURE</button>

<button id="btn" class="btn" onclick="filterSelection('education_childcare')"> EDUCATION & CHILDCARE</button>

<button id="btn" class="btn" onclick="filterSelection('admin_finance')"> ADMINISTRATIVE & FINANCIAL</button>

<button id="btn" class="btn" onclick="filterSelection('retail')"> RETAIL</button>

<button id="btn" class="btn" onclick="filterSelection('industrial_warehousing')"> INDUSTRIAL & WAREHOUSING</button>

<button id="btn" class="btn" onclick="filterSelection('restaurant_public_houses')"> RESTAURANTS & PUBLIC HOUSES</button>

<button id="btn" class="btn" onclick="filterSelection('hotels')"> HOTELS</button>

<button id="btn" class="btn" onclick="filterSelection('health_agedcare')"> HEALTH & AGED CARE</button>
</div>

JAVASCRIPT:

var btnContainer = document.getElementById("dp-projects-button-container");
var btns = btnContainer.getElementsByClassName("btn");

for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function(){
        var current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
    });
}

(I have CSS which applies the colour to .btn.active)

I’ve tried playing around with ‘class’ vs ‘id’, but to no avail. I’ve also triple-checked my class names, css properties and spelling, also to no avail.

I’m fairly new to JavaScript so any help is really appreciated, thanks

Window and Leveling doesn’t update to image displayed in Javascript

I have these html file that I is a simple window to load an image and to use two sliders to adjust the window and leveling of the loaded image. The image loads and the sliders adjust but the image doesn’t update as the sliders move.

I am very new to js and html so it’s probably something obvious

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Window and Level Adjustment</title>
    <style>
        #imageCanvas {
            border: 1px solid black;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

    <canvas id="imageCanvas" width="512" height="512"></canvas>
    <br>
    <label for="window">Window: </label>
    <input type="range" id="window" min="0" max="1000" value="500">
    <br>
    <label for="level">Level: </label>
    <input type="range" id="level" min="0" max="1000" value="500">

    <script>
        const canvas = document.getElementById('imageCanvas');
        const ctx = canvas.getContext('2d');

        const windowSlider = document.getElementById('window');
        const levelSlider = document.getElementById('level');

        let originalImageData;
        let imageData;

        // Load the image
        function loadImage() {
            const img = new Image();
            img.src = 'output_image.png';  // Load the uploaded image
            img.onload = function () {
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                originalImageData = new Uint8ClampedArray(imageData.data);

                // Calculate min and max intensity for dynamic slider range
                let minIntensity = 255, maxIntensity = 0;
                for (let i = 0; i < originalImageData.length; i += 4) {
                    let intensity = originalImageData[i];
                    if (intensity < minIntensity) minIntensity = intensity;
                    if (intensity > maxIntensity) maxIntensity = intensity;
                }

                console.log("Min intensity:", minIntensity);
                console.log("Max intensity:", maxIntensity);

                windowSlider.min = 0;
                windowSlider.max = maxIntensity - minIntensity;
                windowSlider.value = (windowSlider.max - windowSlider.min) / 2;

                levelSlider.min = minIntensity;
                levelSlider.max = maxIntensity;
                levelSlider.value = (levelSlider.max - levelSlider.min) / 2;

                applyWindowLevel();
            };
        }

        function applyWindowLevel() {
            const window = parseInt(windowSlider.value);
            const level = parseInt(levelSlider.value);
            const minVal = level - (window / 2);
            const maxVal = level + (window / 2);

            // Create a copy of the original image data to work on
            imageData.data.set(originalImageData);

            for (let i = 0; i < originalImageData.length; i += 4) {
                let intensity = originalImageData[i];
                let adjusted = (intensity - minVal) * (255 / (maxVal - minVal));
                adjusted = Math.min(Math.max(adjusted, 0), 255);

                imageData.data[i] = imageData.data[i + 1] = imageData.data[i + 2] = adjusted;
            }

            ctx.putImageData(imageData, 0, 0);
        }

        windowSlider.addEventListener('input', applyWindowLevel);
        levelSlider.addEventListener('input', applyWindowLevel);

        loadImage();

    </script>

</body>
</html>

This is output Displayed Image

validate and convert input string in react

I have one form in react in which I have used formik and Yup library for validations. I have requirement that input field should allow only lowercase alphanumeric values which allow hyphen and length between 2 to 30 characters. Also if user is typing Uppercase letters or space then convert that string to lowercase and replace space with hyphen.
e.g. for input like “Shop name123” should convert to “shop-name123”

formik validation is as follows:

postfix: Yup.string()
                  .required(message.ENTER_POSTFIX)
                  .matches(new RegExp("^[a-z0-9- ]{2,30}$"), {
                    message: message.PUBLIC_URL_POSTFIX_INVALID,
                  })

on change of that field I have following code

<Field
                          type="text"
                          className="form-control"
                          style={{ marginTop: "32px" }}
                          value={values.postfix? values.postfix: ""}
                          name="postfix"
                          onChange={(e) => {
                            setFieldValue(
                              "postfix",
                              tranformStrToVar(e.target.value)
                            );
                          }}
                        />

method tranformStrToVar as follows

export function tranformStrToVar(str) {
  let newStr = "";
  if (str) {
    newStr = str.replace(/s+/g, "-").toLowerCase();
    newStr.match(/[^/]+/g).join("-");
  }
  return newStr;
}

With above code working for some cases and getting failed if input has only “—–” etc. That also should not allowed.

How should I validate and convert input at same time and get valid, required input having lowercase alphanumeric seperated by hyphen having character length between 2 to 30 ?

Please help and guide. Thanks