How can I pass props from one child component to another and render in parents with reactJs?

I am passing props from one child component to another and render the data in a parents.
Below is where I am capturing data

import React, { useState } from 'react';
import CSVUpload from './Components/CSVUpload';
import AreaChart from '../Dashboard2/DashboardCharts/AreaChart';
import Dashboard2 from '../Dashboard2/Dashboard';




export default function DataStorage(){
    
    const [csvData, setCSVData] = useState([]);

    const handleCSVDataLoaded = (data) => {
        setCSVData(data);
        
      };
    
    return(
        <>
    <h1>CSV Upload Example</h1>
      <CSVUpload onDataLoaded={handleCSVDataLoaded}  />

        </>
    )
}

Here I can upload data. This works well. Now I want to pass the data to the following child

import React from 'react';
import Paper from '@mui/material/Paper';
import Chart from 'react-apexcharts';

const AreaChart = (props) => {
    const csvData = props.csvData;
    // Extract the necessary data from 'csvData' for the plot
    const categories = csvData.slice(1).map(item => item[0]);
    const data_ = csvData.slice(1).map(item => item[1]);
    console.log(categories)
    const data_series_name = 'Value'; // Provide a name for the series

  const options = {
    xaxis: {
      type: 'datetime',
      categories: categories,
    },
    dataLabels: {
      enabled: false, // Set to false to turn off the display of values
    },
    chart: {
      toolbar: {
        show: true, // Turn off the download option
      },
    },
  };

  const series = [
    {
      name: data_series_name,
      data: data_,
    },
  ];

  return (
    <Paper elevation={4}>
      <Chart options={options} series={series} type="area" height={500} />
    </Paper>
  );
};

export default AreaChart;

and I want to render here

import React from 'react';
import AreaChart from '../Dashboard2/DashboardCharts/AreaChart';

const RenderPlot = () => {
  return (
    <div>
      <h2>PLOT</h2>
       <AreaChart />
    </div>
  );
};

export default RenderPlot;

How can I make it work ? it is not working the way I expecting. Meaning the AreaChart should be rendered on the desired section only

Plot Figure in Web Browser (Offline) in Python Using Flask, accessing .js and .css Files on my local drive

I need some pointing in the right direction. I have a python flask script that opens up a form on my web browser at http://localhost:8000. When I enter a number into the field and press submit, it renders a dummy figure. It works works great when I’m connected to the internet but when I’m on a server that restricts internet access, it wont render the figure.

There are 3 files/links it accesses from within the HTML files:

https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css

https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js

https://cdn.plot.ly/plotly-latest.min.js

How can I get these files onto my local and have the HTML files access them? I am new to HTML and the javascript world.

Here is my app.py, and two template HTML files.

app.py

from flask import Flask, render_template, request
import pandas as pd
import json

import plotly
import plotly.graph_objects as go
import plotly.io as pio

pio.renderers.default = 'browser' # or 'colab' or 'iframe' or 'iframe_connected' or 'sphinx_gallery'

app = Flask(__name__)
app.secret_key = b"my_secret_key"

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST' and 'auto_number' in request.form:
        graphJSON = gm()
        return render_template('plot_fig.html', graphJSON=graphJSON) 
    return render_template("home.html")

def gm():
    fig = go.Figure(data=go.Scatter(x=[1,2,3,4,5], y=[0,1,2,1,0], mode='markers'))
    fig.update_layout(title="Test Figure")
    fig.update_traces(marker={'size': 15})
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return graphJSON
    

if __name__ == '__main__':
    app.run(host='localhost', port=8000, debug=False)

home.html

<!doctype html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>

<body>
    <h1 class="text-center py-5">Figure Generator</h1>
    <div class="row">
        <div class="col-md-4"></div>
            <div class="col-md-4">
                <form class="pure-form" method="POST">

                    <label for="LocoNum" class="form-label">Enter any number here:</label>
                    <input type="text" name="auto_number" placeholder="1234" class="form-control">
                    <p></p>

                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        <div class="col-md-4"></div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
        crossorigin="anonymous"></script>
</body>

plot_fig.html

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
        rel="stylesheet" 
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" 
        crossorigin="anonymous">
</head>

<body>
  <div id='chart' class='chart'></div>
</body>

<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type='text/javascript'>
  var graphs = {{graphJSON | safe}};
  Plotly.plot('chart',graphs,{});
</script>

</html>

How does updating the state in Reactjs work?

I need help understanding why is that the state is updated in the React Developer Tools state, but not when i console.log it.
Below is the code:

const [values, setValues] = useState({
    lastName: "",
    firstName: "",
    lastNameHiragana: "",
    firstNameHiragana: "",
    birthday: "",
    sex: "男",
    telephone: "",
    email: "",
    enterDate: "",
    companyId: "securityInt(SECI)",
    departmentId: "dev",
    commissionStatusId: "somestring",
    houseStatusId: "somestring",
    businessManager: "",
  });


  const onChange = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };

  const handleForm = (e) => {
    e.preventDefault();

    const data = {
      firstName: values.firstName,
      lastName: values.lastName,
      firstNameHiragana: values.firstNameHiragana,
      lastNameHiragana: values.lastNameHiragana,
      companyId: values.companyId,
      birthday: values.birthday,
      sex: values.sex === "somestring" ? 0 : 1,
      mail: values.email,
      telephone: values.telephone,
      enterDate: values.enterDate,
      departmentId: values.departmentId,
      commissioningStatusId: values.commissionStatusId === "somestring" ? 0 : 1,
      houseStatusId: values.houseStatusId,
      businessManager: values.businessManager,
    };

    const newErrorMessage = {};
    const refresh_token = localStorage.getItem("refresh_token");
    const headers = {
      headers: {
        Authorization: `Bearer ${refresh_token}`,
      },
    };

    for (const name in values) {
      const hiraganaRegex = /^[ぁ-ん]+$/;
      const telephoneRegex = /^[0-9]{9,11}$/;
      const emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$/;

      switch (name) {
        case "lastName":
        case "firstName":
        case "birthday":
        case "enterDate":
          if (!values[name]) {
            newErrorMessage[name] = "必須項目です";
          }
          break;

        case "lastNameHiragana":
        case "firstNameHiragana":
          if (!values[name]) {
            newErrorMessage[name] = "必須項目です";
          } else if (!hiraganaRegex.test(values[name]) && values[name]) {
            newErrorMessage[name] = "ひらがなで入力して下さい。";
          }
          break;

        case "telephone":
          if (!values[name]) {
            newErrorMessage[name] = "必須項目です";
          } else if (!telephoneRegex.test(values[name]) && values[name]) {
            newErrorMessage[name] = "9~11桁の半角数字で入力して下さい";
          }
          break;

        case "email":
          if (!values[name]) {
            newErrorMessage[name] = "必須項目です";
          } else if (!emailRegex.test(values[name]) && values[name]) {
            newErrorMessage[name] = "メールアドレスの形式が正しくありません";
          }
          break;
      }
    }
    if (!Object.keys(newErrorMessage).length) {
      // Get companies ID
      const fetchData = async () => {
        if (
          typeof values.companyId === "string" &&
          typeof values.departmentId === "string"
        ) {
          const [companyRes, departmentRes] = await Promise.all([
            axiosInstance.get("/company"),
            axiosInstance.get("/department"),
          ]);

          const company = values.companyId.slice(
            0,
            values.companyId.indexOf("(")
          );
          const findCompany = companyRes.data.result.find(
            (item) => item.name === company
          );
          const findDepartment = departmentRes.data.result.find(
            (item) => item.name === values.departmentId
          );
          console.log(values.companyId);
          console.log(values);
          setValues((prevValues) => ({
            ...prevValues,
            companyId: findCompany.id,
            departmentId: findDepartment.id,
          }));
          console.log(values.companyId);
        }
      };

      // Send the information to server
      const sendData = async () => {
        try {
          const response = await axiosInstance.post("/employee", data, {
            headers: headers,
          });

          console.log(response);
        } catch (error) {
          console.log(error);
        }
      };

      // Call the functions in sequence
      (async () => {
        await fetchData();
        await sendData();
      })();
    }

    setErrorMessage(newErrorMessage);
  };

I need to send the correct companyId and departmentID, which is OK when I check React Developer Tools state, but when I console.log the values, it gives me not the desired result.
Is the below not working, why?

setValues((prevValues) => ({
       ...prevValues,
       companyId: findCompany.id,
       departmentId: findDepartment.id,
}));

Is there anything wrong with the code?
Any input would be helpful.

Thank you in advance.

Object.hasOwn property is possibly undefined TS

tsconfig.json:
{
“compilerOptions”: {
“strict”: true,
“lib”: [“ES2022”],
“exactOptionalPropertyTypes”: true
}
}

interface Shape {
  kind: "circle" | "square",
  radius?: number,
  sideLength?: number
}

function getArea(shape: Shape): number | undefined {
  if (shape.kind === "circle" && Object.hasOwn(shape, "radius")) {
    // 'shape.radius' is possibly 'undefined'. ts(18048)
    return Math.PI * shape.radius**2;
  }
  else if (shape.kind === "square" && "sideLength" in shape) {
    return shape.sideLength**2;
  }
  return undefined;
}

const s1: Shape = {kind: 'circle', radius: undefined};  // if i try this
/* Type '{ kind: "circle"; radius: undefined; }' is not assignable to type 'Shape' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
   Types of property 'radius' are incompatible.
   Type 'undefined' is not assignable to type 'number'.ts(2375) */

why this undefined error? What is missing?

Scroll bug when opening webview / iframe in iOS and otherwise fine in android / web

I have a react app where I use material ui (older version).

please see the video where I have shown the bug.
video link (dropbox)

video showing behaviour in android device

Actually I am not getting any leads to find the bug, somehow it is just the problem happening in iOS when dialog box / popup opens and when the keyboard is opened. So when keyboard opens it just makes the whole page to scroll & that should not happen.

PS: please don’t mark the question as false as I cannot provide a reproducible code as I am not sure where the problem arrises (via material ui or common components or specific code), but if you find some bug and need some code please let me know in the comments and I ll update the question with that code. Currently I am not providing code as it works fine on web and android device.

What I expect: some IOS developer who might have come across the problem might be able to find the bug, it is somehow a behaviour of the iOS thing as it works well in android.

jQuery I can’t read the nodename with (document).on(click [duplicate]

I can’t access attributes of button clicked, the result is «undefined».

Note: The example is built to avoid conflict between the function of the button and the touchstar function.

What’s wrong?

$("#main").on("touchstart, touchend", () => {
  console.log("touch zone");
})

$(document).on("click", "#main a", (e) => {
    e.preventDefault();

    var ab = this.nodeName;
  var cd = $(this).prop("nodeName");
  var ef = $(this).attr("href");
  
  console.log("Button click NODENAME> "+ab);
  console.log("Button click NODENAME> "+cd);
  console.log("Button click ATTR> "+ef);
});
.main {
  width: 40vh;
  height: 90vh;
  overflow: hidden auto;
  background: Gray;
}
<section id="main" class="main">
  <h1>Title demo <a href="#">Action</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
  <h1>Title demo <a href="#">Action</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
  <h1>Title demo <a href="#">Action</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
  <h1>Title demo <a href="#">Action</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
  <h1>Title demo <a href="#">Action</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Codepen into elementor

I wanted to place this codepen project https://codepen.io/pizza3/pen/JjKjbZY into an htlm widget in elementor, but I couldnt get it working no matter what I tried, anyone could help me for this ?

Nothing is displayed in the htlm widget when I insert the code in the script tag
this is a part of the javascript that I can’t get working into elementor :

import { EffectComposer } from "https://unpkg.com/[email protected]/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "https://unpkg.com/[email protected]/examples/jsm/postprocessing/RenderPass.js";
import { UnrealBloomPass } from "https://unpkg.com/[email protected]/examples/jsm/postprocessing/UnrealBloomPass.js";
import { OrbitControls } from "https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls";

var scene,
  camera,
  renderer,
  width = window.innerWidth,
  height = window.innerHeight,
  controls,
  bloomPass,
  composer,
  material;

nginx serves all .js/.css but not .html

Been a long time apache user, and serving static files .html, .js, .css in various subdirectories using reverse proxy is very simple.

For example, I can serve all the following with simply a DocumentRoot:
https://server/dir1/dir5/style.css

https://server/dir1/dir4/theme4.html

https://server/dir1/dir4/a.jpg

https://server/dir1/dir6/theme6.html

https://server/dir2/theme_template.html

TEST
  |
  |--->dir1
  |       |------->dir5
  |       |         |----> style.css
  |       |
  |       |-------->dir4
  |       |          |----> a.jpg
  |       |          |----> b.jpg
  |       |          |----> theme4.html
  |       |-------->dir6
  |                  |----> a.jpg
  |                  |----> b.jpg
  |                  |----> theme6.html
  |   
  |--->dir2
  |        |----->Web.xml
  |        |----->theme_template.html
  |
  |--->dir3
         |---->login.js

My issue with Nginx is the opposite of all posts below; I can get .js, .css, .whatever, but not .html!

The above directories is in a reverse proxy Ngnix.

how to make NGINX serve static content like .js, .css, .html?

Nginx fails to load css files

How to serve HTML from multiple JS, CSS directory in nginx

NGINX does not serve js and css files while serving html

nginx not serving css/js images

Nginx cannot serve css or js

Talking directly to the reverse proxy server I can get all .html, .css, .js, .jpg files with no problem.

The problem is when I talk to the proxy server. In my case I can get all .css, .js, .jpg with no problem. Only .html files fails!

Using:

https://server/dir1/dir4/theme4.html

in web browsers I get 405 Method Not Allowed and a 404 Not Found, and it fails in CORS preflight, with OPTION and GET.

It seems that I must specify each dir1, dir5, dir4, dir6, dir2, dir3 in Nginx’s location block?!

I tried:

    location ~* .(html)$ {
            root /var/www/html/TEST;
            #try_files $uri $uri/ /dir1$uri /dir1/diy4$uri /dir1/dir4/dir6$uri =404;
    }

    location / {
            proxy_no_cache $http_pragma $http_authorization;
            #try_files $uri $uri/ =404;
            include /etc/nginx/mime.types;
    }

Also in Nginx server block I have:

    add_header Access-Control-Request-Methods 'GET, OPTIONS' always;

I have no idea how to make this simple serving of static files work…

Please help.

testcafe selector and expect timeout options are not absolutely clear

I have a following examples:

import moment from 'moment';
import { Selector } from 'testcafe';

fixture `A set of examples that illustrate how to use TestCafe API`
    .page `https://devexpress.github.io/testcafe/example/`
    .after(async ctx => {
        console.log(`End: ${moment().format("HH:mm:ss:SSS")}`)
    } )

// !!!!!!!!!!! "selectorTimeout": 15000,

// ~15 sec
test('Test Selector', async t => {
    console.log(`Start: ${moment().format("HH:mm:ss:SSS")}`)
    await t.click(Selector("asdasdasd"));
    console.log(`End: ${moment().format("HH:mm:ss:SSS")}`)
});

// ~15 sec
test('Test expect', async t => {
    console.log(`Start: ${moment().format("HH:mm:ss:SSS")}`)
    await t.expect(Selector("asdasdasd").visible).ok("");
    console.log(`End: ${moment().format("HH:mm:ss:SSS")}`)
});

// ~6 sec
test('Test expect with selector time out', async t => {
    console.log(`Start: ${moment().format("HH:mm:ss:SSS")}`)
    await t.expect(Selector("asdasdasd", {timeout: 6000}).visible).ok("");
    console.log(`End: ${moment().format("HH:mm:ss:SSS")}`)
});

// ~15 sec
test('Test expect with time out', async t => {
    console.log(`Start: ${moment().format("HH:mm:ss:SSS")}`)
    await t.expect(Selector("asdasdasd").visible).ok("", {timeout: 6000});
    console.log(`End: ${moment().format("HH:mm:ss:SSS")}`)
});

the outcome for the first 3 are clear to me, but what about 4th one? I would like to wait for 6 seconds instead of selectorTimeout. Why it does not pickup specified timeout and does not override the selector one?
Another weird case is that testcafe(at the bottom of browser) shows green light, supposedly expect is passed, but the test fail.

How to get the PATH from .bashrc in JavaScript GitHub Action?

This is a general problem with GitHub Actions and to have the PATH and other environment variables properly set up, we add the following to the top of our workflows:

defaults:
  run:
    shell: bash -leo pipefail {0}

That changes the shell that is used for commands so that it sources .bashrc. This is important to us, since we are using macOS runners and binaries installed with brew aren’t in the default PATH. (There are also a few other reasons we need it.)

A colleague of mine has written a custom JavaScript action that executes a command that is in different locations on differnet runners, depending on OS and CPU architecture. To support all architectures, he’s appending all locations to the PATH before executing the command:

PATH=$PATH:location1:location2 command

Another colleague of mine added a new runner type that installed the binaries to a third location. To be able to support the JavaScript action, he added symlinks to “location1” so that the command would be found by the action, without having to update the PATH in the action.

It’s a bit of a mess and it could easily be cleaned up if I could get the JavaScript action to source .bashrc and have the proper PATH available. Only problem is that I don’t know how to do that. It would be nice if there was some option I could pass to make it do that:

runs:
  using: 'node16'
  main: 'dist/index.js'

I could probably source .bashrc from within the JavaScript and I would accept such answers, as long it’s not too messy.

Transform array of objects with reduce and javascript

I have an array of objects and I´d like to transsform it in a other.

I can do it with a for loop, but I´d like to use reduce.
How could I do it using reduce?

const arr=[
  { medico: "med1", rateio: "rat1", convenio: "conv1", subtotal: 10 },
  { medico: "med2", rateio: "rat2", convenio: "conv2", subtotal: 10 },
  { medico: "med2", rateio: "rat2", convenio: "conv2", subtotal: 20 },
  { medico: "med1", rateio: "rat1", convenio: "conv3", subtotal: 20 },
  { medico: "med1", rateio: "rat1", convenio: "conv3", subtotal: 25 },
  { medico: "med2", rateio: "rat3", convenio: "conv4", subtotal: 15 },
  { medico: 'med2', rateio: 'rat4', convenio: 'conv3', subtotal: 10 },
];

I need the next result:

const result=[{
  medico: "med1", [
    {
      rateio: "rat1",
      grandtotals: [
        { convenio: "conv1", sum_subtotal: 10 },
        { convenio: "conv3", sum_subtotal: 45 }
      ]
    },
]
},
  {
    medico: "med2", [
      {
        rateio: "rat2",
        grandtotals: [
          { convenio: "conv2", sum_subtotal: 30 },
        ]
      },
      {
        rateio: "rat3",
        grandtotals: [
          { convenio: "conv4", sum_subtotal: 15 },
        ]
      },
      {
        rateio: "rat4",
        grandtotals: [
          { convenio: "conv3", sum_subtotal: 10 },
        ]
      }
    ]
}]

Getting values in Jquery Query builder using selectize

I’m trying to solve a problem for some days but I can’t do it.

This code is using Jquery Query Quilder and the plugin selectize, to allow me selecting multiple values.

Everything is okay, except that I could’t get the values selected in the input. The screen below show how is the graphic interface:

enter image description here

The js code follows below:

$(document).ready(() => {
    
        let builder = $('#builder');
    
        const optionsValue = {
            request_type: [
                { value: 'request1', label: 'Request 1' },
                { value: 'request2', label: 'Request 2' },
                { value: 'request3', label: 'Request 3' }
            ],
            priority: [
                { value: 'high', label: 'High' },
                { value: 'medium', label: 'Medium' },
                { value: 'low', label: 'Low' }
            ]
        };
    
        const buildOptions = (result) => {
    
            let options = {};
            let filters = [];
    
            for (let key in result) {
    
                let values = result[key];
    
                for (let key_value in values) {
                    let value = values[key_value];
                    value.optgroup = key;
    
                    value.field = values[key_value].id;
    
                    value.valueSetter = function(rule, val) {
                        rule.$el.find('.rule-value-container input')[0].selectize.setValue(eval("[" + val + "]"));
                    }
    
                    value.valueGetter = function(rule) {
                        return rule.$el.find('.rule-value-container input')[0].selectize.getValue().split(',');
                    }
    
                    value.plugin_config = {
                        valueField: 'value',
                        labelField: 'label',
                        searchField: 'label',
                        sortField: 'label',
                        plugins: ['remove_button'],
                    };
    
                    filters.push(value);
                }
            }
    
            options.allow_empty = { allow_empty: true };
            options.filters = filters;
    
            return options;
        }
    
        const getData = () => {
            return fetch('./request/getdata.php')
            .then(response => response.text())
            .then(data => {
    
                let result = JSON.parse(data);
    
                let options = buildOptions(result);
    
                builder.queryBuilder(options);
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    
        const clickSelect = () => {
            $(document).on('change', '.rules-list li .rule-filter-container select', function() {
                let parent = $(this).closest(".rule-container");
                let input_text = parent.find(".rule-value-container input");
    
                let selectedValue = $(this).val();
    
                input_text.selectize({
                    plugins: ["restore_on_backspace", "clear_button", "remove_button"],
                    delimiter: " - ",
                    persist: true,
                    maxItems: null,
                    valueField: "value",
                    labelField: "label",
                    searchField: ["label", "value"],
                    options: optionsValue[selectedValue],
                    allowEmptyOption: true,
                    multiple: true,
                    input: 'selectize'
                });
            });
        }
    
        const getQueryBuilderData = () => {
            $("#qbinfo").on("click", function(){
    
                var rules = builder.queryBuilder('getRules');
    
                console.log(rules);
            });
        }
    
        getData().then(() => {
            clickSelect();
            getQueryBuilderData();
        });
    });

When it executes the method getQueryBuilderData(), the result is this:

enter image description here

The field value in the inputs return empty 🙁

I believe that the problem is in one of these tow methods:

        value.valueSetter = function(rule, val) {
            rule.$el.find('.rule-value-container input')[0].selectize.setValue(eval("[" + val + "]"));
        }

        value.valueGetter = function(rule) {
            return rule.$el.find('.rule-value-container input')[0].selectize.getValue().split(',');
        }

Because when I use debug, I can’t obtain the values from the input, but I am not sure that the problem is here.

Phaser Complex Collisions

How can I detect the collisions of multiple children from different groups?

enter image description here

Imagine something like this, but with square hitboxes
the pink object is from one group, the red object from another, and the orange objects from another group

(also, this exact order/position is not necessary, but as long as each orange object is touching two bigger objects and they are near each other)

how can I get an collision like this in arcade physics? (matter.js solutions still work if its not possible in arcade, but arcade is preferred)

How to call properly from Plugin to inject meta data in a specific component

I am trying to implement a ‘application/ld+json’ in the header whenever I use the Item collapse component. To not have dublicate script tags in the head I am trying to inject the json data from a plugin whenever I need it. I am using nuxt3 and vue3 js in my setup. I am pretty sure the call for the addLdScript is wrong I am just not sure how to properly do that.

That’s my code:

export default defineNuxtPlugin((nuxtApp) => {
    const metaLdScripts = []

    nuxtApp.addLdScript = (script) => metaLdScripts.push(script)

    const attachLdScripts = () => {
        const head = document.getElementsByTagName('head')[0]

        metaLdScripts.forEach((script) => {
            const scriptTag = document.createElement('script')

            scriptTag.type = 'application/ld+json'
            scriptTag.text = JSON.stringify(script)

            head.appendChild(scriptTag)
        })
    }

    nuxtApp.hook('render:route', (url, result, context) => {
        attachLdScripts()
    })
})

<template>
    <div v-editable="blok" class="c-item c-item-collapse">
        <button @click="toggleCollapse" class="c-item-collapse__header">
            <div class="c-item-collapse__title">
                <ui-headline size="0" :tagName="blok.title_headline">
                    {{ blok.title }}
                </ui-headline>
            </div>
            <div class="c-item-collapse__actions">
                <ui-icon v-if="!isCollapsed" icon="circle-minus" />
                <ui-icon v-else icon="circle-plus" />
            </div>
        </button>
        <div></div>

        <div v-show="!isCollapsed" class="c-item-collapse__content">
            <StoryblokComponent
                v-for="blok in blok.items"
                :key="blok._uid"
                :blok="blok"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue'

const isCollapsed = ref(true)

function toggleCollapse() {
    isCollapsed.value = !isCollapsed.value
}

const { blok } = defineProps({ blok: Object })

const $addLdScript = inject('addLdScript')

onMounted(() => {
    $addLdScript({
        '@context': 'https://schema.org',
        '@type': 'FAQPage',
        mainEntity: [
            {
                '@type': 'Question',
                name: blok.title,
                acceptedAnswer: {
                    '@type': 'Answer',
                    text: blok.items.map(
                        (item) => item.body?.content[0]?.content[0]?.text
                    ),
                },
            },
        ],
    })
})
</script>

<style lang="scss">
.c-item-collapse {
    @apply p-8 bg-white rounded-xl md:rounded;

    .ui-section--bg-white & {
        // box-shadow: 0px 0px 25px 0px #22222214;
        @apply bg-gray-light;
    }

    &__header {
        @apply flex justify-between items-center text-graphite w-full;
    }

    &__actions {
        @apply flex items-center;
    }

    &__title {
        @apply font-black font-barlow text-left text-sm md:text-base;
    }

    &__content {
        @apply pt-4 text-xs md:text-base;
    }
}

.c-item-collapse + .c-item-collapse {
    @apply mt-2 md:mt-4;
}
</style>

Error: $addLdScript is not a function.

Any hints are much appreciated!