event.preventDefault() affecting further execution of code

There are 3 .ejs pages this project index.ejs, loading.ejs and result.ejs. index loads first and has the following code in its script tag:

document.addEventListener("DOMContentLoaded", function () {
      document.querySelector(".form-button").addEventListener("click", async (event) => {
        event.preventDefault();
        window.location.href = "/loading";
        const response = await fetch("/submit", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: new URLSearchParams(new FormData(document.querySelector(".form"))),
        });
      });
    });

This is the post request in the node-express server:

app.post("/submit", async (req, res) => {
  const form_link = req.body.form_link;
  const pythonProcess = await spawn("python", ["./py_scripts/script.py", form_link]);
  pythonProcess.on("exit", () => {
    console.log("Python script finished");
    res.redirect("/result");
  });
});

app.get("/result", (req, res) => {
  res.render("result.ejs");
});

The goal is to render the ‘loading.ejs’ file once the button is clicked until the Python script finishes executing. Once the Python script is done, ‘result.ejs’ is supposed to render.

The problem is that ‘loading.ejs’ is loading, but ‘result.ejs’ is not, even after the script is over. This is possibly beacuse of (my guess)’event.preventDefault()’ affecting what was supposed to happen.

Is it possible to make express handle it instead of working it all out in the script tag of ejs files

I tried asking ChatGPT, claude.ai, Gemini but none of their solution seem to work

Allow dragging items below window height. Vanilla JavaScript

I am trying to build a site for my client, which is not dissimilar to Miro (or other whiteboard apps).

The concept is that individual elements are laid out using absolute positioning but the admin can drag them in the viewport and set width and height properties for each element.

I cannot get any method to work that will allow dragging below the original window height (even though the entire document has elements with heights set greater than the window height).

I have tried 3 methods:

  1. Set some large height property on the wrapper. https://jsfiddle.net/lharby/afjwsm75/
const draggingClass = 'dragging';

class draggable {
    constructor(element, node = [ document ] ) {
        this.node = node;
        this.el = element;

        if ( this.el ) {
            this.mouseDown = this.mouseDown.bind(this);
            this.mouseUp = this.mouseUp.bind(this);
            this.mouseMove = this.mouseMove.bind(this);
        }
    }

    setHandle( handle ) {
        this.handle = handle;
        return this;
    }

    setCallback( callback ) {
        this.callback = callback;
        return this;
    }

    mouseDown( event ) {
        if ( this.callback?.start ) this.callback.start( event, this.el )
        else this.el.classList.add(draggingClass)        
        for ( const node of this.node ) {
            node.addEventListener('mouseup', this.mouseUp);
            node.addEventListener('mousemove', this.mouseMove);
            node.addEventListener('mouseleave', this.mouseUp);
        }
        this.el.addEventListener('mouseleave', this.mouseUp);
    }

    mouseUp( event ) {
        if ( this.callback?.end ) this.callback.end( event, this.el )
        else this.el.classList.remove(draggingClass)
        for ( const node of this.node ) {
            node.removeEventListener('mouseup', this.mouseUp);
            node.removeEventListener('mousemove', this.mouseMove);
            node.removeEventListener('mouseleave', this.mouseUp);
        }
        this.el.removeEventListener('mouseleave', this.mouseUp);
    }

    mouseMove(event) {
        if ( this.callback?.move ) {
            this.callback.move( event, this.el );
        } else {
            const style = window.getComputedStyle(this.el);
            const x = (parseFloat(style.getPropertyValue('left')) || 0) + event.movementX;
            const y = (parseFloat(style.getPropertyValue('top')) || 0) + event.movementY;
            const rect = this.el.getBoundingClientRect();
            const viewHeight = window.innerHeight || document.documentElement.clientHeight;
            const viewWidth = window.innerWidth || document.documentElement.clientWidth;
            const maxX = viewWidth - rect.width;
            const maxY = viewHeight - rect.height;
            const constrainedX = Math.max(0, Math.min(x, maxX));
            const constrainedY = Math.max(0, Math.min(y, maxY));
            this.el.style.position = 'absolute';
            this.el.style.top = constrainedY + 'px';
            this.el.style.left = constrainedX + 'px';
        }
    }

    run() {
        const handle = this.handle ?? this.el
        handle.addEventListener('mousedown', this.mouseDown)
    }

    stop() {
        const handle = this.handle ?? this.el
        handle.removeEventListener('mousedown', this.mouseDown)
    }
}

const boxes = document.querySelectorAll('.box');
const movable1 = new draggable(boxes[0]);
const movable2 = new draggable(boxes[1]);
movable1.run();
movable2.run();
body {
    font-family: monospace;
}

.wrapper {
    min-height: 400vh;
    background-color: rgb(255 0 0 / 10%);
    top: 10px;
    right: 10px;
    bottom: 10px;
    left: 10px;
    overflow-y: scroll;
}

.box {
    position: absolute;
    padding: 10px;
    resize: both;
    height: 150px;
    width: 150px;
    margin-bottom: 20px;
    background: #f0f0f0;
    border: 2px solid #555;
    overflow: auto;
    background-image: linear-gradient(-45deg, #ccc 10px, transparent 10px);
}

.second {
    top: 50px;
    left: 50px;
}

.third {
    top: 100px;
    left: 100px;
}

.heading {
    background: red;
    padding: 5px 10px;
}

.dragging {
    opacity: 0.9;
    border: 2px dashed #8181b9;
    user-select: none;
    z-index: 2;
    cursor: move;
}

.actions {
    display: flex;
    flex-direction: column;
    position: absolute;
    right: 0;
    z-index: 1;
}
<div class="outer">
    <div class="wrapper">
        <div class="box">
            I am box 1
        </div>
        <div class="box second">
            I am box 2
        </div>

        <div class="box second third dragging">
            I am box 3
        </div>
    </div>
</div>
  1. Set html to position fixed with no scroll and place boxes inside a div that does allow scrolling with a large height. https://jsfiddle.net/lharby/25oqth67/

HTML is same as above, but using this CSS

html.no-scroll {
    overflow-y: hidden;
}

.outer {
    position: fixed;
    top: 0;
    bottom: 0;
    width: 100%;
}

.wrapper {
    height: 100%;
    background-color: rgb(255 0 0 / 10%);
    top: 10px;
    right: 10px;
    bottom: 10px;
    left: 10px;
    overflow-y: scroll;
}

.box {
    position: relative; // I also added a JS toggle to switch position from relative to absolute
    ...
}
  1. Dynamically try and set the height of the document, or window height.
    https://jsfiddle.net/lharby/e8fb6537/

Similar HTML and CSS to the previous examples but here is some JS

let vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);

const trigger = document.querySelector('.actions button');
trigger.addEventListener('click', () => {
    let root = document.querySelector(':root');
    let docHeight = document.documentElement.clientHeight;
    let winHeight = window.innerHeight;
    docHeight = 1200; // also tried `${1200}px`
    winHeight = 1300; // also tried `${1300}px`
    root.style.height = `${1400}px`;
    console.log(docHeight, winHeight, root.style.height);
    console.log(vh);
});

I also tried adding an element below the draggable wrapper. As well as setting height properties on the html and body. It seems nothing will let the user drag the boxes below the original window height. Unless I am missing some easy css fix.

The JSFiddles contain all of the other functionality (dragging boxes) which is working as is, but I have added a code snippet to the first example, which would be the easiest to figure out as I assume this could be pure CSS.

Funnily enough if you google this topic there seem to be a glut of answers about limiting the dragging to inside a specific container.

I would rather avoid a library if possible.

https://www.google.com/search?q=javascript+drag+item+beyond+window+height+site%3Astackoverflow.com

Any help much appreciated.

What is the best way to manage data persistence for iOS and Android by developing an app with Quasar Framework?

I’m developing an app for Android and ios with Quasar Framework. Locally data is saved with quasar LocaStorage. Is this procedure enough to ensure data persistence on the device and to exceed the guidelines for iOS?

I haven’t tried to upload the app to the store yet but I would like to manage the data permanence properly to prevent my app from being rejected

How to call a postgresql function that expects an array of custom types from Azure (node)

I have an Azure function written in node. This function connects to a postgresql database using the pg library. It then calls a posgresql function that upserts some data.

When the postgresql function has simple parameters, it works great.

However, I’d like to have the postgresql function expect an array of custom types. E.g.:

CREATE TYPE fund_type AS (
    symbol char(5),
    fund_name text,
    fee DOUBLE PRECISION
);

CREATE OR REPLACE FUNCTION fn_upsert_funds(
    funds fund_type[]
)
...

In the Azure function, I have something like this:

const funds = [
    {
        symbol: "ABCDX"
        fund_name: "Acme Fund"
        fee: 0.25
    },
    {
        symbol: "BCDEX"
        fund_name: "Beta Fund"
        fee: 0.40
    },
]

const res = await client.query('SELECT * from fn_upsert_funds($1::fund_type[])', [funds]);

This doesn’t work – I get an error: malformed record literal error.

I’m sure I need to format/structure the parameter differently, but I can’t figure out how I’m supposed to do it.

Thanks in advance for your advice!

Drawing anti-aliased round dots from vertices in three.js

I am trying to make a grid of points in three.js. I want them to look nice and round, as well as implement distance attenuation. the default PointsMaterial offered by three.js draws square vertices. Therefore I attempt to implement custom shaders.

Vertex:

void main() {
    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * mvPosition;
    gl_PointSize = ${particleSize}.0 / gl_Position.z; // Set the desired point size
}

Fragment:

void main() {
    vec2 coord = gl_PointCoord - vec2(0.5); // Center at (0.5, 0.5)
    float distance = length(coord);
    if (distance < 0.4) {
        gl_FragColor = vec4(0.3, 0.3, 0.3, 1.0); // Inside the circle
    } else if (distance > 0.5) {
        gl_FragColor = vec4(0.3, 0.3, 0.3, 0.0); // Outside the circle
    } else {
        gl_FragColor = vec4(0.3, 0.3, 0.3, 0.5 - (distance - 0.4) * 0.5 / 0.1); // Fade the boundry
    }

The problem is that this scales with the size of the circle. When the circle is too large the borders become fuzzy, and would still disappear when the circle is too small. One idea is to sample different subpixels. However, since the gl_PointSize isn’t passed into the fragment shader it would not know how a shift in the gl_FragCoord would change gl_PointCoord and wouldn’t have enough information for subsampling. Is there any way to achieve smooth round dots without using a rasterized texture?

How to achieve parallel routing in nextjs inside catch all segment?

Project folder structure..

You can see the project folder structure i am using in next js. I am currently working on parallel routing concept in nextjs but i am getting trouble in loading teh parallel routing pages they are not even rendering.

Below is my layout folder other pages are just dummy without any content just hello printed in tsx format.

import ProductCategory from "@/app/fragments/authPage/ProductCategory";
import Navbar from "@/app/reusable-components/Navbar";

const layout = ({
    children,
    filter
}: {
    children: React.ReactNode,
    filter: React.ReactNode;

}) => {
    return (
        <div style={{ backgroundColor: '#F1F3F6', width: '100%', height: '100%' }}>

            <Navbar cart={false} />
            <ProductCategory />

            <div>
                hello
                {children}
            </div>
            <div>
                {filter}

            </div>

        </div>
    )
}

export default layout

Try :
i am trying to load the filter parallel route page inside page.tsx or layout.tsx but its not rendering there is no error i am displayed i dont know what to do i have seen video tutorials but its the same thing i am doing but still.

i have hard referesh the browsesr but no use please help me with this…………?

Front end help for a wysiwyg editor [closed]

I need to build a wysiwyg editor that will allow you to add on the “canvas”:

  • text – Edit: move, change size, color
  • images – Edit: move, opacity, skew
  • shapes – Edit: move, color, size, skew
  • some animations – I am considering gsap

After editing the changes will be sent to the backend which will build an html which should look exactly like the one from the editor.
For now I have an editor with vanilla JavaScript that is working just fine with just text, but since what I’ve described above needs complex context menu for editing text/images/shapes and for changing animations options, I need to think whether I need a complex framework for that.
For now I manage to escape front end frameworks by using vanilla js in combination with Liveview hooks and doing most of the work on the backend, but I need your input on this.
Can get away without using a front end framework like react, but find just some js libraries for helping me to edit the objects in the canvas ?
What other considerations do you have ?
What I’ve already tried:
Vanilla by changing html styles directly from js

Confusion on webgl2 about format and sampler type mismatch

I am tring to implement a GPU accelerated computation with Javascript

I input the image by

const gl = this.renderer.getContext(); //this.renderer is a WebGLRenderer
this.distancesTransformFeedback.BSTextureLoc = gl.getUniformLocation(this.distancesTransformFeedback.program, 'BSTexture');
gl.activeTexture(gl.TEXTURE0);
let texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32UI, 4096, 4096, 0,gl.RGBA_INTEGER, gl.UNSIGNED_INT,this.paddedblendshapes);
gl.uniform1i(this.distancesTransformFeedback.BSTextureLoc, 0);

and in the shader I use

uniform highp usampler2D BSTexture;

However, it always throw the error

[.WebGL-000039AC02ED8000] GL_INVALID_OPERATION: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).

I consulted this answer

I have looked up OnpenGL ES 3.0.6
It says this is a valid conbination

Format Type Internal_Format
RGBA_INTEGER UNSIGNED_INT RGBAUI32

I could not figure out what’s wrong

Javascript function is not working with double-digit numbers

Given an array of numbers, I have to find the number with the highest frequency and return it. If there are two or more numbers with the same highest frequency then I need to return the biggest number.

Below is the code I’ve written..

const numbers = [1, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 6, 7, 5];
const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];

function frequency(array) {
    let object = {}
    let maxCount = 0;
    let result = 0;

    for (let num of array) {
        if (object.hasOwnProperty(num)) {
            object[num] = object[num] + 1;
        }
        else object[num] = 1;
    }
    console.log(object)
    let entry = Object.entries(object)
    for (const [key, val] of entry) {
        if (maxCount < val) {
            maxCount = val;
            result = key;
        }
    }

    for (const [key, val] of entry) {
        result = maxCount === val && key > result ? key : result;

    }
    return [result, maxCount];
}

const [res, count] = frequency(numArr);
console.log(`number with highest freq: ${res}nfrequency: ${count}`)

Function frequency is working with arrays containing single-digit numbers (e.g numbers). But it’s not giving correct output with arrays containing double-digit numbers (e.g numArr)

The above code should output 10 as the number with highest frequency and 3 as its frequency. But it outputs 5 and 3 respectively. Why is that? Is this related to ASCII values? Thankyou for your time.

Websocket secure connection error in browser

Can anyone tell me why the websocket connection is showing error? How to fix this?

//script.js Code snippet error
in browser: WebSocket connection to
‘wss://pdfsahakari.online:8443/sahakari/landing/ws/document-uploader/’
failed: uploadFile @ script.js:16 onclick @ landing/:36 script.js:33

How to fix the issue?

vueUse useIntersectionObserver and rootMargin, triggering well before element is within range

I’m really confused what I’m doing wrong here. I’m trying to implement an infinitescroll that will load new items when the bottom edge of the target element is within 200px of the bottom of the viewport but it triggers almost as soon as I start scrolling

    const observer = useIntersectionObserver(landmark, ([{isIntersecting}], observerElement) => {

        const rect = landmark.value.getBoundingClientRect();
        const viewportHeight = window.innerHeight || document.documentElement.clientHeight;

        if (isIntersecting && canLoadMoreItems.value){

            console.log(rect.top, rect.bottom, rect.width, rect.height, viewportHeight, isIntersecting)
            console.log('Root:', observer.root);

            loadMoreItems();
        }
    },
    {

        rootMargin: '0px 0px 200px 0px',
    });

when it first triggers the log shows:

123 6411 1871 6288 553 true
Root: undefined

Have I somehow got the wrong root set?

Problem passing a variable from my jscript file for my php file

So I’m using instascan api to scan qr codes and supposedly take the scanned content and send it to my php file, but no matter if I’m using POST or GET it never reads them in the php file at all and says it should be receiving a POST or GET in the php
This is my js code:

var app = new Vue({
  el: '#app',
  data: {
    scanner: null,
    activeCameraId: null,
    cameras: [],
    scans: []
  },
  mounted: function () {
    var self = this;
    self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5 });
    self.scanner.addListener('scan', function (content, image) {
      self.scans.unshift({ date: +(Date.now()), content: content });
      self.sendToPHP(content); // Call function to send content to PHP file
    });
    Instascan.Camera.getCameras().then(function (cameras) {
      self.cameras = cameras;
      if (cameras.length > 0) {
        self.activeCameraId = cameras[0].id;
        self.scanner.start(cameras[0]);
      } else {
        console.error('No cameras found.');
      }
    }).catch(function (e) {
      console.error(e);
    });
  },
  methods: {
    formatName: function (name) {
      return name || '(unknown)';
    },
    selectCamera: function (camera) {
      this.activeCameraId = camera.id;
      this.scanner.start(camera);
    },
    sendToPHP: function (content) {
      var self = this;
      var url = 'Table.php?content=' + encodeURIComponent(content);
    
      fetch(url, {
        method: 'GET'
      })
      .then(function(response) {
        if (response.ok) {
          console.log('Content sent to PHP successfully');
          return response.text();
        } else {
          console.error('Error sending content to PHP');
          throw new Error('Error sending content to PHP');
        }
      })
      .then(function(data) {
        // Handle response from PHP if needed
        console.log(data);
      })
      .catch(function(error) {
        console.error('Error:', error);
      });
    }
       
  }
});

in this js code I’m trying to send the content variable via GET

and this is my php code:

<?php
// Check if the request method is GET
if ($_SERVER["REQUEST_METHOD"] === "GET") {
    // Debug: Output the entire $_GET array
    var_dump($_GET);
    
    // Check if the 'content' parameter exists in the query string
    if (isset($_GET['content'])) {
        // Retrieve the scanned content from the query string
        $content = $_GET['content'];

        
        echo "Scanned content received via GET: " . $content;

        
        //  could save the scanned content to a database
    } else {
        // If 'content' parameter is missing in the query string
        echo "Error: 'content' parameter is missing in the query string.";
    }
} else {
    // If the request method is not GET
    echo "Error: This endpoint only accepts GET requests.";
}
?>

and this php code is where i should receive my data from content variable but it always echos the message “Error: This endpoint only accepts GET requests.”

I’m using xampp to open my files in localhost and I have used POST and GET methods exchangeably a lot to make this code work but always gives the same message. The goal from this code in php is I want to send the latest scanned content to my database to check if that scan exists in a table in my database, so I thought I would try this before connecting to my database and see if it just sends the data.

jsPDF mass download from client side – potential memory out of crash

I have a requirement of downloading 200,000 records from client side. Each record would be converted to a barcode(library – jsBarcCode) and wil be added in the PDF using jsPDF. It would be a batch wise download of 2000 records per PDF, then the next 2000 and so on. It works fine till 9-10 PDFs, after that it shows potential memory out of crash and the browser memory goes above 4GB.

Upon capturing memory heap snapshot from the memory tab in chrome developer tools, I got to know that addSVGAsImage function of jsPDF uses canvg internally and calling the function internally multiple times which has reference in the window scope causing memory leak. That’s why when I tried to remove the DOM elements it was not much of help.

https://github.com/canvg/canvg/issues/405

Current implementation is as follows

verticalBarcodeDownload: async function (pdfData) { 
//pdfData - An array if object with 2000 data    
                while (pdfData.length) {
                    await this.verticalBarcode(pdfData.splice(0, 2000));
                }
}

verticalBarcode: function (newjsonDataPDF) {
                return new Promise((resolve, reject) => {
                    var doc = new jsPDF('p', 'pt', 'a4', { compress: true });
                    doc.addFileToVFS("arial-normal.ttf", constants.fontVal1);
                    doc.addFileToVFS("FontsFree-Net-arial-bold-bold.ttf", constants.fontVal2);
                    var that = this;
                    this.getView().byId("html").setContent(
                        '<div id="printPageBarcode"></div>'
                    );
                    var svgElements = [];
                    var rotatedSVGElements = [];
                    for (let i = 0; i < newjsonDataPDF.length; i++) {
                        let node = document.createElementNS("http://www.w3.org/2000/svg", "svg");
                        node.setAttribute("id", "barcode" + i);
                        document.getElementById("printPageBarcode").appendChild(node);
                        var a = JsBarcode("#barcode" + i, newjsonDataPDF[i].sku, {
                            format: "CODE128C",
                            displayValue: false
                        });
                        let rotatedSVG = document.createElementNS(
                            "http://www.w3.org/2000/svg",
                            "svg"
                        );
                        rotatedSVG.setAttribute("width", "100"); 
                        rotatedSVG.setAttribute("height", "100");
                        document.body.appendChild(rotatedSVG);

                        let group = document.createElementNS("http://www.w3.org/2000/svg", "g");
                        group.setAttribute("transform", "rotate(90 50 50)");
                        group.appendChild(a._renderProperties[0].element); //As I need to display it vertically
                        rotatedSVG.appendChild(group);

                        document.getElementById("printPageBarcode").appendChild(rotatedSVG);
                        rotatedSVGElements.push(rotatedSVG); 
                        doc.addSvgAsImage(new XMLSerializer().serializeToString(rotatedSVG),
                            x,
                            y,
                            100,
                            100); //Here canvg is used internally


Zoom Video SDK – Unable to render more than 4 videos with SharedArrayBuffer enabled on Chrome

Video SDK Type and Version
Zoom Video SDK 1.10.8 for Web https://developers.zoom.us/docs/video-sdk/web/get-started/

Description
I am unable to render more than 4 videos in my Chrome (123.0.6312.106) browser.
It works fine for Firefox 124.0.2

I have enabled SAB like the below in my SvelteKit server

response.headers.set('Cross-Origin-Embedder-Policy', 'require-corp');
response.headers.set('Cross-Origin-Opener-Policy', 'same-origin');

SAB Verification:

self.crossOriginIsolated is true in the console

Still, I am unable to subscribe to more than 4 videos. I have also set enforceMultipleVideos: false.

Error?
subscribe video counts greater than maximum size (4)

How To Reproduce

Windows, Chrome 123.0.6312.106

  1. Enable SAB like this
export async function handle({ event, resolve }) {
    const cookieString = event.request.headers.get('cookie');
    const user = await getAPIClient(fetch).getUser(cookieString);
    event.locals = { user, token: getTokenFromCookie(cookieString) };
    if (!canAccessEndpoint(user, event.url.pathname)) {
        error(403, 'Unauthorized access for server endpoint');
    }

    const response = await resolve(event);

    setCMIdCookie(event, response);

    response.headers.set('Cross-Origin-Embedder-Policy', 'require-corp');
    response.headers.set('Cross-Origin-Opener-Policy', 'same-origin');

    return response;
}
  1. Create a canvas to paint all videos
<canvas id="participant-videos-canvas" width="1692" height="1285"></canvas>

<style>
    #participant-videos-canvas {
        width: 100%;
        height: auto;
    }
</style>
  1. Init zoom using this function
async init() {
        await this.client.init('en-US', 'Global', { patchJsMedia: true, enforceMultipleVideos: false });
    }
  1. Render all videos on an event
attachEventListeners() {
        this.client.on('peer-video-state-change', async () => {
            function sleep(ms) {
                return new Promise((resolve) => setTimeout(resolve, ms));
            }

            await sleep(5000); // Sleep for 5 seconds

            const participants = this.client.getAllUser();
            const layout = getVideoLayout(1692, 1285, participants.length);

            layout.forEach((cell, index) => {
                this.stream.renderVideo(
                    document.querySelector('#participant-videos-canvas'),
                    participants[index].userId,
                    cell.width,
                    cell.height,
                    cell.x,
                    cell.y,
                    cell.quality
                );
            });
        });
  1. Error on console “subscribe video counts greater than maximum size (4)”

Referencing sample app (https://github.com/zoom/videosdk-web-sample) ,
I am using the same headers method for enabling SAB. And using the same canvas to render all videos. I don’t see what am I missing here.