Scrolling scollbar programatically

I have created a slider component in svelte that shows a number of product cards in a list. The cards are snapping when clicking the right/left button in the scrollbar sinceI have added “scroll-snap-type: x mandatory” in the CSS for the container.

enter image description here

How do i mimic click on the scrollbars left/right-arrows for my custom navigation buttons? Setting the scrollbar position won’t do the trick.

+page.svelte

<SliderProducts>
  {#each data.productsFeaturedData as product}
    <ProductCard product={product}/>
  {/each}
</SliderProducts>

SliderProducts.svelte

<script lang="ts">
  import Flex from '../atoms/Flex.svelte';
  import ButtonNavigation from '../molecules/ButtonNavigation.svelte';

  $: innerWidth = 0;
  $: containerWidth = 0;
  $: marginOffset = (innerWidth - containerWidth) / 2 + 8;

  const navigateSlider = (x: MouseEvent) => {
    if (x.target) {
        const element = x.target as HTMLButtonElement;
        const direction = element.dataset.direction;

        // TODO: Implement button navigation
        console.log(direction);
    }
  };
</script>

<svelte:window bind:innerWidth />

<div class="slider-products">
  <div class="container" bind:clientWidth={containerWidth}>
    <h2>Trending in Shoes</h2>
    <div class="button-navigation__container">
        <ButtonNavigation direction="left" on:click={navigateSlider} />
        <ButtonNavigation direction="right" on:click={navigateSlider} />
    </div>
  </div>

  <div class="slider-container">
    <Flex type="row" vAlign="top" colGap={true}>
        <div
            class="slider-track"
            style="margin-left: {marginOffset}px; padding-right: {marginOffset}px;"
        >
            <slot />
        </div>
    </Flex>
  </div>
</div>

How to have non-minified files to be rendered on DEBUG configuration

I have C# asp. net framework Visual Studio solution. The .aspx/.ascx files do have a script tags written. Since we use a minified mechanism outside of Visual Studio, minified files are being referenced on the pages.
e.g.

The problem is, whenever I want to debug, I need to remove the .min from the script tag, so that the non-minified file is rendered.

The problem is, developers do often forget to put the .min back to the .aspx/.ascx files, then the non-minified files get rendered in non-prod and prod environments.
I am looking for a solution, where I can remove the .min.js from the script file, whenever the web project runs in the DEBUG configuration, so that
-developers does not have make this change and later forget to put the .min back to the code base.
So, in theory this what I am trying to achieve

In the DEBUG configuration, I should have the script tag to be <script src=abc.js></script>
I think it can be done with some sort of code behind code to insert the entire script tag.
I do not think I can go with RegisterStartUpScript part, as I have files in MVC as well.

tried if I can perform a code-behind C# code to insert a script tag, could not succeed.

React AG Grid – Validate that Custom Cell is not empty if row selected

I have a Grid of 3 columns. Each row has a cell with a Checkbox and two Custom Cell Components (by default empty). Whenever a Custom Cell is clicked, a Modal opens up and allow the user to:

  • Select a value from radio buttons
  • Insert a value from input field

If a row is selected the Custom Cells of that row are mandatory, therefore should not be empty in order to proceed (a Submit button will then be displayed).

What is the best way to validate that the Custom Cells of a selected row are not empty?

Here is the code of my Grid:

const Grid = () => {
  const [rowData] = useState<IRow[]>([
    {
      car_brand: '',
      car_name: '',
    },
    {
      car_brand: '',
      car_name: '',
    },
    {
      car_brand: '',
      car_name: '',
    },
  ]);

  const [columnDefs] = useState<ColDef[]>([
    {
      field: 'car_brand',
      headerName: 'Car Brand',
      cellRenderer: SelectCarBrand,
    },
    {
      field: 'car_name',
      headerName: 'Car Name',
      cellRenderer: EnterCarName,
    },
  ]);

 const rowSelection = useMemo(() => {
   return {
     mode: 'multiRow',
   };
 }, []);

  return (
    <div>
      <AgGridReact rowData={rowData} columnDefs={columnDefs} rowSelection={rowSelection} />
    </div>
  );
};

export default Grid;

Here is the code of one Custom Component:

const SelectCarBrand = (params: CustomCellRendererProps) => {
  const { isOpen, onOpen, onClose } = useDisclosure();

  const [radioValue, setRadioValue] = useState<string>();

  const handleOnChange = (value: string) => {
    setRadioValue(value);
    params.setValue(value);
  };

  return (
    <Box>
      <HStack onClick={onOpen} cursor="pointer">
        {!radioValue && (
          <Text>
            Select Car Brand
          </Text>
        )}
        {radioValue && <Text>{radioValue}</Text>}
      </HStack>

      <Modal isOpen={isOpen} onClose={onClose}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>
            Select Car Brand
          </ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <RadioGroup onChange={(e) => handleOnChange(e)}>
              <Stack>
                <Radio value="Tesla">
                  <Text>Tesla</Text>
                </Radio>
                <Radio value="Ferrari">
                  <Text>Ferrari</Text>
                </Radio>
                <Radio value="Lamborgini">
                  <Text>Lamborgini</Text>
                </Radio>
              </Stack>
            </RadioGroup>
          </ModalBody>

          <ModalFooter>
            <Button onClick={onClose}>
              Close
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </Box>
  );
};

export default SelectCarBrand;

Text is positioned incorrectly (Tesseract.js)

I’m creating a image to text converter where the text in the image can be selected (like Live Text on iOS). I would like the generated text to be the same size and position as the original text in an image.

The idea is that the generated text will be transparent (It’s solid in the image for demonstration purposes) because I think it’ll be too complicated to match the text in the image exactly but at least the user will be able to select the text.

Result

Original Photo for Testing

Here’s my code

document.getElementById('imageUpload').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const image = document.getElementById('uploadedImage');
            image.src = e.target.result;

            const progressBar = document.getElementById('progressBar');
            progressBar.style.display = 'block';

            Tesseract.recognize(
                image.src,
                'eng',
                {
                    logger: function(m) {
                        if (m.status === 'recognizing text') {
                            progressBar.value = m.progress;
                        }
                    }
                }
            ).then(({ data: { text, lines } }) => {
                progressBar.style.display = 'none';
                const textOverlay = document.getElementById('textOverlay');
                textOverlay.innerHTML = '';

                lines.forEach(line => {
                    const div = document.createElement('div');
                    div.textContent = line.text;
                    div.style.top = `${line.bbox.y0}px`;
                    div.style.left = `${line.bbox.x0}px`;
                    div.style.width = `${line.bbox.x1 - line.bbox.x0}px`;
                    div.style.height = `${line.bbox.y1 - line.bbox.y0}px`;
                    div.style.fontSize = `${line.bbox.y1 - line.bbox.y0}px`;
                    div.classList.add('text-line');
                    textOverlay.appendChild(div);
                });
            });
        };
        reader.readAsDataURL(file);
    }
});
body {
    font-family: 'Arial', sans-serif;
    background-color: #f4f4f9;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #333;
}

header {
    background-color: #007BFF; /* Change to blue */
    color: white;
    padding: 20px 0;
    width: 100%;
    text-align: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    position: relative;
}

header h1 {
    margin: 0;
    font-size: 2.5em;
    font-weight: bold;
}

header::after {
    content: '';
    display: block;
    width: 50px;
    height: 4px;
    background-color: white;
    margin: 10px auto 0;
    border-radius: 2px;
}
main {
    margin: 20px;
    width: 90%;
    max-width: 800px;
    text-align: center;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

footer {
    background-color: #4CAF50;
    color: white;
    padding: 10px 0;
    width: 100%;
    text-align: center;
    position: fixed;
    bottom: 0;
}

#image-container {
    position: relative;
    display: inline-block;
    margin-top: 20px;
    border: 2px solid #ddd;
    border-radius: 5px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

#image-container img {
    max-width: 100%;
    height: auto;
    display: block;
}

.text-overlay {
    position: absolute;
    top: 0;
    left: 0;
    color: transparent;
    white-space: pre;
    font-family: monospace;
    pointer-events: none;
    overflow: hidden;
    width: 100%;
    height: 100%;
}

.text-line {
    position: absolute;
    background: rgba(255, 255, 255, 0.7);
    color: black; /* Change to black to make text visible */
    pointer-events: auto;
    white-space: pre;
    border-radius: 3px;
    padding: 2px;
    font-size: 16px; /* Adjust font size as needed */
    line-height: 1.2; /* Adjust line height as needed */
}

#uploadedImage {
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
}

#progressBar {
    width: 100%;
    height: 20px;
    border-radius: 10px;
    overflow: hidden;
    background-color: #ddd;
    margin-top: 20px;
}

#progressBar::-webkit-progress-bar {
    background-color: #ddd;
    border-radius: 10px;
}

#progressBar::-webkit-progress-value {
    background-color: #4CAF50;
    border-radius: 10px;
}

#progressBar::-moz-progress-bar {
    background-color: #4CAF50;
    border-radius: 10px;
}

.custom-file-upload {
    display: inline-block;
    padding: 10px 20px;
    cursor: pointer;
    background-color: #007BFF;
    color: white;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    transition: background-color 0.3s ease;
}

.custom-file-upload:hover {
    background-color: #0056b3;
}

.custom-file-upload:active {
    background-color: #004494;
}

#imageUpload {
    display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selectable Text Overlay</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>Selectable Text Overlay</h1>
    </header>
    <main>
        <h2>Upload an Image</h2>
        <label for="imageUpload" class="custom-file-upload">
            Choose File
        </label>
        <input type="file" id="imageUpload" accept="image/*">
        <div id="image-container">
            <img id="uploadedImage" src="">
            <div id="textOverlay" class="text-overlay"></div>
        </div>
        <progress id="progressBar" value="0" max="1" style="width: 100%; display: none;"></progress>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/tesseract.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

Guys, im trying to do a google chrome extension for the company that i work, but i’m facing lots of errors on the manifest.json

Basically my extension consists in finding phone numbers on the screen, and adding icons by the side of them. Then when you click on the icon it opens an popup.

After building with npm run build, i try to upload without packing but i receive the following error:

the error:

this is my manifest.json:

{
    "name": "Nvoip",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": ["storage", "tabs", "activeTab", "scripting"],
    "description": "Extensão criada com o intuito de realizar ligações, enviar Whatsapp e       SMS.",
    "background": {
    "service_worker": "background.js"
    },
    "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

my content.js only have a “console.log(“Chrome extension go”);”

i did a background.js to do the communication between the content.js and the script that i made, but there isn’t LOTS of content.

background.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === "numbers_found") {
      // Envia para o popup assim que ele abrir
      chrome.runtime.sendMessage(message);
    }
  });

the structure of my project:

IDK anymore what can i do to solve this problem, can anyone give-me some help?

I tried to add a ./content.js at my manifest.json, and i tried using “manifest_version”: 2, but it doesn’t work as well

Auto-generate element id / data-property from className

In my ReactJS app, I use SCSS modules and hashed class names that change with each deploy, resulting in something like this:

Header_mobileMenuToggle__6n6-W

I want to integrate a third party no-code tool that uses the elements’ className to find an element and provide user onboarding. However, when I pass the class name with the hash value, it will break after the next deploy, because no such class will exist anymore.

I can provide the third party app with any css selector so I thought I could give it the elements’ id or a data property. Thus, something like this in the built instance of my app would work:

<div className="Header_mobileMenuToggle__6n6-W" id="Header_mobileMenuToggle">...</div>

Writing the respective jsx like this in all of my code would be tedious and not worth the no-code benefit from the third party integration.

Question

Is there any way, like with some dependency / library, to assign the original class name, or the non-hashed part of the class name to the id or some data-xxx property automatically when building my app?

Server-side vs. client-side API requests: Best practices for handling multiple API calls in a web application

I’m working on a financial website with the following features:

  • A market overview section
  • News updates
  • Portfolio analysis dashboards

The application requires fetching data from multiple APIs (around 10 or more) to populate various components of the dashboard.

I’m trying to decide whether to make these API requests on the server-side or the client-side.

What are the best practices and key factors to consider in such cases? Some aspects I’m thinking about include:

  • Performance and latency
  • Security concerns (e.g., protecting API keys)
  • Scalability when dealing with high traffic
  • Frequency of data updates (real-time vs. less frequent updates)

How can I decide the optimal approach for handling API requests in this type of web application?

Unable to Resize Circle and Stretch Rectangle with Leaflet Draw’s EditControl in React-Leaflet

I’m working with react-leaflet and react-leaflet-draw to create and edit shapes on a map. I can draw circles and rectangles, but I’m experiencing two specific issues:

1. I can’t resize the circle after it’s drawn: Although the move handler works, the resize handles for the circle don’t seem to function properly.

2. I can’t stretch the rectangle while drawing it: However, after the rectangle is drawn, I can resize and move it as expected.

import {
  MapContainer,
  TileLayer,
  Marker,
  Popup,
  useMap,
  FeatureGroup,
} from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-draw/dist/leaflet.draw.css";
import L from "leaflet";
import { FullscreenControl } from "react-leaflet-fullscreen";
import "react-leaflet-fullscreen/styles.css";
const EditControl = React.lazy(async () => {
  const module = await import("react-leaflet-draw");
  return { default: module.EditControl };
});

// @ts-ignore
import icon from "leaflet/dist/images/marker-icon.png";
// @ts-ignore
import iconShadow from "leaflet/dist/images/marker-shadow.png";
let DefaultIcon = L.icon({
  iconUrl: icon,
  shadowUrl: iconShadow,
  iconAnchor: [12, 41],
});
L.Marker.prototype.options.icon = DefaultIcon;

const ChangeMapView = ({ center }) => {
  const map = useMap();
  useEffect(() => {
    map.setView(center);
  }, [center, map]);
  return null;
};

const Map = () => {
  const [sensors, setSensors] = useState([]);
  const [mapCenter, setMapCenter] = useState([0, 0]);
  const [sensorsInCircle, setSensorsInCircle] = useState([]);

  useEffect(() => {
    fetch("/sensors")
      .then((res) => res.json())
      .then((data) => {
        setSensors(data);
        if (data.length > 0) {
          const { latitude, longitude } = data[0];
          setMapCenter([latitude, longitude]);
        }
      })
      .catch((err) => console.error("Error fetching data:", err));
  }, []);

  const onShapeCreated = (e) => {
    const { layer, layerType } = e;
  
    if (layerType === "circle") {
      const radius = layer.getRadius();
      const center = layer.getLatLng();
  
      const sensorsInRange = sensors.filter((sensor) => {
        const sensorLatLng = L.latLng(sensor.latitude, sensor.longitude);
        return sensorLatLng.distanceTo(center) <= radius;
      });
  
      setSensorsInCircle(sensorsInRange);
      alert(`Sensors in circle: ${sensorsInRange.length}`);
    }
  
    if (layerType === "rectangle") {
      const bounds = layer.getBounds();
  
      const sensorsInRectangle = sensors.filter((sensor) => {
        const sensorLatLng = L.latLng(sensor.latitude, sensor.longitude);
        return bounds.contains(sensorLatLng);
      });
  
      setSensorsInCircle(sensorsInRectangle);
      alert(`Sensors in rectangle: ${sensorsInRectangle.length}`);
    }
  };
  
  return (
    // @ts-ignore
    <MapContainer center={mapCenter} zoom={10} scrollWheelZoom={true} style={{ height: "500px", width: "100%" }}
    >
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        // @ts-ignore
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      />
      <FullscreenControl position="topleft" />
      <ChangeMapView center={mapCenter} /> {/* Component to change map view */}
      <FeatureGroup>
        <React.Suspense fallback={<div>Loading...</div>}>
          <EditControl
            position="topright"
            draw={{
              polyline: false,
              circlemarker: false,
              marker: {
                icon: DefaultIcon
              },
              rectangle: {
                shapeOptions: {
                  color: '#ff7800',
                  weight: 1,
                },
              },
            }}
            onCreated={onShapeCreated}
          />
        </React.Suspense>
      </FeatureGroup>
      {sensors.map((sensor) => (
        <Marker
          key={sensor.deviceId}
          position={[sensor.latitude, sensor.longitude]}
        >
          <Popup>
            <b>Device ID:</b> {sensor.deviceId} <br />
            <b>Description:</b> {sensor.description} <br />
            <b>Dimming Level:</b> {sensor.dimmingLevel}
          </Popup>
        </Marker>
      ))}
    </MapContainer>
  );
};

export default Map;

I am using the latest versions of the required libraries, but I suspect there may be an incompatibility between leaflet-draw and react-leaflet-draw. Specifically, leaflet-draw does not seem to be correctly imported, as this part of the code is not explicitly declared and triggers an error in the server console.

How to have interactions with right mouse click as well as brush in d3

I have a scatterplot with a tooltip interaction on the points using the right mouse button. On top of it I added a 2D brush, it works perfectly, but I cannot iniziate brushing if I am on a datapoint because it will catch the event and not send it to the brush. I tried to swap the order of the components but at that point I have the other problem around, now my points never receive the mouse event.

onchange event not being triggered if input file is empty

I have this function, which asks the user for a file, and returns the File if selected, and (should) return null if nothing is selected.

async pickFile(allowed_extensions?: string[]): Promise<File | null> {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = allowed_extensions?.join(',') ?? '*';
    input.click();

    return new Promise((resolve) => {
        input.onchange = () => {
            if (input.files && input.files.length > 0) {
                resolve(input.files[0]);
            } else {
                resolve(null);
            }
        };
    });
}

If I select a file and confirm, it works normally. However, if I close the selection window, it seems the onchange event is not triggered. Is this behavior expected? If so, how could I handle it?

Reproducible example

Microsoft Kinect controller for a threejs character: bones not moving correctly

I am working on a project to control a character in threejs using a microsoft kinect.
The data for the connect is coming in correctly, The mapping for the bones is working I guess.
But when you look at the movement in the top left – that is the kinect data mapped to points displaying a skeleton – the character is not moving the same way :slight_smile:

Video: https://global.discourse-cdn.com/flex035/uploads/threejs/original/3X/9/7/97c1c8c941aa8b2b98b22602136629070a9c9008.mov

Would someone be willing to help out/collab on this or does anyone see where I have gone wrong?

All input is much appreciated!

        <!DOCTYPE html>
    <html>

    <head>
        <title>Kinect ThreeJS Controller</title>
        <style>
            body {
                margin: 0;
            }

            canvas {
                display: block;
                position: absolute;
                top: 0;
                left: 0;
            }

            #bodyCanvas {
                z-index: 1;
                pointer-events: none;
            }
        </style>
    </head>

    <body>
        <canvas id="artifactCanvas"></canvas>

        <canvas id="bodyCanvas" width="512" height="424"></canvas>

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/umd/index.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/loaders/FBXLoader.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>

        <script>
            const socket = io.connect('http://localhost:8000/');
            // Set up scene, camera, and renderer
            const windowWidth = window.innerWidth;
            const windowHeight = window.innerHeight;

            const scene = new THREE.Scene();
            const camera = new THREE.PerspectiveCamera(75, windowWidth / windowHeight, 0.1, 1000);
            const renderer = new THREE.WebGLRenderer({ canvas: artifactCanvas });
            renderer.setSize(windowWidth, windowHeight);
            //document.body.appendChild(renderer.domElement);

            // Add lights
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
            scene.add(ambientLight);
            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
            directionalLight.position.set(0, 1, 1);
            scene.add(directionalLight);

            // Set up camera position and controls
            camera.position.set(0, 100, 300);  // Adjust these values
            camera.lookAt(0, 0, 0);
            const controls = new THREE.OrbitControls(camera, renderer.domElement);

            let skeleton;

            // Load FBX model
            const fbxLoader = new THREE.FBXLoader();
            fbxLoader.load('santa.fbx', (fbx) => {
                // Try a larger scale
                //fbx.scale.setScalar(1.0);  // Adjust this value to match skeleton size
                scene.add(fbx);

                skeleton = fbx.skeleton;

                // Add skeleton helper to visualize the skeleton
                const skeletonHelper = new THREE.SkeletonHelper(fbx);
                skeletonHelper.material.linewidth = 2; // Make bones more visible
                skeletonHelper.visible = true;
                scene.add(skeletonHelper);

                // Store bone references for easier access
                const bones = {};
                const initialPositions = {};
                fbx.traverse((bone) => {
                    if (bone.isBone) {
                        const name = bone.name.toLowerCase();
                        bones[name] = bone;
                        initialPositions[name] = bone.position.clone();
                    }
                });
                // Connect to socket


                socket.on('bodyFrame', (data) => {
                    const joints = JSON.parse(data);
                    // Map Kinect joints to model bones
                    for (const jointName in joints) {
                        const joint = joints[jointName];
                        const boneName = mapJointToBone(jointName);
                        if (bones[boneName]) {
                            // Apply position relative to initial pose
                            bones[boneName].position.set(
                                initialPositions[boneName].x + joint.cameraX * 10,
                                initialPositions[boneName].y + joint.cameraY * 10,
                                initialPositions[boneName].z - joint.cameraZ
                            );
                        }
                    }
                });
            });

            // Helper function to map Kinect joint names to model bone names
            function mapJointToBone(jointName) {
                /*
                "mixamorigHead"
                "mixamorigHeadTop_End"
                "mixamorigHips"
                "mixamorigLeftArm"
                "mixamorigLeftFoot"
                "mixamorigLeftForeArm"
                "mixamorigLeftHand"
                "mixamorigLeftLeg"
                "mixamorigLeftShoulder"
                "mixamorigLeftToe_End"
                "mixamorigLeftToeBase"
                "mixamorigLeftUpLeg"
                "mixamorigNeck"
                "mixamorigRightArm"
                "mixamorigRightFoot"
                "mixamorigRightForeArm"
                "mixamorigRightHand"
                "mixamorigRightLeg"
                "mixamorigRightShoulder"
                "mixamorigRightToe_End"
                "mixamorigRightToeBase"
                "mixamorigRightUpLeg"
                "mixamorigSpine"
                "mixamorigSpine1"
                "mixamorigSpine2"
    
                */
                const mapping = {
                    0: 'mixamorigspine',
                    2: 'mixamorigneck',
                    3: 'mixamorighead',
                    4: 'mixamorigleftshoulder',
                    5: 'mixamorigleftarm',
                    6: 'mixamorigleftforearm',
                    7: 'mixamoriglefthand',
                    8: 'mixamorigrightshoulder',
                    9: 'mixamorigrightarm',
                    10: 'mixamorigrightforearm',
                    11: 'mixamorigrighthand',
                    12: 'mixamorigleftupleg',
                    13: 'mixamorigleftleg',
                    14: 'mixamoriglefttoe_end',
                    16: 'mixamorigrightupleg',
                    17: 'mixamorigrightleg',
                    18: 'mixamorigrighttoe_end'
                };
                return mapping[jointName] || jointName;
            }

            // Animation loop
            const clock = new THREE.Clock();

            function animate() {
                requestAnimationFrame(animate);
                controls.update();
                renderer.render(scene, camera);
            }

            // Handle window resize
            window.addEventListener('resize', () => {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            });

            animate();



            var canvas = document.getElementById('bodyCanvas');
            var ctx = canvas.getContext('2d');
            var colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#00ffff', '#ff00ff'];

            // handstate circle size
            var HANDSIZE = 2;

            // closed hand state color
            var HANDCLOSEDCOLOR = "red";

            // open hand state color
            var HANDOPENCOLOR = "green";

            // lasso hand state color
            var HANDLASSOCOLOR = "blue";

            function updateHandState(handState, jointPoint) {
                switch (handState) {
                    case 3:
                        drawHand(jointPoint, HANDCLOSEDCOLOR);
                        break;

                    case 2:
                        drawHand(jointPoint, HANDOPENCOLOR);
                        break;

                    case 4:
                        drawHand(jointPoint, HANDLASSOCOLOR);
                        break;
                }
            }

            function drawHand(jointPoint, handColor) {
                // draw semi transparent hand cicles
                ctx.globalAlpha = 0.75;
                ctx.beginPath();
                ctx.fillStyle = handColor;
                ctx.arc(jointPoint.depthX * 512, jointPoint.depthY * 424, HANDSIZE, 0, Math.PI * 2, true);
                ctx.fill();
                ctx.closePath();
                ctx.globalAlpha = 1;
            }



            socket.on('bodyFrame', function (bodyFrame) {
                bodyFrame = JSON.parse(bodyFrame);

                ctx.clearRect(0, 0, canvas.width, canvas.height);
                var index = 0;
                bodyFrame.forEach(function (aJoint) {

                    for (var jointType in aJoint) {
                        ctx.fillStyle = colors[index];
                        ctx.fillRect(aJoint.depthX * 512, aJoint.depthY * 424, HANDSIZE, HANDSIZE);
                    }
                    //updateElbowState(body.joints[5], body.joints[9]);
                    index++;
                });
            });

            // Add grid helper for reference
            const gridHelper = new THREE.GridHelper(1000, 100);
            scene.add(gridHelper);

        </script>

    </body>

    </html>

Working with calling remote javascript file in html [closed]

I’d like to work with an external javascript file, but i have no idea how to call it and display the data it generates.
Lets say the link is: https://vsite.com/remote/vacancy/key/e994ba67775bbfe6adcf55a2234823483e3d70e8fa87/format/js
(I changed the site and key due to privacy).

I tried the following:

<script src="https://vsite.com/remote/vacancy/key/e994ba67775bbfe6adcf55a2234823483e3d70e8fa87/format/js" </script>

But that doesnt work, it just keeps loading.

Anyone can point me in the right direction?

How Nuxt is diffrent from Vue when it comes to reactive variables?

I used Vue for years for my frontend (amateur) development and decided to give a try to Nuxt.

After going though the tutorial I thought I had a general idea and created a simple project where:

  • I would have a input on the page that sends a number to the backend,
  • which in turn responds with a an incremented number
  • which is concurrently displayed on the main page.

To this I created a new project in which I wrote a few files:

server/api/addOne.ts

export default defineEventHandler((event) => {
    const oldNumber = (getRouterParam(event, 'number') || 0) as number
    return {
        oldNumber: oldNumber,
        newNumber: oldNumber + 1,
    }
})

app.vue

<template>
  <div>
    <AddOne></AddOne>
  </div>
</template>

components/AddOne.vue

<template>
    <div>
        <input v-model="myNumber" />
        <button @click="sendToServer">send</button>
        <div> -{{ numberFromServer }}- </div>
    </div>
</template>

<script lang="ts">
const myNumber = ref(0)
const numberFromServer = ref(0)
const sendToServer = async (number: number) => {
    console.log('clicked')
    const { data, pending, error, refresh } = await useFetch('/api/addOne', {
        method: 'post',
        body: {
            number: myNumber.value
        }
    })
    numberFromServer.value = data.newNumber
    myNumber.value = -1
    console.log(`number from server: ${numberFromServer.value}`)
}
</script>

The app builds and displays what is expected:

enter image description here

The app does not work (inputting a number and pressing send doe nothing) and I get the following warnings:

 WARN  [Vue warn]: Property "myNumber" was accessed during render but is not defined on instance.
  at <AddOne>
  at <App>
  at <NuxtRoot>


 WARN  [Vue warn]: Property "numberFromServer" was accessed during render but is not defined on instance.
  at <AddOne>
  at <App>
  at <NuxtRoot>

I do not understand where they come from – myNumber and numberFromServer are defined in the component. I was already surprised that VSCode was not suggesting them when I was typing them but I thought that it was a matter of having the right plugin, maybe.

I think I am doing something fundamentally wrong,thus my question about where variables should be defined in Nuxt, versus where they are in Vue.