Plotly Dash – Triggering a callback on user modification of a prop

I need to trigger a callback if the value of a dcc.Dropdown component in dash is modified by the user. Essentially, I am looking to avoid the cases where the value component of a prop is modified by a different callback (anything other than the user).

It seems that dash does not have any method for distinguishing whether a user/something else modified a prop. As such, I have been attempting to use event listeners to detect when the dcc.Dropdown is changed due to a click or keydown event.

document.addEventListener('DOMContentLoaded', function() {
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length) {
                const dropdown = document.getElementById('my-dropdown');
                if (dropdown) {
                    dropdown.addEventListener('click', function(event) {
                        if (event.target && event.target.matches("div.VirtualizedSelectOption")) {
                            console.log(event.target.innerText);
                        }
                    });
                    observer.disconnect();                 }
            }
        });
    });

    observer.observe(document.body, { childList: true, subtree: true });
});

This does detect selections of a value from the dcc.Dropdown, but does not detect if the user removes the value.

The reason I am looking for a solution to this is I need to modify the values in this list dependent on future selected values. For example if there ends up being a duplicate entry added I need to remove the value in the dcc.Dropdown as it is no longer a valid entry. This cannot be done statically (eg. disabling options which lead to duplicates) as the options change frequently.

React SVG coordinate system mismatch – cursor position doesn’t match where elements are rendered

I’m building a floor plan application in React where users can place desk icons by clicking on an SVG floor plan. However, I’m encountering a coordinate system mismatch where desks aren’t appearing where users click.

The Issue

  • When a user clicks on the floor plan, the desk appears offset from
    the cursor position. The offset isn’t consistent – it seems to
    increase the further the click is from the center of the SVG.
  • For example, when I click at position x:22.5%, y:17.7%, the desk
    appears at approximately x:30.6%, y:17.7% – showing a horizontal
    offset of about 8.1% that grows larger the further I click from the
    center.

Technical Details

  • Floor plan is an SVG with viewBox=”0 0 2200 1700″ and a group
    transformation transform=”translate(0, 1700) scale(0.1, -0.1)”
  • I’m calculating click position as percentage of container
    width/height:
const x = ((e.clientX - rect.left) / rect.width) * 100;
const y = ((e.clientY - rect.top) / rect.height) * 100;
  • When I place a desk at these coordinates, it appears offset and to
    the right of the click position
  • I’ve tried applying transform: translate(-50%, -50%) to center
    elements, but the issue persists
function FloorPlan() {
    // State to store your data
    const [desks, setDesks] = useState([]);
    
    // Other state and logic...
    
    return (
        <div className="floor-plan">
            {/* Admin controls */}
            {/* ... */}
            
            <div className="floor-plan-wrapper" ref={wrapperRef} onClick={handleWrapperClick}>
                <FloorPlanSVG>
                    <foreignObject x="0" y="0" width="2200" height="1700">
                        <div xmlns="http://www.w3.org/1999/xhtml">
                            {desks.map(desk => (
                                <Desk
                                    key={desk.id}
                                    desk={desk}
                                    onUnassignEmployee={onUnassignEmployee}
                                />
                            ))}
                        </div>
                    </foreignObject>
                </FloorPlanSVG>
            </div>
        </div>
    );
}
// Desk.js
function Desk({ desk, onUnassignEmployee }) {
    // Component logic...
    
    const deskStyle = {
        position: 'absolute',
        left: `${desk.x}%`,
        top: `${desk.y}%`,
        width: '35px',
        height: '30px',
        backgroundColor: /* ... */,
        transform: 'translate(-50%, -50%)', // Center the desk
        // Other styles...
    };
    
    return (
        <div ref={setNodeRef} style={deskStyle} onContextMenu={handleContextMenu}>
            {/* Desk contents */}
        </div>
    );
}
function FloorPlanSVG({children}) {
    return (
        <svg
            xmlns="http://www.w3.org/2000/svg"
            width="100%"
            height="100%"
            viewBox="0 0 2200 1700"
            preserveAspectRatio="xMidYMid"
        >
            <g
                transform="translate(0, 1700) scale(0.1, -0.1)"
                fill="#000000"
                stroke="none"
            >
                {/* Floor plan paths... */}
            </g>
            {children}
        </svg>
    );
}

How can I properly translate between browser click coordinates and SVG coordinates with transformations?

Is there a way to apply an inverse transformation to correctly position elements?
Should I consider a different approach altogether for implementing this floor plan?

I’ve tried proportional scaling adjustments and several approaches but haven’t found a consistent solution. I’d appreciate any insights on how to solve this coordinate system mismatch.

Ideally, I need a solution where when a user clicks on the floor plan, the desk appears exactly at that location, regardless of where on the SVG they click. The ghost desk preview should also align with where the actual desk will be placed.

Unable to install npm nodemon

I am trying to install npm package nodemon by running this command:
npm i nodemon -g

And I am receiving this error message below:

npm error code MODULE_NOT_FOUND
npm error path ?C:Program Filesnodejsnode_modulesnpmnode_modulestuf-jsnode_modulesmake-fetch-happenpackage.json
npm error Cannot find module ‘C:Program Filesnodejsnode_modulesnpmnode_modulestuf-jsnode_modulesmake-fetch-happenlibindex.js’. Please verify that the package.json has a valid “main” entry
npm error A complete log of this run can be found in: C:Usersmbulelo.tshabaneAppDataLocalnpm-cache_logs2025-03-06T14_33_24_047Z-debug-0.log

npm error

I have tried the following command as well below:

npm install nodemon –save-dev

Still same error message received.

How can I run very old Chrome apps?

I have a Chrome App crx file published in 2013 that I would like to run. Modern Chrome refuses and fails to run it for a variety of reasons, including deprecation of Chrome Apps in 2020, extension security changes in 2022, javascript API changes over many different versions, etc. Older versions of Chrome tend to not work on modern OSes for various library and interface related reasons.

Looking for a library to generate and download a React component as a high-quality pdf

Can anyone suggest a good library for generating and downloading a React component as a PDF?

I have tried jspdf and html2pdf, but they only generate low-quality PDFs with blurry, non-selectable text. Additionally, if I insert a link, it is not clickable in the generated PDF.

I need a library that can produce high-quality, selectable text and supports clickable links. Any recommendations?
I want to handle this in frontend only

How to wait for an external script to be ready in Vue 3?

I am trying to integrate Google Pay as a component in an application. I need to load the Google Pay Javascript file before I perform any actions. This is what I am doing:

onMounted(()=>{
  const scripts = [
    "https://pay.google.com/gp/p/js/pay.js",
  ];

  // Append the pay.js script to the <head> tag
  scripts.forEach(script => {
    let tag = document.createElement("script");
    tag.setAttribute("src", script);
    tag.setAttribute("async", true);
    
    document.head.appendChild(tag);
  });

  //Check if Google Pay exists
  function isGooglePayReady(){
    if('google' in window && Object.keys(window.google).length) {
      loadGooglePay()
    }
}

// Have to currently use a setTimeout to wait for script to load
setTimeout(()=> isGooglePayReady(), 500);

I set the timeout to 500 arbitrarily because I don’t know how long it at takes for the https://pay.google.com/gp/p/js/pay.js script to load be available.

Is there a better way to wait for the script to load and be ready than using a setTimeout() function?

How to Use JSON Placeholder in a React JS Project [closed]

enter image description here

When developing a React application, you often need APIs for testing. JSON Placeholder is a great free resource that provides mock data for prototyping and development. In this post, I’ll demonstrate how to use JSONPlaceholder in your React project. Additionally, we’ll learn how to fetch and use a custom JSON file hosted online.

What is JSON Placeholder?
JSON Placeholder is a free online REST API that provides various endpoints to work with mock data like posts, comments, users, and more. It’s an excellent tool for learning and testing API calls without needing to set up your own server.
Website: JSON Placeholder.

Setting Up the React Project:
To follow along, ensure you have Node.js installed and a React app set up. If you don’t already have one, create it using:

npx create-react-app json-placeholder-demo
cd json-placeholder-demo

Install axios for making API requests (optional):

npm install axios

Fetching Data from JSON Placeholder
Let’s create a React component to fetch and display posts from JSON Placeholder.

JsonPlaceholder.jsx

import React, { useState, useEffect } from "react";
import axios from "axios";
import "./main.css"; // Import the CSS file

const JsonPlaceholder = () => {
  const [users, setUsers] = useState([]);

  // Fetch data from JSON Placeholder
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get(
          "https://jsonplaceholder.typicode.com/users"
        );
        setUsers(response.data); // Fetch all users
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchUsers();
  }, []);

  return (
    <div className="user-container">
      <h1 className="header">User Profiles</h1>
      <div className="card-container">
        {users.map((user) => (
          <div key={user.id} className="user-card">
            <h2 className="user-name">{user.name}</h2>
            <p className="user-detail">
              <strong>Username:</strong> {user.username}
            </p>
            <p className="user-detail">
              <strong>Email:</strong> {user.email}
            </p>
            <p className="user-detail">
              <strong>Phone:</strong> {user.phone}
            </p>
            <p className="user-detail">
              <strong>Address:</strong> {user.address.street},{" "}
              {user.address.city}
            </p>
            <p className="user-detail">
              <strong>Company:</strong> {user.company.name}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default JsonPlaceholder;

main.css

/* General Styles */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f8f9fa;
}

/* Header Styles */
.header {
  text-align: center;
  margin: 20px 0;
  color: #343a40;
  font-size: 2rem;
  font-weight: bold;
}

/* Container for Cards */
.user-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  width: 100%;
  max-width: 1200px;
}

/* Card Styles */
.user-card {
  background-color: #ffffff;
  border: 1px solid #dee2e6;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.user-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

/* User Information */
.user-name {
  font-size: 1.5rem;
  color: #007bff;
  margin-bottom: 10px;
}

.user-detail {
  font-size: 1rem;
  color: #495057;
  margin: 5px 0;
}

.user-detail strong {
  color: #343a40;
}

enter image description here

Using Custom JSON Data

This JSON file contains a list of food items. Here’s how to fetch and display it.

FoodApi.jsx

import React, { useState, useEffect } from "react";
import axios from "axios";
import "./FoodMain.css"; 

const FoodApi = () => {
  const [foods, setFoods] = useState([]);
  const [filteredFoods, setFilteredFoods] = useState([]);
  const [filter, setFilter] = useState({ category: "All", country: "All" });

  // Fetch data from local JSON file or URL
  useEffect(() => {
    const fetchFoods = async () => {
      try {
        const response = await axios.get(
          "https://sudhanshu1919.github.io/FoodJson/Foodapi.json"
        );
        setFoods(response.data);
        setFilteredFoods(response.data);
      } catch (error) {
        console.error("Error fetching food data:", error);
      }
    };

    fetchFoods();
  }, []);

  return (
    <div className="food-container">
      <h1 className="food-header">Food Items</h1>

      <div className="food-card-container">
        {filteredFoods.map((food) => (
          <div key={food.id} className="food-card">
            <div className="inner-card">
              <div>
                <img
                  src={food.image}
                  alt={food.foodname}
                  className="food-image"
                />
              </div>
              <div>
                <h3 className="food-name">{food.foodname}</h3>
                <p className="food-detail">
                  <strong>Category:</strong> {food.category}
                </p>
                <p className="food-detail">
                  <strong>Price:</strong> {food.prise}
                </p>
                <p className="food-detail">
                  <strong>Country:</strong> {food.country}
                </p>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default FoodApi;

FoodMain.css

/* General Styles */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f3f4f6;
}

/* Header */
.food-header {
  text-align: center;
  margin: 20px 0;
  font-size: 2.5rem;
  color: #34495e;
  font-weight: bold;
}

/* Food Cards Container */
.food-card-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* Food Card */
.food-card {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.food-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

/* Food Details */
.food-name {
  font-size: 1.5rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.food-detail {
  font-size: 1rem;
  color: #131414;
  margin: 5px 0;
}

enter image description here

Why does flipping the sign in my angle constraint condition unexpectedly fix my vector rotation logic?

I am implementing a snake-like movement system where each segment follows the previous one while maintaining:

  1. A fixed distance constraint.
  2. An angle constraint, where if the angle between two segments drops below 90°, I rotate the segment to 120° in the same direction.
follow(targetX, targetY, prevX, prevY) {
  let dx = targetX - this.x;
  let dy = targetY - this.y;
  let distance = Math.sqrt(dx * dx + dy * dy);

  // Maintain distance constraint, inf -> influence
  if (distance > this.inf) {
    let scale = this.inf / distance;
    this.x = targetX - dx * scale;
    this.y = targetY - dy * scale;
  }

  if (prevX !== undefined && prevY !== undefined) {
    const ax = targetX - prevX;
    const ay = targetY - prevY;
    const bx = this.x - targetX;
    const by = this.y - targetY;

    const dot = ax * bx + ay * by;
    const mod_a = Math.sqrt(ax * ax + ay * ay);
    const mod_b = Math.sqrt(bx * bx + by * by);
    const angle = Math.acos(dot / (mod_a * mod_b)); // Compute angle

    // Theoretically correct condition, but it doesn't work
    // if (angle < Math.PI / 2) { 

    // Flipping the sign unexpectedly fixes it
    if (angle > Math.PI / 2) { 
      const cross = ax * by - ay * bx; // Cross product to determine rotation direction
      const angleFix = angle - (2 * Math.PI) / 3; // Rotate to 120°

      const cosA = Math.cos(angleFix);
      const sinA = Math.sin(angleFix);

      let newBx, newBy;

      if (cross > 0) {
        newBx = bx * cosA - by * sinA;
        newBy = bx * sinA + by * cosA;
      } else {
        newBx = bx * cosA + by * sinA;
        newBy = -bx * sinA + by * cosA;
      }

      let length = Math.sqrt(newBx * newBx + newBy * newBy);
      let scale = this.inf / length;
      this.x = targetX + newBx * scale;
      this.y = targetY + newBy * scale;
    }
  }
}


const numCircles = 5; // Snake length
const circles = [];
for (let i = 0; i < numCircles; i++) {
  circles.push(new Circle(250, 250, 10 - i * 0.2, 20, ctx));
}

canvas.addEventListener("mousemove", (e) => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  circles[0].x = e.offsetX;
  circles[0].y = e.offsetY;

  for (let i = 1; i < circles.length; i++) {
    circles[i].follow(
      circles[i - 1].x,
      circles[i - 1].y,
      circles[i - 2]?.x,
      circles[i - 2]?.y,
      i
    );
  }

  circles.forEach((circle) => circle.draw());
});

I originally expected the angle constraint condition to be:

if (angle < Math.PI / 2) {

But it didn’t work as expected. Instead, when I flipped the sign to:

if (angle > Math.PI / 2) {

It worked correctly

Possible Explanations I’m Considering:

  1. Is my angle calculation incorrect?
    I’m using Math.acos(dot / (mod_a * mod_b)), which always returns a value between 0 and π.
  2. Could I be mistakenly measuring the supplementary angle?
  3. Could this be due to floating-point precision issues?
    Since Math.acos relies on dot products and normalization, could numerical errors cause unexpected results?
  4. Is my vector orientation affecting the logic?
  5. Since a and b are defined relative to different points, is there a sign inconsistency in their direction?
  6. Is the cross product affecting rotation direction?
  7. My rotation logic depends on ax * by – ay * bx. Could this be incorrectly influencing the behavior?

Primevue Forms – how to use FormInstance functions?

Trying out Primevue forms (with Vue3 composition API). I’m struggling to understand the documentation.

https://primevue.org/forms/

It describes FormInstance methods that can be used to setValues,setFieldValue, getFieldStates and check the states of the form. (See API tab). I need to be able to access and set field values from methods in the component script. Are these accessible from there? I’ve been able to use the reset function in a button inside the form by referring to the v-slot variable like so: @click="$form.reset()"

However, I don’t seem to be able to access the actual form from the script. Shouldn’t it be accessible by giving it a ref and creating a ref variable in the script?

So for example, I’m trying something like this:

<Form v-slot="$form" ref="request_form" :initialValues="initialValues" :resolver @submit="submit_requests">
  <FormField v-slot="$field" name="request_type">
    <input type="hidden" v-bind="$field.props">
  </FormField>
  <FormField v-slot="$field" name="id">
    <input type="hidden" v-bind="$field.props">
  </FormField>
....
  <Button type="button" @click="set_value" label="Set Value" />
  <Button type="button" @click="set_values" label="Set Values" />
  <Button type="submit" label="Save" />
</Form>
<script setup>
...
const request_form = ref(null)

const set_value = () => {
  request_form.setFieldValue('request_type', 'my cool request type')
}

const set_values = () => {
  request_form.setValues({
    'request_type', 'my cool request type',
    'id', 1
  })
}
</script>

Based on my reading of the documentation, this should work, but I get TypeError: c.setFieldValue is not a function

Which makes me think I don’t understand how to actually access the form instance. Any help with this appreciated.

Why does “type”: “module” have to be removed from my package.json?

If I want to use import statement in my JavaScript in Node then it’s probably best to put "type": "module" in your package.json, right? I did that. I wrote some code:

"use strict";

import * as fs from 'node:fs'; 

console.log("yo");

and then compiled it to a JavaScript .js file. TypeScript turned my code into this:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

console.log("yo");

And this doesn’t run apparently, as mentioned in ReferenceError: exports is not defined in ES module scope, you need to remove "type": "module" from your package.json. But there is no explanation. If I don’t remove it I get:

ReferenceError: exports is not defined in ES module scope This file is
being treated as an ES module because it has a '.js' file extension
and 'pathNodeJSProjectpackage.json' contains "type": "module". To
treat it as a CommonJS script, rename it to use the '.cjs' file
extension.
    at file:///path/NodeJSProject/script.js:2:23
    at ModuleJob.run (node:internal/modules/esm/module_job:271:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:578:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:116:5)

awaiting promises ergonomics [closed]

Updating an application which have some spaghetti code to await promises.

Most of the code is:

const x = await webAPIcall.get();
const y = await dbORM.get();

But wrapped in a library with some weird ergonomics to get the values out of the calls (i suspect the library was started to just fire events).

Nowadays, is modern JS better at parallelizing those without complex work aroudns?

How can I route to a component, then scroll to a section of the page?

I am having trouble figuring this out.
The site has 3 pages, the scrollable Homepage, the Gallery and the Pricing pages.

I have a navigation bar that, when in the HomePage, uses react-scroll to scroll to the corresponding section of the page.
When not in the HomePage, I want it to first go to the HomePage and then scroll to the correct segment.

I found a similar question to this, but for some reason, I can not get it to route to the homepage.

Also, as a note, the scroll part works fine when I am on the home page; I just can’t get it to transfer back to Home when on another page.

The imports:

import { useLocation, useNavigate } from "react-router-dom";
import { Link as ScrollLink } from "react-scroll";
import * as Scroll from "react-scroll";

The Javascript:

const path = useLocation().pathname;
const location = path.split("/")[1];
const navigate = useNavigate();
const scroller = Scroll.scroller;

const goToPageAndScroll = async (selector) => {
  await navigate("/");
  scroller.scrollTo(selector, {
    duration: 500,
    smooth: true,
    offset: -75,
    spy: true
  });
};

The HTML:

{location !== "pricing" || "gallery" ? (
  <>
    <li>
      {""}
      <ScrollLink to='hero' smooth={true} offset={0} duration={500}>Home</ScrollLink>
    </li>
    <li><ScrollLink to='services' smooth={true} offset={-300} duration={500}>Services</ScrollLink></li>
    <li><ScrollLink to='about' smooth={true} offset={-200} duration={500}>About</ScrollLink></li>
    <li><ScrollLink to='gallery' smooth={true} offset={-250} duration={500}>Gallery</ScrollLink></li>
    <li><ScrollLink to='contact' smooth={true} offset={0} duration={500} className='btn'>Contact Us</ScrollLink></li>
  </>
) : (
  <>
    <li onClick={() => goToPageAndScroll("hero")}>{""}Home</li>
    <li onClick={() => goToPageAndScroll("services")}>Services</li>
    <li onClick={() => goToPageAndScroll("about")}>About</li>
    <li onClick={() => goToPageAndScroll("gallery")}>Gallery</li>
    <li onClick={() => goToPageAndScroll("contact")}>Contact</li>
  </>
)} 

while installing tailwind Css i am having this error ‘npm error could not determine executable to run’

i am trying to install the tailwind in react project but while creating tailwind.config file i am having this issue.
this is the error i am facing
npx tailwindcss init -p npm error could not determine executable to run npm error A complete log of this run can be found in: C:UsersPMLSAppDataLocalnpm-cache_logs2025-03-06T15_42_53_449Z-debug-0.log

i have cleared cheche and deleted node module folder and npm install too. i have installed latest version of node too but still do’nt work.

How can I replicate the GridToolbarFilterButton badge animation with GridToolbarColumnsButton using Material UI component library?

This question is specific to usage of the Material UI React component library. I’ve created a functioning Code Sandbox example, available this link. I am using the Data Grid component, and the default behavior of the Filter button (GridToolbarFilterButton) is such that it shows a Badge over the button’s icon. This is not default behavior of the Columns button (GridToolbarColumnsButton), but I’ve managed to add and achieve the same functionality.

One thing that I am having trouble with is getting the same animation / transition to happen them the badge becomes visible or invisible. On the Filter button, you can see that the badge has an animation where it seems to grow into view, and then shrink out of view. On the Columns button, it just immediately appears or disappears. I’ve spent some time trying to look at the Material UI source code to see if I can piece it together, but it feels just a little bit out of my reach at the moment.

Any thoughts on how I might be able to mimic that same animation for the Columns button? Happy to provide additional information. I’ve included a GIF animation of the Code Sandbox I provided, hopefully this will be a helpful visualize of differing animations between the badge appearing/disappearing on both buttons. Based on this pull request on the MUI-X project, it seems that perhaps the MUI team might be doing something related to this in the relatively near future.

enter image description here