Not work p5.js in Elementor frontend editor (iframe)

  1. I create canvas element on page, works is fine home page Screenshot
  2. When i want edit this page in Elementor frontend editor, canvas not work, in console error Uncaught TypeError: Cannot read properties of null (reading ‘appendChild’) Screenshot page with canvas in frontend editor
    Any idea? Thanks!

Code create canvas

HTML

<div id="audio_visualizers"></div>

JS

var pieces, radius, fft, mapMouseX, mapMouseY, toggleBtn, audio, uploadBtn, uploadedAudio, uploadAnim;
var colorPalette = ["#000", "rgba(22, 59, 72, 0.5)", "#00a6e0", "#002a38"];
var uploadLoading = false;
var audioButton = true;
function preload() {
    audio = loadSound("sound/Audio_Visualizers1-1.mp3");
}


function uploaded(file) {
    uploadLoading = true;
    uploadedAudio = loadSound(file.data, uploadedAudioPlay);
}


function uploadedAudioPlay(audioFile) {

    uploadLoading = false;

    if (audio.isPlaying()) {
        audio.pause();
    }

    audio = audioFile;
    audio.loop();
}


function setup() {

    const canvasAudio = createCanvas(windowWidth, windowHeight);
    canvasAudio.parent('audio_visualizers');

    if (audioButton == true) {

        toggleBtn = createButton("play");

        toggleBtn.addClass("toggle-btn");

        toggleBtn.parent('audio_visualizers');
        
        toggleBtn.mousePressed(toggleAudio);

    } else {
        audio.loop()
    }

    fft = new p5.FFT();

}

function draw() {



    background(colorPalette[0]);

    noFill();

    fft.analyze();

    var bass = fft.getEnergy("bass");
    var treble = fft.getEnergy("treble");
    var mid = fft.getEnergy("mid");

    var mapMid = map(mid, 0, 255, -radius, radius);
    var scaleMid = map(mid, 0, 255, 1, 1.5);

    var mapTreble = map(treble, 0, 255, -radius, radius);
    var scaleTreble = map(treble, 0, 255, 1, 1.5);

    var mapbass = map(bass, 0, 255, -100, 800);
    var scalebass = map(bass, 0, 255, 0, 0.8);

    mapMouseX = map(mouseX, 0, width, 4, 10);
    mapMouseY = map(mouseY, 0, height, windowHeight / 4, windowHeight);

    pieces = mapMouseX;
    radius = mapMouseY;

    translate(windowWidth / 2, windowHeight / 2);

    strokeWeight(1);

    for (i = 0; i < pieces; i += 0.5) {

        rotate(TWO_PI / pieces);


        /*----------  BASS  ----------*/
        push();
        strokeWeight(5);
        stroke(colorPalette[1]);
        scale(scalebass);
        rotate(frameCount * -0.5);
        line(mapbass, radius / 2, radius, radius);
        line(-mapbass, -radius / 2, radius, radius);
        pop();



        /*----------  MID  ----------*/
        push();
        strokeWeight(0.5);
        stroke(colorPalette[2]);
        scale(scaleMid);
        line(mapMid, radius / 2, radius, radius);
        line(-mapMid, -radius / 2, radius, radius);
        pop();


        /*----------  TREMBLE  ----------*/
        push();
        stroke(colorPalette[3]);
        scale(scaleTreble);
        line(mapTreble, radius / 2, radius, radius);
        line(-mapTreble, -radius / 2, radius, radius);
        pop();

    }

}


function toggleAudio() {
    if (audio.isPlaying()) {
        audio.pause();
    } else {
        audio.play();
    }
}


function windowResized() {
    resizeCanvas(windowWidth, windowHeight);
}

I think in Elementor frontend editor, DOM elements are created in an external window (iframe). And library p5.js can’t find div element and create canvas

Conditional render/import Astro components

I am trying to make a site on Astro js + Strapi.I faced a problem when implementing “Dynamic Zones” in Strapi.
Since the data comes in an array with component names, it would be logical to conditionally render these parts.But I can’t understand how to conditionally render these components(blocks) in Astro js.

API response:

{
  ....

  "blocks": [
    {
      "id": 3,
      "__component": "global.hero",
      "title": "Some hero title"
    }
    {
      "id": 4
      "__component": "global.banner",
      "title": "Some banner title"
    }
  ]
}

Page.astro

---
import BlockRenderer from "./BlockRenderer.astro";

const { post } = Astro.props;
const { blocks } = post.attributes;


---

<div>

  {blocks.map((block:any)=> <BlockRenderer block={block} />)}

</div>

BlockRenderer.astro

---
import Hero from "./Hero.astro";
import Banner from "./Banner.astro";


const { block } = Astro.props;
function getBlock(block:any){
  if(block.__component === 'global.hero'){
     return <Hero block={block} />
  }
  else if(block.__component === 'global.banner'){
     return <Banner block={block} />
  }
}
---
<div>
  {getBlock(block)}
</div>


I don’t use any frameworks.Pure astro js.I didn’t find anything like that in the documentation.Any ideas how it can be solved ?

Swiper.js Not Working Properly in Chrome Browser, but Working Fine in Safari – How to Resolve?

I created a card container using swiper.js. Within which I have created more than 10 different categories of cards which can be swiped with the help of swiper.js.
I coded it in VS code and checked it on live server and this code is working perfectly on my chrome browser.

PROLEM —-

But, the problem is that if I uploaded that code on GitHub without making any changes and uploaded it through Netlify.app and when I checked it on the browser, many types of problems appeared in it.

But this problem is occurring only on browsers like Chrome, Firefox, Microsoft Edge, Bing. But it is working properly on Apple browser.

Problems like

I have added some breakpoints in swiper.js. This is the code of that breakpoints:

var swiper = new Swiper(“.mySwiper”, {
slidesPerView: 1,
spaceBetween: 10,
breakpoints: {
‘1200’: {
slidesPerView: 3,
spaceBetween: 30,
},
‘768’:{
slidesPerView: 2,
spaceBetween: 30,
},
‘620’: {
slidesPerView: 2,
spaceBetween: 10,
},
},
freeMode: true,
navigation: {
nextEl: “.swiper-btn-next”,
prevEl: “.swiper-btn-prev”,
},
keyboard: true,
});

Problem—

Now the problem is that when I check the code done on my vs code on the server then this breakpoints code is working properly and when I check the same code on the browser through Github and Netlify.app then it is not working properly.

I created a card container using swiper.js. Within which I have created more than 10 different categories of cards which can be swiped with the help of swiper.js. I coded it in vs code and checked it on live server and this code is working perfectly on my chrome browser.
But, the problem is that if I uploaded that code on GitHub without making any changes and uploaded it through netlify and when I checked it on the browser, many types of problems appeared in it. But this problem is occurring only on browsers like Chrome, Firefox, Microsoft Edge, Bing. But it is working properly on Apple browser.

Problems like

I have added some breakpoints in swiper.js. This is the code of that breakpoints

Now the problem is that when I check the code done on my vs code on the server then this breakpoints code is working properly and when I check the same code on the browser through github and netlify then it is not working properly. .

Please someone give a solution to this.

node:events:492 throw er; // Unhandled ‘error’ event

i tired to install a bot get from github but dont work i dont know where is problem please check the error and help me

https://github.com/lefdilia/Axabot

NOTE: im new to nodejs

–My pc terminal–

PS C:UsersLoorDAxabot_init> npm install
                                
up to date, audited 112 packages in 3s
8 packages are looking for funding
  run `npm fund` for details

6 vulnerabilities (3 high, 3 critical)

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

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

Run `npm audit` for details.
PS C:UsersLoorDAxabot_init> npm start

> [email protected] start
> node _install.js


[1] New Server Install ( To setup newly bought servers )
[2] Bot Only (Fresh install of Axabot [FILES ONLY])
[0] CANCEL

Please choose install type? [1, 2, 0]: 1
* Ip Address : xxx.xxx.xxx.xxx
* Username : root
* Password : ********
node:events:492
      throw er; // Unhandled 'error' event
      ^

Error: ENOENT: no such file or directory, open 'C:tmprsync_pass'
Emitted 'error' event on WriteStream instance at:
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'C:\tmp\rsync_pass'
}

Node.js v20.10.0
PS C:UsersLoorDAxabot_init> 

–My Server terminal–

qweasd@Axabot:~$ suPassword:root@Axabot:/home/qweasd#
apt-get install rsync
Reading package lists... DoneBuilding dependency tree... DoneReading state information... Donersync is already the newest version (3.2.7-1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.root@Axabot:/home/qweasd#

I did as tutorial except used Debian 12 64 bits then Debian 9 64 bits as say tutorial

svgPanZoom: how to contain svg within parent element (‘outside’-containment)

I am asking sth about this svg pan zoom library:
https://github.com/bumbu/svg-pan-zoom

How do I contain the svg within the area that is panzoomable, such that the user cannot pan the svg completely out of view, such that it’s gone?

Similar to how this works in a different panzoom library:

(❌ When you press the link, you need to scroll down for outside containment! There is two sections with the same name, the link leads to the first one, the inside containment! ❌)

https://timmywil.com/panzoom/demo/#Containment%20within%20the%20parent

I am talking about this section:

Panzoom(elem, { contain: 'outside', startScale: 1.5 })

My attempt:

I edited this starter template https://bumbu.me/svg-pan-zoom/demo/inline.html as such:

window.zoomTiger = svgPanZoom('#demo-tiger', {
  zoomEnabled: true,
  controlIconsEnabled: true,
  fit: true,
  center: true,
  contain: true, // ✅ -> changed this line here
  // viewportSelector: document.getElementById('demo-tiger').querySelector('#g4') // this option will make library to misbehave. Viewport should have no transform attribute
});

however it seems that it’s not working as I want it to. I am not quite sure what the contain option even means in the svgPanZoom library.

The @timmywil/panzoom library does this perfectly but I find the svgPanZoom library to be more powerful in general so I want to use it instead. In particular the timmywil-panzoom library struggles with zoom when the user has zoomed in a lot already, see this here:
https://github.com/timmywil/panzoom/issues/643

Backtrace the source map file where a minificated error happened

I am using componentDidCatch at the very top of my app to catch any errors. When they do happen I send a slack message with the information of the error. This information refers to the minified version of the app.
Something like this

Error: TypeError: undefined is not an object (evaluating 'cr.researcher.uuid') Message:{"componentStack":"nq4n@https://production.site.com/assets/index-b3f2d26c.js:1173:5035nL

I can not replicate the error, therefore I need to back trace the minified location of the error to the component where it happen and try to fix it. I could run a script locally that does the translation, since I have a copy of the source map.

I am using vite for compilation.

I tried to use the npm package, https://www.npmjs.com/package/source-map#consuming-a-source-map, but I can’t seem to get it to do the job.

After Login Home is redirecting multiple time with http://localhost:3000/home#code=0.UIBDN in NextJS Applications

Here is the Code which i am using Layout.tsx file is reloaded twice before login Microsoft azure login page display , after successfully login done . layout, wrapper, siginpage all are loading multiple time see below code .

layout.tsx
----------
"use client";
import { Open_Sans } from "next/font/google";
import "./globals.css";
import store from "./store/index";
import { Provider } from "react-redux";
import { PublicClientApplication } from "@azure/msal-browser";
import {
  MsalProvider,
  UnauthenticatedTemplate,
  AuthenticatedTemplate,
} from "@azure/msal-react";
import React from "react";
import SignInPage from "./components/SignInPage";
import ThemeRegistry from "./styles/ThemeRegistry";
import wrapper from "./components/wrapper";
import axios from "axios";

const inter = Open_Sans({ subsets: ["latin"] });
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [msalInstance, setMsalInstance] = React.useState<any>(null);
 
  React.useEffect(() => {
    console.log("useeffect running");
    axios.get("route").then((res) => {
      console.log(res.data);
      setMsalInstance(new PublicClientApplication(res.data));
    }, (err) => {
      console.log(err);
    })
  }, []);


  return (
    <html lang="en">
      <body className={inter.className}>
        {msalInstance ? (
          <MsalProvider instance={msalInstance}>
            <UnauthenticatedTemplate>
              <SignInPage />
            </UnauthenticatedTemplate>
            <AuthenticatedTemplate>
              <Provider store={store}>
               <ThemeProvider theme={theme}>
                  <wrapper>{children}</wrapper>
               </ThemeProvider >
              </Provider>
            </AuthenticatedTemplate>
          </MsalProvider>
        ) : null}
      </body>
    </html>
  );
};


wrapper.tsx
---------
import React, { useEffect, useState } from "react";
import { useMsal } from "@azure/msal-react";


export default function wrapper({ children }: { children: React.ReactNode }) {
  const { accounts } = useMsal();
  const [roles, setRoles] = useState<string[]>([]);
  useEffect(() => {
    const { roles } = accounts[0]?.idTokenClaims ?? {};
    if (!roles) {
      setRoles(["Invalid"]);
    } else {
      setRoles(roles);
    }
  }, []);

  return <section>{children}</section>;
}



signinPAge.tsx
--------------
import { useMsal } from "@azure/msal-react";
import { loginRequest } from "./authConfig";
import React, { useEffect } from "react";
import sessionStore from "../utilities/sessionStore";

const SignInPage: React.FC = () => {
  const { instance } = useMsal();
  console.log("Step 1 sigin")
  useEffect(() => {
    console.log("use signin ")
    if (sessionStore.getItem("msal.account.keys") == null) {
      instance?.loginRedirect(loginRequest);
    }
  }, [instance]);

  return <></>;
};
export default SignInPage;


route.tsx
---------

import { NextRequest } from 'next/server';
import { Configuration} from '@azure/msal-browser';

export async function GET(req: NextRequest) {
    if (req.method === 'GET') {
        const msalConfig: Configuration = {
            auth: {
              clientId: process.env.CLIENT_ID!,
              authority: 'https://login.microsoftonline.com/' + process.env.TENANT_ID
            },
            cache: {
              cacheLocation: "sessionStorage"
            }
          };

        return new Response(JSON.stringify(msalConfig), {
            status: 200,
        })
    } else {
        return new Response(
            null, { status: 405 }
        ); 
    }
};

home.tsx
------------

"use client";
import type { Metadata } from 'next';

export default function Home({
    children,
  }: {
    children: React.ReactNode
  }) {
    return (
      <section>{children}</section>
    )
};

using dependency “@azure/msal-browser”: “^2.38.0”, “@azure/msal-react”: “^1.5.9”,
http://localhost:3000/home#code=0.UIBDN this reload again and again after 10 – 12 time reload home page displayed . I want once login is done it should display home page and in url it should not be #code .

Generate multiple webpack output files from a single script

Need help with the webpack.
Project on vue, using ts and scss.
Need to generate multiple js output files that use the same source.

Now module.export looks like this:

module.exports {
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({ extractComments: false }),
        ],
    },
    entry: [
        './src/index.js'
    ],
    resolve: {
        modules: [path.resolve(__dirname, './src'), 'node_modules'],
        extensions: ['.js', '.ts', '.vue', '.json'],
    },
    output: {
        path: __dirname + '/public/',
        filename: 'project.js',
    },
    module: {
        rules: [
            {
                test: /.vue$/,
                use: 'vue-loader'
            },
            {
                test:    /.(ts)?$/,
                loader:  'ts-loader',
                options: {
                    allowTsInNodeModules: true,
                    transpileOnly: true,
                },
            },
            {
                test:   /.js$/,
                loader: 'babel-loader',
            },
            {
                test: /.(png|svg|jpg|jpeg)$/i,
                type: 'asset/inline',
            },
            {
                test: /.(gif)$/i,
                type: 'asset/resource',
            },
            {
                test:  /.scss$/,
                oneOf: [
                    {
                        resourceQuery: /module/,
                        use:           [
                            MiniCssExtractPlugin.loader,
                            {
                                loader:  'css-loader',
                                options: {
                                    modules: {
                                        localIdentName: '[local]_[hash:base64:3]',
                                    },
                                },
                            },
                            'sass-loader',
                        ],
                    },
                    {
                        use: [
                            MiniCssExtractPlugin.loader,
                            'css-loader',
                            'sass-loader',
                        ],
                    },
                ],
            },
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'project.css',
        }),
        new VueLoaderPlugin(),
        new somePlugin(
            params
          },
        ),
}

The output is a project js file and nodmodule scripts.
I need two output files, both created from index.js, but using different parameters for some plugin:

new somePlugin(
    params
    },
),

This plugin changes the final output file, and it is necessary to have two output files with different parameters for this plugin.

Both final scripts use the same style files and module files are not changed either, i.e. there is no need to rebuild them.

I tried to make module.exports as an array and do push, and duplicate the code, but in this case duplicate scripts of nodmodules are generated, because the output has a different filename. I would like to get rid of duplication, I couldn’t come to another solution yet.

Use JSON file as Pagination in NextJS

I am building a science blog in which the urls of the posts are stored in a static JSON file.

[
  {
    "Subject": "Mathematics",
    "chapters": "mathematics",
    "contentList": [
      {
        "content": "Algebra",
        "url": "algebra-content-url"
      },
      {
        "content": "Trigonometry",
        "url": "trigonometry-content-url"
      },
      {
        "content": "Geometry",
        "url": "geometry-content-url"
      }
    ]
  },
  {
    "Subject": "Physics",
    "chapters": "physics",
    "contentList": [
      {
        "content": "Newton's 1st law",
        "url": "newtons-fisrt-law-url"
      },
      {
        "content": "Newton's 2nd law",
        "url": "newtons-second-law-url"
      },
      {
        "content": "Newton's 3rd law ",
        "url": "newtons-third-law-url"
      }
    ]
  }
]

I want to add pagination on single post page. This answer works perfectly for ReactJS but the only problem is useEffect hook uses ‘client’ which is conflicting with generateStaticParams() of NextJS. I have modified the code –

// 'use client'
// 'use server'
import React, { useMemo } from 'react'
import fs from "fs"
import PaginationControls from "@/app/components/PaginationControls"
import Link from "next/link"
import Markdown from "react-markdown"
import rehypeKatex from "rehype-katex"
import remarkMath from "remark-math"
import rehypeRaw from "rehype-raw"
import matter from "gray-matter"
import 'katex/dist/katex.min.css'

import ScienceTopics from '@/app/(subjects)/mathematicalphysics/MathematicalPhysicsMenuItems.json'
import path from "path"

import { Metadata, ResolvingMetadata } from "next"
import { notFound, useSearchParams } from "next/navigation"


// export const runtime = 'edge'

export const dynamicParams = false;

const allPosts = ScienceTopics.flatMap(({ Subject, chapters, contentList }) =>
contentList.map((topics) => ({

    subjectName: Subject,
    subjectId: chapters,
    ...topics,

  })),
);


const folder = path.join(process.cwd(), 'src/ScienceTopics');// put it outside of app folder

const getPostContent = (chapterID:string, postID: string) => {
  
  const file = `${folder}/${chapterID}/${postID}.md`;

  if (!file) {
    notFound();
  }
  const content = fs.readFileSync(file, "utf8");
  const matterResult = matter(content);
  // return matterResult;
  return {
    title: matterResult.data.title,
    desc: matterResult.data.metaDesc,
    content: matterResult.content,
    img: matterResult.data.ImageUrl
  }
};




export async function generateMetadata({params}:{params: {chapterID:string, postID:string}},
   parent: ResolvingMetadata): Promise<Metadata>{
  const post = getPostContent(`${params.chapterID}`,`${params.postID}`) //call post using chapterID and postID

  const prevImg = (await parent).openGraph?.images || [] //get previous images
  const title = post.title //gets the title from md file
  const description = post.desc // gets the description from md file
  const imgUrl = "/" + post.img // gets the image from the header of the md file
  return {
    title: title,
    description: description,
    openGraph:{
      images: [imgUrl, ...prevImg]
    }
  }
}



// generates static pages 
export async function generateStaticParams() {
  return allPosts.map((post) => ({
    chapterID: post.sectionId,
    postID: post.url

  }))
}


interface Post {
  sectionId: string;
  title: string;
  url: string;
}

interface Pagination {
  prev?: string;
  post?: Post;
  next?: string;

}
const ScienceBlogPage = ({params}:{params:any) => {
  
  
  //gets ids from url
  // const chapterID = params.chapterID
  const postID = params.postID;
  // calculate prev/next page URLs
  const { prev, next, post } = useMemo<Pagination>(() => {
    const postIndex = allPosts.findIndex(({ url }) => url === postID);

    return {
      prev: allPosts[postIndex - 1]?.url,
      post: allPosts[postIndex],
      next: allPosts[postIndex + 1]?.url
    };
  }, [postID]);



  if(!post) {
    return null;
  }
  const curr_post = getPostContent(`${post.sectionId}`,`${post.url}`)
  
  return (

    <>

      <h1>{curr_post.title}</h1>
      <hr className="my-6 border border-dashed bg-sky-600 h-0.5" />
      <article lang="bn" className="prose lg:prose-xl">
        <Markdown remarkPlugins={[remarkMath]} rehypePlugins={[rehypeKatex, rehypeRaw]}>
          {curr_post.content}</Markdown>
      
      </article>
     <Link className="float-left text-teal-600" aria-disabled={!prev} href={`${prev}`}>prev</Link>
     <Link className="float-right text-teal-600" aria-disabled={!next} href={`${next}`}>next</Link>
    </>

  )
}

export default ScienceBlogPage



Though the ${post.url} updates properly, ${post.sectionId} does not update also the link is tries to go to ‘url/undefined’ when it hits the end.

How can I update the value of ${post.sectionId} when it hits end of the ‘contentList array’ on JSON? And make the Link disabled when there’s no more item in Subject in JSON using NextJS?

amcharts change Mapchart lines’ strokewidth

I want to set “strokeWidth=2” of lines based on this condition:

(id === “london” && did === “vilnius”) else set “strokeWidth=8”.

I have a chart here: [https://codepen.io/Anisha-Ramanuj/pen/mdoEgQV].
Kindly check code there.

function selectOrigin(id) {
  debugger
  currentId = id;
  var dataItem = originSeries.getDataItemById(id);
  var dataContext = dataItem.dataContext;
  chart.zoomToGeoPoint(dataContext.zoomPoint, dataContext.zoomLevel, true);
  var destinations = dataContext.destinations;
  var lineSeriesData = [];
  var originLongitude = dataItem.get("longitude");
  var originLatitude = dataItem.get("latitude");

  am5.array.each(destinations, function (did) {
    var destinationDataItem = destinationSeries.getDataItemById(did);
    if (!destinationDataItem) {
      destinationDataItem = originSeries.getDataItemById(did);
    }
    var sw = (id === "london" && did === "vilnius") ? 2 : 8;
    lineSeriesData.push({
  
      geometry: {
        type: "LineString",
        coordinates: [
          [originLongitude, originLatitude],
          [
            destinationDataItem.get("longitude"),
            destinationDataItem.get("latitude")
          ]
        ]
      },
      strokeWidth: sw,
      stroke: root.interfaceColors.get("alternativeBackground"),
      strokeOpacity: 0.09
    });
 });
 
 lineSeries.data.setAll(lineSeriesData);
}

Why I am not getting Request Body key value in multer?

I am trying to actually upload a file to my server using Node.js in Public Folder to serve the Static Content in the Future.

For the to be done I am using multer package in Node.js and it has been sucessfully added to public folder but I want to have a File Structure maintain inside public folder therefore with imagedata appended in binary i am adding another key as well to the request as “id” where i am sending a id generated in the Frontend to the backend.

But I am not getting that “id” to my request object in multer middleware and once the upload complete in middleware and the same “id” i am getting in controller inside req.body.

Can you help me where I am getting wrong in it.

Backend-Code:

From Here the api call has been executed:

const express = require("express");
const upload = require("../middlewares/FileUploads.js");
const {
    UploadFileController
} = require("../controllers/UploadController");

//router object
const router = express.Router();

router.post("/upload",upload.single("files[0]"),UploadFileController);

FileUpload.js(Multer)

const multer  = require('multer')
const fs = require("fs");
const storage=multer.diskStorage({
    destination: function(req,file,cb){
      console.log("Upload Destination",req.body);
      const { id } = req.body
      const path = `./public/${id}`
      fs.mkdirSync(path, { recursive: true })
      return cb(null, path)
    },
    filename: function(req,file,cb){
      const fileName=`${Date.now()}-${file.originalname}`
      req.myData={
        fileName
      }
      return cb(null,fileName);
    }
  
  })
module.exports= upload = multer({ storage })

UploadController.js

exports.UploadFileController=(req,res)=>{
    // console.log(req.params);
    console.log("Upload Controller",req.body);
    const {myData}=req;

    res.status(200).json({
    "success": true,
    "time": "2024-01-02 04:56:17",
    "data": {
        "baseurl": "http://localhost:3001/",
        "msg": [
            "File image.png was uploaded"
        ],
        "files": [
            myData.fileName
        ],
        "isImages": [
            true
        ],
        "code": 220
    },
    "elapsedTime": 0
});

}

I have added to Console.log inside middleware(multer) and controller. This is the attach ScreenShot:
enter image description here

Request From Frontend
enter image description here

CSS: If i set the height in the css, the panel has problems resizing when i drag with the mouse when i set the height, so it freezes

I have 3 panels (left, center, right) that resize when I drag them with the mouse. In the right panel I have an iframe whose css is width: 100%. To make it clearer I colored it red.

I would like to extend the height of the iframe across the entire right panel, so i also set height:100% in css #preview. Height extension in the panel happens correctly.

enter image description here

The problem is that when I set height:100%, then the right panel is no longer resizable. It will have problems when I drag it with the mouse to resize it and it’s like it’s stuck: it will stretch correctly (moving it from right to left), but it will no longer be able to shrink (moving it from left to right). IMPORTANT: If i don’t use height:100%, then the right panel resizes correctly

P.S: I don’t want to use a specific height: ? px, but height: 100% in percentage.

How can I adjust the resizability of the right panel (using height:100%) and prevent it from crashing?

html

​<div class="wrapper" style="--min-width: 200px;--min-height: 100px;">
  <div class="pane left">
    This is the left pane.
  </div>
  <div class="pane center_container">
    <div class="gutter gutter-v"></div>
    <div class="pane center1">
      This is the center pane1
    </div>
    <div class="pane">
      <div class="gutter gutter-h"></div>
      This is the center pane2.
    </div>
  </div>
  <div class="pane">
    <div class="gutter gutter-v"></div>
      <iframe id="preview"></iframe>
  </div>
</div>

css

*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 0;
}

.wrapper {
  height: 100vh;
  width: 100vw;
  background: #333;
  border: 6px solid #666;
  display: flex;
}

.pane {
  position: relative;
  color: #fff;
  /* 
  --min-width in .wrapper inline style 
  <div class="wrapper" style="--min-width: 200px;--min-height: 100px;"> 
  */
  min-width: var(--min-width);
}

.pane:last-child {
  flex-grow: 1;
}

.pane:has(.pane) {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.pane>.pane {
  /* 
  --min-height in .wrapper inline style 
  <div class="wrapper" style="--min-width: 200px;--min-height: 100px;">
  */
  min-height: var(--min-height);
}

.gutter {
  --l: 100%;
  --s: 10px;
  background: #666;
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
}

.gutter-v {
  width: var(--s);
  height: var(--l);
  cursor: col-resize;
}

.gutter-h {
  height: var(--s);
  width: var(--l);
  cursor: row-resize;
}


.left {
  width: 600px;
}

.center_container {
  width: 650px;
}

.center1 {
height: 700px;
}

#preview {
  display: block;
  width: 100%;
  height: 100%;
  background: #991717;
  border: 0;
}

javascript

const gutters = document.querySelectorAll(".gutter");
const panes = document.querySelectorAll(".pane");
const minWidth = document.querySelector(".wrapper").style.getPropertyValue("--min-width");
const minHeight = document.querySelector(".wrapper").style.getPropertyValue("--min-height");

function resizer(e) {
  window.addEventListener("mousemove", mousemove);
  window.addEventListener("mouseup", mouseup);

  //   check gutter if vertical or horizontal
  const is_vertical = e.currentTarget.classList.contains("gutter-v");
  //   get previous position (x or y depending on is_vertical)
  const prev = is_vertical ? e.x : e.y;
  //   get current pane, the parent pane of the gutter you are moving
  const currentPane = e.currentTarget.parentNode;
  const currentPanel = currentPane.getBoundingClientRect();
  //   get previous pane, when move gutter-v:
  //   if current pane is center, prev pane will be left pane
  //   if current pane is right, prev pane will be center pane
  //   left pane will never be current pane cause it don't have gutter
  const prevPane = currentPane.previousElementSibling;
  const prevPanel = prevPane.getBoundingClientRect();

  function mousemove(e) {
    // minWidth and minHeight are string ('200px' and '100px' in this case), change them to integer
    const min = parseInt(is_vertical ? minWidth : minHeight);
    // calculate distance between prev and current position
    const distance = prev - (is_vertical ? e.x : e.y);
    // calculate new width/height of current pane and prev pane
    const newCurrentSize = (is_vertical ? currentPanel.width : currentPanel.height) + distance;
    const newPrevSize = (is_vertical ? prevPanel.width : prevPanel.height) - distance;
    // if new width/height is less than min, return and don't change pane style
    if (newCurrentSize < min || newPrevSize < min) return;
    // change pane width/height depending on is_vertical
    if (is_vertical) {
      currentPane.style.width = newCurrentSize + "px";
      prevPane.style.width = newPrevSize + "px";
    } else {
      currentPane.style.height = newCurrentSize + "px";
      prevPane.style.height = newPrevSize + "px";
    }
  }

  function mouseup() {
    window.removeEventListener("mousemove", mousemove);
    window.removeEventListener("mouseup", mouseup);
  }
}
gutters.forEach((gutter) => gutter.addEventListener("mousedown", resizer));

If i set the height in the css, the panel has problems resizing when i drag with the mouse when i set the height, so it freezes

I have 3 panels (left, center, right) that resize when I drag them with the mouse. In the right panel I have an iframe whose css is width: 100%. To make it clearer I colored it red.

I would like to extend the height of the iframe across the entire right panel, so i also set height:100% in css #preview. Height extension in the panel happens correctly.

The problem is that when I set height:100%, then the right panel is no longer resizable. It will have problems when I drag it with the mouse to resize it and it’s like it’s stuck: it will stretch correctly, but it won’t be able to shrink anymore.

P.S: I don’t want to use a specific height: ? px, but height: 100% in percentage.

How can I adjust the resizability of the right panel (using height:100%) and prevent it from crashing?

html

​<div class="wrapper" style="--min-width: 200px;--min-height: 100px;">
  <div class="pane left">
    This is the left pane.
  </div>
  <div class="pane center_container">
    <div class="gutter gutter-v"></div>
    <div class="pane center1">
      This is the center pane1
    </div>
    <div class="pane">
      <div class="gutter gutter-h"></div>
      This is the center pane2.
    </div>
  </div>
  <div class="pane">
    <div class="gutter gutter-v"></div>
      <iframe id="preview"></iframe>
  </div>
</div>

css

*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 0;
}

.wrapper {
  height: 100vh;
  width: 100vw;
  background: #333;
  border: 6px solid #666;
  display: flex;
}

.pane {
  position: relative;
  color: #fff;
  /* 
  --min-width in .wrapper inline style 
  <div class="wrapper" style="--min-width: 200px;--min-height: 100px;"> 
  */
  min-width: var(--min-width);
}

.pane:last-child {
  flex-grow: 1;
}

.pane:has(.pane) {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.pane>.pane {
  /* 
  --min-height in .wrapper inline style 
  <div class="wrapper" style="--min-width: 200px;--min-height: 100px;">
  */
  min-height: var(--min-height);
}

.gutter {
  --l: 100%;
  --s: 10px;
  background: #666;
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
}

.gutter-v {
  width: var(--s);
  height: var(--l);
  cursor: col-resize;
}

.gutter-h {
  height: var(--s);
  width: var(--l);
  cursor: row-resize;
}


.left {
  width: 600px;
}

.center_container {
  width: 650px;
}

.center1 {
height: 700px;
}

#preview {
  display: block;
  width: 100%;
  height: 100%;
  background: #991717;
  border: 0;
}

javascript

const gutters = document.querySelectorAll(".gutter");
const panes = document.querySelectorAll(".pane");
const minWidth = document.querySelector(".wrapper").style.getPropertyValue("--min-width");
const minHeight = document.querySelector(".wrapper").style.getPropertyValue("--min-height");

function resizer(e) {
  window.addEventListener("mousemove", mousemove);
  window.addEventListener("mouseup", mouseup);

  //   check gutter if vertical or horizontal
  const is_vertical = e.currentTarget.classList.contains("gutter-v");
  //   get previous position (x or y depending on is_vertical)
  const prev = is_vertical ? e.x : e.y;
  //   get current pane, the parent pane of the gutter you are moving
  const currentPane = e.currentTarget.parentNode;
  const currentPanel = currentPane.getBoundingClientRect();
  //   get previous pane, when move gutter-v:
  //   if current pane is center, prev pane will be left pane
  //   if current pane is right, prev pane will be center pane
  //   left pane will never be current pane cause it don't have gutter
  const prevPane = currentPane.previousElementSibling;
  const prevPanel = prevPane.getBoundingClientRect();

  function mousemove(e) {
    // minWidth and minHeight are string ('200px' and '100px' in this case), change them to integer
    const min = parseInt(is_vertical ? minWidth : minHeight);
    // calculate distance between prev and current position
    const distance = prev - (is_vertical ? e.x : e.y);
    // calculate new width/height of current pane and prev pane
    const newCurrentSize = (is_vertical ? currentPanel.width : currentPanel.height) + distance;
    const newPrevSize = (is_vertical ? prevPanel.width : prevPanel.height) - distance;
    // if new width/height is less than min, return and don't change pane style
    if (newCurrentSize < min || newPrevSize < min) return;
    // change pane width/height depending on is_vertical
    if (is_vertical) {
      currentPane.style.width = newCurrentSize + "px";
      prevPane.style.width = newPrevSize + "px";
    } else {
      currentPane.style.height = newCurrentSize + "px";
      prevPane.style.height = newPrevSize + "px";
    }
  }

  function mouseup() {
    window.removeEventListener("mousemove", mousemove);
    window.removeEventListener("mouseup", mouseup);
  }
}
gutters.forEach((gutter) => gutter.addEventListener("mousedown", resizer));