How to fix “Composite.add is not a function” [closed]

I am making a project using MatterJS. However, I am having some difficulties. Whenever I run my code it throws the error TypeError: Composite.add(...) is not a function. I checked to make sure that MatterJS was added correctly by adding the following snippet to my code:

if(Composite.add){
    console.log(Composite.add)
}

Upon running, the code put in the console the contents of Composite.add, and it is definitely defined as a function. Yet it still says that Composite.add is not a function. What can I do to fix this?
Here is the relevant portion of my code:

// module aliases
var Engine = Matter.Engine,
  Render = Matter.Render,
  Runner = Matter.Runner,
  Bodies = Matter.Bodies,
  Composite = Matter.Composite,
  Body = Matter.Body,
  Events = Matter.Events;
World = Matter.World;
// const G = 1;
// var mouse;
// let path = [];
if (Composite.add) {
  console.log('Composite.add found')
}
// create an engine
var engine = Engine.create({
  gravity: {
    x: 0,
    y: 1,
    scale: 0
  }
});

world = engine.world;

var w = window.innerWidth;
var h = window.innerHeight;
var canvas = document.getElementById('canvasM');
let ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let circleA = Bodies.circle(100, 100, 10);
console.log(circleA.area)
//the error is thrown here ↓
Composite.add(world, [circleA])
<script src='https://cdn.jsdelivr.net/gh/liabru/[email protected]/build/matter.js'></script>
<canvas id="canvasM" data-pixel-ratio="2" style="position:relative; z-index:0;"></canvas>

Adding Hidden Validation-Only Fields to WooCommerce Checkout

I have a problem with WooCommerce. I’m trying to add additional fields that will function only as validation. I don’t want them to appear in the order summary, emails, etc. These are my example checkboxes, but I also have others that hide depending on whether someone selects something. Later in the summary, if not selected, it shows “No,” and I don’t want that to be visible at all. This is the new block-based WooCommerce.

woocommerce_register_additional_checkout_field(
    array(
        'id'       => 'namespace/agree-terms',
        'label'    => 'I agree to the terms and conditions',
        'location' => 'order',
        'type'     => 'checkbox',
    )
);

woocommerce_register_additional_checkout_field(
    array(
        'id'       => 'namespace/agree-marketing',
        'label'    => 'I agree to receive marketing emails',
        'location' => 'order',
        'type'     => 'checkbox',
    )
);

How to display document.getElementById in HTML [closed]

I’m a beginner in JavaScript and since I’ve bumped in this problem more then once I’m trying to find an answer. So, I got this challenge: learn about math object operator, perform an operation and display it in my html file. So after writing the code in JS and HTML the result is not displayed in html webpage. So how do I display the document.getElementById in html correctly? What it’s wrong in my code.

Thanks!

I wrote this:

document.getElementById("mathObj").innerHTML = Math.round(4.4);
<p id="mathObj"></p>

I was expecting to be displayed on the webpage, but it’s not working.

Drawing a simple polygon with D3.js doesn’t work

Can’t find the issue why the polygon is not drawn with the following code in d3:

<script type="module">
            import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7/+esm";

            var width = 650,
                height = 225;

            // Creates a projection of the Netherlands
            var projection = d3
                .geoMercator()
                .center([5.5, 52.2]) // GPS coordinates of the center of the Netherlands
                .scale(7000) // Adjust the scale as needed
                .translate([width / 2, height / 2]);

            var path = d3.geoPath().projection(projection);

            // Creates the SVG that state paths and location points will be attached to
            var d3_map = d3
                .select(".svg")
                .append("svg")
                .attr("width", width)
                .attr("height", height);

            // Creates a 'g' (group) element within the SVG which states paths will be attached to
            var states = d3_map.append("g").attr("class", "states");
            var locations = d3_map.append("g").attr("class", "locations");

            var mapFeatures = {
                type: "FeatureCollection",
                features: [
                    {
                        type: "Feature",
                        geometry: {
                            type: "Polygon",
                            coordinates: [[plot]],
                        },
                        properties: {
                            statcode: "PV20",
                            jrstatcode: "2024PV20",
                            statnaam: "Groningen",
                            rubriek: "provincie",
                            id: 1,
                            FID: "provincie_gegeneraliseerd.7ff1a1db-9761-46b4-b8c0-8962f9c49e5a",
                        },
                        id: "PV20",
                    },
                ],
            };
            console.log("Ontvangen coordinaten: ", mapFeatures.features[0].geometry.coordinates);

            // Binds the data to the SVG and create one path per GeoJSON feature
            states
                .selectAll("path")
                .data(mapFeatures.features)
                .enter()
                .append("path")
                .attr("d", path)
                .attr("fill", function (d) {
                    return d.properties.statnaam === "Groningen" ? "#1d92b5" : "grey";
                })
                .style("stroke", "black");
        </script>

So the plot is dynamically filled. For example with the following coordinates: [[4.46658332590609, 51.9189952744721], [4.4665832076367, 51.9189932420877], [4.46660765324146, 51.918992768389], [4.46661899727716, 51.9189924976887], [4.46663310465063, 51.9189921587427], [4.46665520951266, 51.9189917026561], [4.46665580183947, 51.9189982690841], [4.46665885751841, 51.9189981222296], [4.46666937101816,8844, 51.9191898770815], [4.46639899390348, 51.9191872684845], [4.46639666721731, 51.9191518345738], [4.46639599771547, 51.9191419417015], [4.46639402603949, 51.9191104656227], [4.46639314503411, 51.91909670593], [4.46639029235821, 51.9190514701581], [4.46638744152916, 51.9190061445128], [4.46656804474943, 51.9189961435434], [4.46658332590609, 51.9189952744721]]

<div class="svg"></div>

All I get is a blue square: Image of the map

I’ve tried different scaling and center() in the projection. Couldn’t figure out what’s wrong.

Datatable Column parameter value is not working [duplicate]

I’m unable to pass a parameter to the deleteitem() function.

<script>
$(document).ready(function() {
    $('#userTable').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "response.php",
            "type": "POST"
        },
        "columns": [
            { "data": 0 },
            { "data": 1 },
            { "data": 2 },
            { "data": 3 },
            { "data": 4 },
            { title: "Approve", "defaultContent": "<button onclick='edititem();'>Aprove</button>" },
            { title: "Reject", "defaultContent": "<button onclick='deleteitem("+${data[0]}+");'>Reject</button>" }
        ]

       
    });
});


function deleteitem(value) {


alert(value);

  }
   
</script>

ReactJs how to control how many times an alert is show?

I am new to Reactjs, and trying to edit a legacy application that uses the old version 17.

How can i make an alert show only one time ?

I need to show only when the page loads and not when i call edit, delete and add modals ?

I do create the showTotals variable at the constructor :

export default class List extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            showTotals: true,
        };          
    }

Into the render method i call the alert if some condition and showModals are true :

render (){
  if( total_values > contract_total && showModals ) {
        swal('', 'Total is greater than ... ', 'error');                                    
  } 
}

I only need to call the alert when the page loads.

I do not want to call the alert into the actions like delete, add and edit .

Can i change the showTotals to false into the existing onClick event?

   <Button
        onClick={() => this.handleDelActClick(row, rowId)}
        >
        <i>delete</i>
        </Button>

Because i try to set inside the method but the alert still shows :

handleDelActClick = (row, id) => {
        this.setState({ showTotals: false });
            if (data) {
                this.delItem(row.id, id);
            }       
    };

Streamlit app is not displaying the custom component due to frontend asset loading issue

Problem Description

I’m integrating a custom JavaScript component with a Streamlit application. When I run app.py, the app displays an error message in the browser indicating it cannot load the my_folder_uploader component due to potential network latency or proxy settings.

Error message

Your app is having trouble loading the app.my_folder_uploader component.
If this is an installed component that works locally, the app may be having trouble accessing the component frontend assets due to network latency or proxy settings in your app deployment.
For more troubleshooting help, please see the Streamlit Component docs or visit our forums.

Dir Structure

my_streamlit_component/
├── frontend/
│   ├── build/                   # Webpack output directory
│   ├── src/
│   │   └── MyComponent.jsx
├── package.json
├── webpack.config.js
├── .babelrc
└── app.py                       # Streamlit application

Code Snippet

app.py

import streamlit as st
import streamlit.components.v1 as components

_component_func = components.declare_component(
    "my_folder_uploader",
    path="frontend/build"  # Ensure this path points to the correct build directory
)

def my_folder_uploader():
    files = _component_func()
    return files

st.title("Folder Uploader")
uploaded_files = my_folder_uploader()

if uploaded_files is not None:
    st.write("Uploaded files in the folder:")
    for file in uploaded_files:
        st.write(file)

MyComponent.jsx

// MyComponent.jsx
import React, { useCallback } from "react";
import ReactDOM from "react-dom";
import { withStreamlitConnection, Streamlit } from "streamlit-component-lib";

const FolderUploader = () => {
  const handleFiles = useCallback((event) => {
    const files = event.target.files;
    const fileArray = Array.from(files).map(file => file.webkitRelativePath);
    Streamlit.setComponentValue(fileArray);
  }, []);

  return (
    <div>
      <h1>Folder Uploader</h1>
      <input type="file" webkitdirectory="true" onChange={handleFiles} />
    </div>
  );
};

const ComponentWithConnection = withStreamlitConnection(FolderUploader);

ReactDOM.render(<ComponentWithConnection />, document.getElementById("root"));

Environment Information

Python v3.12.6
Node.js v22.13.1
React v17.0.2
Webpack v5.97.1
Babel v5.8.38
Windows 11

What I’ve Tried

Cleared the browser cache.
Rechecked Webpack configuration.
Ensured the React component is correctly mounted.

Expected Outcome

The custom JavaScript component should render correctly within the Streamlit app page and allow users to select a folder for upload.

Laraberg enable default color settings

I have installed VanOns/laraberg package for laravel (v11) and followed the instructions for the whole installation and configuration. Everything seems to work alright and I can view, edit and create the articles with it.

My problem is that im missing the color options. I dont have any setting to change color for a paragraph or other blocks. Even when i want to change the html with color="" it wont accept it and wants to restore the block without this setting.

In the documentation it gives an option for colors, so I expect it to be included.

interface EditorSettings {
    height?: string;
    mediaUpload?: (upload: MediaUpload) => void;
    fetchHandler?: FetchHandler;
    disabledCoreBlocks?: string[];
    alignWide?: boolean;
    supportsLayout?: boolean;
    maxWidth?: number;
    imageEditing?: boolean;
    colors?: Color[];
    gradients?: Gradient[];
    fontSizes?: FontSize[];
}

However, I have tried many ways to enable it but no solution has worked. This is my last try:

        const options = {
            height: "500px",
            mediaUpload: function(callback) {
                callback("https://via.placeholder.com/800x400"); // Beispiel-Bild
            },
            fetchHandler: function(url, options) {
                return fetch(url, options).then(response => response.json());
            },
            disabledCoreBlocks: [], // Beispiel: Paragraph und Bild deaktivieren
            alignWide: true,
            supportsLayout: true,
            maxWidth: 800,
            imageEditing: true,
            colors: [
                { name: "Rot", slug: "red", color: "#ff0000" },
                { name: "Blau", slug: "blue", color: "#0000ff" },
                { name: "Grün", slug: "green", color: "#008000" },
                { name: "Gelb", slug: "yellow", color: "#ffff00" }
            ],
            gradients: [
                { name: "Rot zu Blau", slug: "red-to-blue", gradient: "linear-gradient(90deg, #ff0000, #0000ff)" },
                { name: "Grün zu Gelb", slug: "green-to-yellow", gradient: "linear-gradient(90deg, #008000, #ffff00)" }
            ],
            fontSizes: [
                { name: "Klein", slug: "small", size: 12 },
                { name: "Normal", slug: "normal", size: 16 },
                { name: "Groß", slug: "large", size: 24 }
            ]
        };

        Laraberg.init('editor', options);
    });

Other settings work, even the fontSizes, only the color settings are missing. I want to include the default settings for colors.

When I click a paragraph there should be an option for text color in the sidebar like for font sizes.

Console wont print any errors.

It should look something like this

enter image description here

pull method not available for mongoose.Schema.Types.ObjectId[]

Hey I have created a model User like so:

import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    email: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      required: true,
    },
    status: {
      type: String,
      default: 'I am new!',
    },
    posts: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Post',
      },
    ],
  },
  { timestamps: true }
);

export const User = mongoose.model('User', userSchema);

I want to use the pull method to fetch a specific postId and clear it.

export const deletePost = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const postId = req.params.postId;
    const fetchedPost = await Post.findById(postId);
    if (!fetchedPost) {
      const error = new HttpError("Could not find post.", 404);
      return next(error);
    }
    if (fetchedPost.creator.toString() !== req.userId) {
      const error = new HttpError("Not Authorized!", 403);
      return next(error);
    }
    clearImage(fetchedPost.imageUrl);

    await Post.findByIdAndDelete(postId);

    // Clearing User and Post relation
    const user = await User.findById(req.userId)!;
    if (user) {
      user.posts.pull(postId);
      await user.save();
    }

    res.status(200).json({ message: "Deleted post!" });
  } catch (err) {
    return next(new HttpError("Failed to delete a post", 500));
  }
};

However I am getting error from my ts lsp
Property 'pull' does not exist on type 'ObjectId[]'.ts(2339) any

Have things changed in the the mongoose where pull method is deprecated and do I need to create pull util method manually or am I doing something wrong?

HTML drag and drop API bad performance, heavy hit testing

I am involved on a project that needs to use the drag and drop API with lots of drop zones and many DOM nodes so i am trying to optimize the dragging system as much as possible. I found out that in chrome dev tools performance tab, when dragging the most heavy operation is hit testing, i can understand that it needs hit testing to try to check if the dragging item can be dropped on the item below. The point here is that it is obvious that it is not possible to remove them, hit testing is necessary, but foreach task is executing hit testing twice. That has no sense for me. I want to understand if that cloned hit testing could be removed in some way because it could be a great performance difference.

To do a simple isolated test i tried with a drag&drop example of w3schools, taken from here https://www.w3schools.com/html/html5_draganddrop.asp

<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<p>Drag the W3Schools image into the rectangle:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>

The result of performance here if i zoom onto one task:
Chrome dev tools screenshot of one drag task performance (light example)

It can be seen that the hit test is duplicated, now i will send the same screenshow but in my project, so you can see that it could be a very big performance trouble on heavier examples.
Chrome dev tools screenshot of many drag tasks performance (heavy project)

vite react page not found (Cannot GET /mypage) after assembling the build and redirect on page using address bar

Reproduction:

npm create vite@latest

choose: react

choose: typescript

cd vite-project

npm install

npm i react-router-dom

App.tsx:

import { Routes, Route,  BrowserRouter } from 'react-router-dom';

import './App.css'
import TestA from './pages/TestA'
import TestB from './pages/TestB'
function App() {

  return (
    <>
      <BrowserRouter>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <h3>Nav:</h3>
          <a href="/">TestA</a>
          <a href="/testb">TestB</a>
        </div>
        <Routes>
          <Route path="/" element={<TestA />} />
          <Route path="/testb" element={<TestB />} />
        </Routes>
      </BrowserRouter>
    </>
  )
}

export default App

pages/TestA.tsx:

const TestA = () => {
  return (
    <div>TestA</div>
  )
}

export default TestA

pages/TestB.tsx:

const TestB = () => {
  return (
    <div>TestB</div>
  )
}

export default TestB

vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
})

package.json:

{
  "name": "vite-project",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-router-dom": "^7.1.4"
  },
  "devDependencies": {
    "@eslint/js": "^9.17.0",
    "@types/node": "^22.12.0",
    "@types/react": "^18.3.18",
    "@types/react-dom": "^18.3.5",
    "@vitejs/plugin-react": "^4.3.4",
    "eslint": "^9.17.0",
    "eslint-plugin-react-hooks": "^5.0.0",
    "eslint-plugin-react-refresh": "^0.4.16",
    "globals": "^15.14.0",
    "typescript": "~5.6.2",
    "typescript-eslint": "^8.18.2",
    "vite": "^6.0.5"
  }
}

index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

Problem:

npm run build 

load on the server (or open on local server)

when i try to go through (for example http://127.0.0.1:5500/testb) the address bar or using navigaton I got error:

Cannot GET /testb

I tried: 76115927 75272022 75554837 but it not helped me. This problem is from vite v2 and I don’t know how to solve it.

Make typescript identify specific object type in array objects instead of union

There is an api that generates a response like this:

type Resp = {
    id: string;
    keyA: {
        subKeyA: string;
        subKeyA2: string;
        id: string;
    }[],
    keyB: {
        subKeyB: string;
        subKeyB2: number;
        id: string;
    }[],
}

so it’s an object with a id string prop and the other props are arrays of objects.
These objects only have id prop in common, rest of the props can be named differently and have different types.

What I want is a function that is able to get the inner props based on that id:

const testFn = <K extends Exclude<keyof Resp, "id">, S extends Resp[K]>(src: S, attribute: keyof S[number], idMatch: string) =>{
    for (const { id, ...props } of src) {
            if (id === idMatch) {
                return props[attribute]; // ts error 2536
            }
    }
    return null;
};

The function works fine, but typescript throws error on return. This is because it sees the type as a union of all possible object types in those arrays.

How can I make it see only the type of the object that is supposed to be returned?

How to stop PhaserJS from eating mouse events?

I’ve put a PhaserJS instance on my website for background visuals. Unfortunately, when the mouse is over it, it eats all my clock events (and probably other mouse events too), despite that the relevant div is actually underneath the visual elements that are meant to be hearing these events. This means that these objects don’t get to hear the events, which is breaking a lot of functionality.

I’ve tried this:

let gio = inst.game.input; // Game input object
gio.enabled = false;
gio.isOver  = false;
gio.mouse.enabled = false;
gio.mouse.isTop = false;
gio.globalTopOnly = false;

But to no avail. Ideas, anyone?

Test can’t find conditional render component, disappearing too quickly

I am displaying a loading indicator whilst I wait for an async process to occur, however I believe my test might be missing it being displayed because the async process is too quick?

const [isLoading, setIsLoading] = useState(false);

const handleClick = async () => {
  setIsLoading(true); // Show loader when waiting for url to be fetched
  await getAsyncRedirectUrl().then(url => {
    setIsLoading(false); // Hide loader when url fetched
    window.open(url);
  })
}

return (
  <>
    {isLoading && <LoadingIndicator data-testid="loader" />}
    <button onClick={handleClick} data-testid="button">Click me</button>
  </>
)

I have tried to test with the following, to no avail.

it('should show loader', async () => {
  render(<MyComponent />);

  await userEvent.click(screen.queryByTestId('button'));

  await waitFor(() => {
    expect(screen.queryByTestId('loader')).toBeInTheDocument();
  });  
});

The outcome of this test is a failure stating that the loader wasn’t found within the DOM.

How to dispatch multiple events from a component?

Let’s imagine we have simple <input> with onChange and onPaste event. In Svelte4 I have used to use this code:

import {createEventDispatcher} from "svelte";
const dispatch = createEventDispatcher();

function change() {
  dispatch("change");
}

function paste() {
  dispatch("paste");
  dispatch("change");
}
<input on:paste={paste} on:change={change} />

But in Svelte5 I should use (as it’s written in the documentation) $props but I don’t know how to dispatch multiple events (paste and change). Any ideas?