Make the child of a loaded gltf file transparent dynamically using THREE.JS

I’m new to Three.js but have some experience with javascript. I’m loading a gltf model with an async loader function. This all seems to function correctly. I’m them creating a series of timer events to act upon the loaded object and/or the camera. Again this seems to work well until I come to making a particular child of the loadedObject transparent. I’ve managed a partial success but would like the function to ease the child transparency not just jump the change abruptly This is the function as it stands

  loadedObject.traverse((child) => {
    if (child.material) {
      console.log('Alpha', child.name);
      if (child.name === 'Crossbars') {
        let newMaterial = child.material.clone();
        newMaterial.transparent = true;
        newMaterial.opacity = 0.1;
        child.material = newMaterial;
      }
    }
  });

But when I add a tween like this: Nothing happens. What am I doing wrong?

  loadedObject.traverse((child) => {
    if (child.material) {
      console.log('Alpha', child.name);
      if (child.name === 'Crossbars') {
        let newMaterial = child.material.clone();
        newMaterial.transparent = true;
        child.material = newMaterial;
        new TWEEN.Tween(child.material).to({ opacity: 0.1 }, 50000).start();
      }
    }
  });

useCallback on function passed to a leaf element in react?

If a component has a leaf element (like button) that takes an onClick function which is coming from a custom hook, should that onClick be wrapped in useCallback?

Folder Structure

- someComponent (folder)
  
   SomeComponent.tsx (file)

   - hooks (folder)

    useSomeComponentClick.ts
//SomeComponent

const handleClick = useSomeComponentClick();

return (
  <button onClick={handleClick} />
);

// useSomeComponentClick

const useSomeComponentClick = () => {
   const handleClick = () => {
      // do something on click
   }

   return handleClick;
}
 

Now, should be wrap handleClick in useCallback?

How to show usernames in a separate column and align them correctly with timeslots in vis.js?

I am using vis.js to create a timeline where:

The left column shows the dates.
The timeline shows the reservations for different sections.

Problems:
Usernames should be in a separate column (next to the date column).
Usernames should align correctly with their timeslots when multiple sections have the same reservation time.

function makeTimelineItems(reserveData) {
    const items = [];
    reserveData.forEach((reserve) => {
        const menus = reserve?.Menus ?? [];
        for (const menu of menus) {
            const openTime = dayjs(menu.open_time).format("HH:mm");
            let closeTime = dayjs(menu.close_time).format("HH:mm");
            if (closeTime === '00:00') {
                closeTime = '24:00';
            }
            const userName = reserve.Users ? `${reserve.Users.last_name} ${reserve.Users.first_name}` : '';

            let item = {
                id: items.length,
                group: `day_${dayjs(reserve.reservation_checkin_date).format('YYYY/M/D')}`,
                subgroup: `${reserve.Sections.id ?? ""}-${menu.id}`,
                start: StartThisMonthDate + ' ' + openTime,
                end: StartThisMonthDate + ' ' + closeTime,
                content: `<span>${openTime}~${closeTime}</span> <span style="font-weight: bold;">${menu.menu_name} ${reserve.Sections.section_name ?? ""}</span> <span style="font-weight: bold;">予約者: ${userName}</span>`
            };
            if (parseInt(reserve.proposal_status) === cancelReception) {
                item['style'] = 'border-color: lightgray; background-color: lightgray;';
            }
            items.push(item);
        }
    });

    return items;
}

function makeTimelineGroups(targetDate, reserveData) {
    const targetToday = new Date(targetDate);
    const targetFirstDate = new Date(targetToday.getFullYear(), targetToday.getMonth(), 1).getDate();
    const targetLastDate = new Date(targetToday.getFullYear(), targetToday.getMonth() + 1, 0).getDate();
    const dispItems = [];
    for (let i = targetFirstDate; i < targetLastDate + 1; i++) {
        const dateText = `${targetToday.getFullYear()}/${targetToday.getMonth() + 1}/${i}`;
        const usersForDate = reserveData
            .filter(reserve => dayjs(reserve.reservation_checkin_date).format('YYYY/M/D') === dateText)
            .map(reserve => reserve.Users) // Get the user object
            .filter(user => user) // Exclude null/undefined users
            .map(user => `${user.last_name} ${user.first_name}`); // Format user name
        
        // Join usernames with a separator (e.g., comma or line break)
        const usernameList = usersForDate.length > 0 ? usersForDate.join('<br>') : '';
        const dispItem = {
            id: DayLabel + dateText,
            content: `${dateText} <br/> ${usernameList}`,
        };
        dispItems.push(dispItem);
        
    }
    console.log(dispItems);
    return new vis.DataSet(dispItems);
}

function renderDailyTimeLine(el, reserveData, targetDate = new Date()) {
    const groups = makeTimelineGroups(targetDate,reserveData);
    const items = makeTimelineItems(reserveData);

    const beginningToday = dayjs().startOf("day").format();
    const lastToday = dayjs().endOf("day").format();

    var options = {
        zoomKey: "ctrlKey",
        stack: false,
        min: beginningToday,
        max: lastToday,
        start: beginningToday,
        end: lastToday,
        zoomMax: 86399999,
        zoomMin: 10799999,
        orientation: "top",
        format: {
            minorLabels: {
                hour: "HH:mm",
            },
        },
        groupTemplate: function (group) {
            const [date, usernameList] = group.content.split('<br/>');
            return `
            <div style="display: flex; border: 1px solid #0f0f0f;">
                <div style="width: 50%; text-align: left; padding: 5px; border-right: 1px solid #0f0f0f;">
                    ${date}
                </div>
                <div style="width: 50%; text-align: left; padding: 5px;">
                    ${usernameList}
                </div>
            </div>
            `;
        },
        showMajorLabels: false,
    };
    
    timeline = new vis.Timeline(el, items, groups,options);

    setPopoverEvent();
}

Here i am attaching current output image and expected image output.enter image description here
enter image description here

What I Need:
Show usernames in a separate column like the date column.
Align usernames correctly with their respective timeslots when multiple sections have the same reservation time.

Any suggestions on how to achieve this in vis.js?

Thanks!

Translating a entire page using a API

So i want to translate my page entirely using a api, for that i need to access the text from the page and send it to the API and then place the translated text back in place so that i can translate my page in a click, is there a simple way to do it or how to do it?

I found a API to translate but it needs a the text as input so i want to access all the text in a page.

https://apilayer.com/marketplace/language_translation-api?e=Sign+Up&l=Success

Triggering a modal dialog from inside a popover with react aria

I’ve created two components built on top of the components provided by react-aria-components:

ComboBox: renders a Popover beneath it to render the list of items, if there are no items present, the content of the Popover can be an empty state

Modal: I’ve made thin wrappers around Modal, Dialog, and ModalOverlay to apply my own styling.

The problem:
I’m creating an empty state for my ComboBox that contains a DialogTrigger with a button and a modal inside. Clicking the button should open a modal to create a new resource.

However, when the button is clicked, this traps focus in my newly created Modal. Which fires a blur event on my Combobox Popover – this causes the Popover to unmount, which then unmounts the DialogTrigger within that contains the Modal. This causes the Modal to instantly disappear.

I was wondering if anyone has an established pattern for this kind of behaviour where one react-aria Dialog triggers another? I need to some way to preserve the ComboBox’s Popover while the Modal is open.

If there is any confusion please ask for clarification – thanks in advance for any help!

Any idea how to make canvas ctx.restore() to work here?

Using HTML canvas to draw circles onto rectangle with each “touchmove” event.

Expecting to see the last circle only because using ctx.restore() and also previosly save initial canvas with the rectangle with ctx.save(), but seeing all previosly drawn circles. Do knot why ctx.restore() isn’t happening. Please see the code.

Making canvas and drawing a rectangle

  function drawInitialCanvas(x, y) {
const parent = whatEverYourParent;

if (parent.firstElementChild) {
  parent.firstElementChild.remove();
}

const canvas = document.createElement("canvas");
elemContentStep1.append(canvas);
canvas.setAttribute("id", "myCanvas");
canvas.setAttribute("width", 355);
canvas.setAttribute("height", 650);

const ctx = canvas.getContext("2d");
ctx.strokeStyle = "white";

ctx.rect(20, 500, 300, 100);
ctx.fill();
ctx.save();

crossFadeCanvasCtx = ctx;
 }

the touch listener

  function onTouchMove(e) {

const x1 = e.changedTouches[0].pageX;
const y1 = e.changedTouches[0].pageY;

drawCircle(x1, y1 - 55);
  }

draw circle

  function drawCircle(x, y) {
const ctx = crossFadeCanvasCtx;

ctx.restore();
ctx.beginPath();
ctx.arc(x, y, 30, 0, 2 * Math.PI);
ctx.stroke();
   }

Any ideas very welcome!

Can one table row have two data row in react mui?

I want to make my table look like this:

I want to make my code like this

I am able to make this but two rows are not aligned. They comes one section after another and not in same line. Here is my code. Sections is an array of object having 20 rows at each 0,1,2 indices. I am able to make header but not able to handle rows. Please let me know if you need more information.

     {sections.map((section, index) => (
                        <TableBody key={index}>
                            {section.map((row, rowIndex) => (
                                <TableRow
                                    key={rowIndex}
                                    sx={{
                                        '&:nth-of-type(odd)': {
                                            backgroundColor: 'zebra.odd',
                                        },
                                        'color': 'primary.main',
                                    }}
                                >
                                    {headers.map((header, i) => (
                                        <TableCell
                                            key={i}
                                            component='th'
                                            scope='col'
                                            align='left'
                                            sx={tableCellStyles}
                                        >
                                            <Typography
                                                sx={{
                                                    color: 'primary.main',
                                                    fontWeight: 400,
                                                    fontSize: 14,
                                                }}
                                            >
                                                {index === 0 && (row[header.toLowerCase()] ?? '')}
                                            </Typography>
                                        </TableCell>
                                    ))}
                                    {headers.map((header, i) => (
                                        <TableCell
                                            key={i}
                                            component='th'
                                            scope='row'
                                            align='left'
                                            sx={tableCellStyles}
                                        >
                                            <Typography
                                                sx={{
                                                    color: 'primary.main',
                                                    fontWeight: 400,
                                                    fontSize: 14,
                                                }}
                                            >
                                                {index === 1 && (row[header.toLowerCase()] ?? '')}
                                            </Typography>
                                        </TableCell>
                                    ))}
                                    {headers.map((header, i) => (
                                        <TableCell
                                            key={i}
                                            component='th'
                                            scope='col'
                                            align='left'
                                            sx={tableCellStyles}
                                        >
                                            <Typography
                                                sx={{
                                                    color: 'primary.main',
                                                    fontWeight: 400,
                                                    fontSize: 14,
                                                }}
                                            >
                                                {index === 2 && (row[header.toLowerCase()] ?? '')}
                                            </Typography>
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))}
                        </TableBody>
                    ))}

Import JSDOC type annotations from a JavaScript npm package

I have an npm package for NodeJS that is implemented in (plain and not compiled) JavaScript and uses JSDOC type annotations to type check the code using TypeScript and this works like a charm.
When using the above package in another project by adding it as a dependency, it seems as if TypeScript would no longer use the JSDOC type annotation in the source of the package but rather demands a declaration file.

re Count visible rows in html table [closed]

The answer given by Philipp Sengelmann on stackoverflow (Feb 17, 2023) works well, with the html table provided. This contains 4 rows:

A   A   A
B   B   B
B   B   B
C   C   C

and gives a row count of 1 if “A” is selected, 2 for “B”. If I change the fourth row to:

X   Y   Z

I would expect a count of 1 whichever column is chosen. Instead, I only get a result for “Y”, the others giving zero.

Can anyone explain this strange behaviour?

Robot Framework : Wait JS events to be applied

I have Robot Framework tests that are automated in a Gitlab pipeline in a Docker environment (Apache + Robot Framework runs entirely on the Gitlab runner)

The problem is that regularly, tests fail because JS events are not yet fully applied when clicking a button.
RF is faster than the browser and clicks the button before the JS has time to be fully executed.

I can’t modify the application to apply the events as soon as possible, and in any case some are in external libraries.

I tried everything, nothing to do. I despair of being able to make these tests reliable.

Here is the code to reproduce the behavior, the setTimeout allows to simulate a certain delay in the execution of the JS.

<!doctype html>
<html lang=en>
<head>
    <meta charset=utf-8>
    <title>blah</title>
    <script src="jquery.js"></script>
</head>
<body>

<button id="button1">Click me 1</button>
<button id="button2">Click me 2</button>
<p id="result"></p>

<script>
    $(document).ready(function(){
        $('#button1').click(function() {
            setTimeout(function(){
                $('#button2').click(function() {
                    $('#result').text('Button 2 clicked');
                });
            }, 500)
        });
    });
</script>

</body>
</html>

And here is an example of RF test suite to reproduce the issue. I added a bunch of identical test cases and ran them in parallel with Pabot. It gives me random failures.

*** Settings ***

Library    SeleniumLibrary

*** Test Cases ***

test 0
    test click button with timeout
test 2
    test click button with timeout
test 3
    test click button with timeout
# .....

*** Keywords ***

test click button with timeout
    Open Browser    about:blank    headlessfirefox
    Go To    http://myapp-apache-1/test.html

    Click Element    id=button1
    Click Element    id=button2

    Wait Until Element Is Visible   //*[text()[contains(normalize-space(), "Button 2 clicked")]]

Any ideas? or I should resort to putting Sleep everywhere…

I’ve tried a bunch of various waiting solutions found here and elsewhere, but haven’t found anything that works.

Is there any way to select a mixture of multiple files and folders at once?

In the given code, at a time I can select multiple files or folders using javascript,

  1. Selecting multiple files
    <input type="file" id="filePicker1” multiple>

  2. Selecting folders, multiple folder selection not working. At a time one folder I can select
    <input type="file" id="filePicker2” multiple webkitdirectory mozdirectory>

I want like selecting mixture of multiple files and folders at once.

Can anyone please help me with the above.

I tried default method of file picker in javascript. In that unable to select files and folders together in a single operation.

How to pass more than one params when navigating to another screen?

I am still learning React Native and I am stuck with navigating to a screen with some params. I know that to pass a param to another screen we can do it like this:

/item/[id].jsx

const ItemDetailsScreen = () => {
    const { id } = useLocalSearchParams();
    return (
        <View ...>
             ...
        </View>
    );
};

And in the previous screen we just call: router.push(``/item/${id}``)

Now, what if I need to pass two params: id and name?

Thank you.

SCORM package not loading correctly in LMS (JS displayed as text)

I’m encountering an issue where a SCORM package is not loading correctly in our e-learning platform. Instead of executing JavaScript, the code is displayed as plain text on the screen. This happens on both Google Chrome and Microsoft Edge (latest versions).

What I have checked so far :

Tried in Incognito mode → Same issue.

Checked the browser console (F12) → No blocking errors, but the SCORM JS files are not executing.

Checked network requests (F12 → Network tab) → No 404 or 403 errors on SCORM-related files.

Verified SCORM package upload → The package was correctly imported into the LMS.

Tried another SCORM package → It works fine, so the problem seems related to this specific SCORM file.

Cleared cache and disabled browser extensions → No effect.

Here is a screenshot of the issue: Instead of executing JavaScript, the SCORM package displays the script as plain text.

enter image description here

Vite “spawn EPERM” Error When Running npm run dev on Windows

PS C:UsersadilrDesktopMega> npm run dev

[email protected] dev
vite

failed to load config from C:UsersadilrDesktopMegavite.config.js
error when starting dev server:
Error: spawn EPERM
at ChildProcess.spawn (node:internal/child_process:420:11)
at Object.spawn (node:child_process:753:9)
at ensureServiceIsRunning (C:UsersadilrDesktopMeganode_modulesesbuildlibmain.js:1975:29)
at build (C:UsersadilrDesktopMeganode_modulesesbuildlibmain.js:1873:26)
at bundleConfigFile (file:///C:/Users/adilr/Desktop/Mega/node_modules/vite/dist/node/chunks/dep-CHZK6zbr.js:66736:24)
at loadConfigFromFile (file:///C:/Users/adilr/Desktop/Mega/node_modules/vite/dist/node/chunks/dep-CHZK6zbr.js:66706:27)
at resolveConfig (file:///C:/Users/adilr/Desktop/Mega/node_modules/vite/dist/node/chunks/dep-CHZK6zbr.js:66307:30)
at _createServer (file:///C:/Users/adilr/Desktop/Mega/node_modules/vite/dist/node/chunks/dep-CHZK6zbr.js:62908:24)
at createServer (file:///C:/Users/adilr/Desktop/Mega/node_modules/vite/dist/node/chunks/dep-CHZK6zbr.js:62905:10)
at CAC. (file:///C:/Users/adilr/Desktop/Mega/node_modules/vite/dist/node/cli.js:736:26)

How force Fabric.js polygon to update his points correctly after modify

I’m using the latest version of Fabric.js, and I have a problem with a polygon. As we know, in Fabric.js, the points field of a polygon doesn’t update after modification (it always contains the initial points).

I want to recalculate the polygon’s points after modification to get the current position of each point. To achieve this, I use the trick with calcTransformMatrix (the points are calculated correctly), and then I assign the new points to the existing polygon.

The problem occurs when I try to scale or rotate a polygon with updated points—this leads to crashes and bugs, and I don’t know why.

Here is my code:

const canvas = new fabric.Canvas("canvas", {
  width: 600,
  height: 600,
  backgroundColor: "lightgray",
});

const polygonPoints = [
  { x: 100, y: 50 },
  { x: 200, y: 80 },
  { x: 250, y: 200 },
  { x: 150, y: 300 },
  { x: 50, y: 200 },
];

const polygon = new fabric.Polygon(polygonPoints, {
  fill: "rgba(0, 128, 255, 0.5)",
  stroke: "blue",
  strokeWidth: 2,
  selectable: true,
});

canvas.add(polygon);

// On modified
polygon.on("modified", (o) => {
  // Calculate new points
  const newPoints = polygon
    .get("points")
    .map(
      (p) =>
        new fabric.Point(p.x - polygon.pathOffset.x, p.y - polygon.pathOffset.y)
    )
    .map((p) => p.transform(polygon.calcTransformMatrix()));

  polygon.set({ points: newPoints });
  polygon.setBoundingBox(true);
  canvas.requestRenderAll();

  // Now after recalculate points it work fine when drag but scale/rotate dont work correctly
  polygon.points.forEach((e) => {
    canvas.add(
      new fabric.Rect({
        left: e.x,
        top: e.y,
        width: 5,
        height: 5,
        fill: "red",
      })
    );
  });
});

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fabric js</title>

    <script src="https://cdn.jsdelivr.net/npm/fabric@latest/dist/index.min.js"></script>
  </head>
  <body>
    <canvas id="canvas" width="600" height="600"></canvas>
    <script src="main.js"></script>
  </body>
</html>

After dragging, when we try to scale or rotate, we can see weird behavior.

I expect that after updating the points, rotating or scaling should not break the polygon.
Here is demo code:

https://codesandbox.io/p/devbox/vibrant-kowalevski-v8vkjk?workspaceId=ws_JP9WoSuC2iw5iMuNawSDEv

If you try scale/rotate after drag (so after update points) you will see crashes.

Before drag (before points update):
enter image description here
After drag & scale/rotate or just scale/rotate:
enter image description here