PrimeNG menu not opening when button is clicked

I have a button on my website which is meant to open a PrimeNG popup menu when clicked. I plan to change the design of only that button later. However, nothing happens when I click it.

The menu shows up without the button.

Why is this?

app.component.html

<div class = "background">
    <div id = pLogo>
      <img src = "../assets/petronas-logo-dark.svg" width="30%" height="30%" alt="Petronas">
    </div>
    <div id = BurgerMenu>
      <p-menu #menu [model]="items" [popup]="true" />
      <p-button (onClick)="menu.toggle($event)" icon="pi pi-ellipsis-v"/>
    </div>
</div>

app.component.ts

:host ::ng-deep .p-button { 
    background-color: #00a19c;
    border-color: #00a19c;
    font-family: "Museo Sans 900", Arial, sans-serif !important;
    font-size: 1.5vw;
}

:host ::ng-deep .p-button:hover { 
    background-color: #00928d;
    border-color: #00928d;
    font-family: "Museo Sans 900", Arial, sans-serif !important;
    font-size: 1.5vw;
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ButtonModule } from 'primeng/button';
import { DividerModule } from 'primeng/divider';
import { RippleModule } from 'primeng/ripple';
import { CommonModule } from '@angular/common';
import { MenuModule } from 'primeng/menu';
import { ToastModule } from 'primeng/toast';
import { trigger, state, style, animate, transition } from '@angular/animations';
import { MenuItem, MessageService } from 'primeng/api';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, ButtonModule, DividerModule, RippleModule, CommonModule, MenuModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})

export class AppComponent implements OnInit{
  title = 'login_app';
  LoadingStatus = true
  items!: MenuItem[];

  ngOnInit(): void {
    setTimeout(() => {
        this.LoadingStatus = false;  // Remove the loading screen after the animation
      }, 2000);
    this.items = [
            {
                label: 'Options',
                items: [
                    {
                        label: 'Refresh',
                        icon: 'pi pi-refresh'
                    },
                    {
                        label: 'Export',
                        icon: 'pi pi-upload'
                    }
                ]
            }
        ];  
    }
  }

Thank you!

To integrate javascript within Mailchimp HTML Builder

I want to embed gamification code from dot.vu, which is in javascript into Mailchimp HTML builder. But based on my reading, Mailchimp HTML builder cannot support javascript. I tried to embed it and send a test email. As a result, the javascript part didnt appear on the send email. Need assistance on this issue.

Need assistance on how I can embed the gamification link so that it’ll appear within the marketing email being send from Mailchimp

Threejs – Texuture Image Missing when I leave app tab

I’m working on creating a 3d Map mesh which contains a plane geometry and MeshPongMaterial on threejs.
This Material takes two texture images: one for displacementMap(WEBP for DEM) and another for MAP(WEBP).

Here’s the problem.
Whenever I move to other tab(I’m using Chrome Broswer) and do some actions, the Map image loaded with THREE.TextureLoader disappears or gets distored when i get back to current tab.

the missing texture
the yellow plane is the mesh placed right under the map Mesh.

what it was & what should be
Only the Map mesh’s texture missing or distorted i guessed (the brown-white plane is map-mesh)

I want to know what would be the main problem or Cause for this.
thanks for Read This.

I tried updating material and mesh when i re-focused on tab with EventListener ‘focus’.

  • Plus, I am trying to avoid using reload code everytime I return to current tab.

Web Speech Api not-allowed no voice acting

For some reason, the voice acting of the text stops happening to me. The logic is as follows – tasks are automatically created on my server according to time and data about tasks is transmitted over sockets, and at the moment when the time for the task approaches (and 5 minutes before the time) voice acting occurs. However, for some reason a not-allowed error occurred. What could be the reason? Moreover, I noticed that this happens on tasks when there is a long period of time between voiceovers. How can I fix it?

This is what my code currently looks like

voice(text) {
      const utterance = new SpeechSynthesisUtterance(text);


  utterance.onend = () => {
    const timestamp = new Date();
    console.log(`Pronunciation complete ${text} time: ${timestamp}`);
    this.$store.dispatch('saveCurNumberVoiceToLocalStorage', { text, timestamp });
  };

  utterance.onerror = (event) => {
    console.error('Pronunciation error:', event.error);
    const timestamp = new Date();
    this.$store.dispatch('logSpeechSynthesisError', { text, timestamp, error: event.error });
  };

  speechSynthesis.speak(utterance);
},

Unexpected behavior of setTimeout/setInterval when tab is inactive [duplicate]

I’ve implemented a user activity tracking and countdown timer in React using setTimeout and setInterval. Everything works fine when the browser tab is active, but I’m facing issues when the tab is inactive or the browser window is minimized.

The Problem

The timers are supposed to track user inactivity and start a countdown that eventually logs the user out. When I stay on the same tab, the logic works perfectly. However, if I switch to another tab or minimize the browser, the timers seem to slow down or pause, and they don’t resume correctly when I return to the tab. For example, a countdown that should have finished while the tab was inactive instead starts only when I come back to the tab.

Example code

export const useActivityTimer = ({
  inactivityTimeout,
}: useActivityTrackerProps) => {
  const [isUserInactive, setIsUserInactive] = useState(false)
  const [isTimerClear, setIsTimerClear] = useState(false)
  const inactivityTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const resetInactivityTimerRef = useRef<() => void>()

  const resetInactivityTimer = useCallback(() => {
...
    inactivityTimerRef.current = setTimeout(() => {
      setIsUserInactive(true)
    }, inactivityTimeout * ONE_SECOND_IN_MS)
  }, [inactivityTimeout, isTimerClear, isUserInactive])

  const clearActivityTimer = useCallback(() => {
    setIsTimerClear(true)
    if (inactivityTimerRef.current) {
      clearTimeout(inactivityTimerRef.current)
    }
  }, [])

  const handleActivity = useCallback(() => {
    if (resetInactivityTimerRef.current) {
      resetInactivityTimerRef.current()
    }
  }, [])

  const addEventListeners = useCallback(() => {
    document.addEventListener('click', handleActivity)
    document.addEventListener('mousemove', handleActivity)
    document.addEventListener('keydown', handleActivity)
  }, [handleActivity])

  const removeEventListeners = useCallback(() => {
    document.removeEventListener('click', handleActivity)
    document.removeEventListener('mousemove', handleActivity)
    document.removeEventListener('keydown', handleActivity)
  }, [handleActivity])

  useEffect(() => {
    resetInactivityTimerRef.current = resetInactivityTimer
    resetInactivityTimerRef.current()
  }, [resetInactivityTimer])

  useEffect(() => {
...
  }, [addEventListeners, inactivityTimeout, removeEventListeners])

  return {
...
  }
}

export const useCountdownTimer = ({
  countdownTime,
}: useCountdownTimerProps) => {
  const [countdown, setCountdown] = useState(countdownTime)
  const [isTimeout, setIsTimeout] = useState(false)
  const countdownTimerRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const clearCountdownTimer = useCallback(() => {
...
  }, [])

  const handleTimeout = useCallback(() => {
...
  }, [clearCountdownTimer])

  const startCountdown = useCallback(() => {
    setCountdown(countdownTime)
    countdownTimerRef.current = setInterval(() => {
      setCountdown((prev) => {
        if (prev === 0) {
          handleTimeout()
          return 0
        }
        return prev - 1
      })
    }, ONE_SECOND_IN_MS)
  }, [countdownTime, handleTimeout])

  return {
...
  }
}

Question

Why do setTimeout and setInterval behave differently when the tab is inactive? How can I ensure that the timers work consistently, even when the user is not on the active tab or when the browser is minimized?

Newbie Help: Syntax error: SyntaxError: Unexpected identifier (JavaScript)

Armature coder here. I may be doing something simple wrong here but I’m basically wanting to have a Boolean determine what action is to be taken in a function that gets called later. While there is missing items such as cropped and croppedNmb don’t worry as these are pre-defined in the whole script. Specifically I am using .gs but .gs is a JavaScript-Based coding format thingy.

Again, I’m super new so it could be a simple solution such as incorrect formatting.

function getFormat(format = String, textOrNumber = Boolean) { //0 = get text 1 = get number
  if textOrNumber = 0 {
    return cropped;
  }
  else if textOrNumber = 1 {
    croppedNmb = formattedValue.replace(cropped, '')
    return croppedNmb
  }
}

This would then be called later. For example, this is the test I’m using to see if the above function works (which it doesn’t currently)

Logger.log(getFormat(currentRange, 1) + getFormat(currentRange, 0));

Auth0 iFrame login works on Firefox, but not on Chrome/Safari

Our web app uses Auth0 as an authentication provider. Typically, this works great. Recently we’re running into an issue where when the login flow is run through an iFrame (embedded in Shopify) we receive an error and the login fails. The weird part is that the flow works consistently in Firefox, but not in Chrome or Safari. Originally it wasn’t working at all, but switching to classic login and changing settings for cross-origin authentication and clickjacking protection fixed the issue.

These are the console errors we’re receiving. The first is Safari (fails to login), then Firefox (success).

Help!!

Firefox 1 Firefox 2 Firefox 3 Safari

Adding allowed origins, classic login, multiple browsers. Problem occurs only in browsers other than Firefox.

React Chart Not Updating When apiData Remains the Same

I’m working on a React component that displays a line chart using react-chartjs-2. The chart should update whenever new data (apiData) is received from an API. The issue I’m facing is that if the new apiData value is the same as the previous one, the chart does not update or re-render.

Here’s the relevant part of my component:

import React, { useState, useContext, useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import { DataContext } from '../../context/DataContext';
import 'chart.js/auto';
import styled from 'styled-components';

const MAX_DATA_POINTS = 100;

const Container = styled.div`
    width: 99%;
    height: 100%;
`;

const Graph = ({ apiData, graphLabel }) => {
    const { streaming, clearFlag, setClearFlag } = useContext(DataContext);

    const [graphData, setGraphData] = useState(() => {
        const storedData = sessionStorage.getItem('graphData');
        return storedData ? JSON.parse(storedData) : [];
    });

    const [key, setKey] = useState(0); // new state to track re-renders

    useEffect(() => {
        if (streaming) {
            setGraphData(prevData => {
                const newData = [
                    ...prevData,
                    { time: new Date().toLocaleTimeString(), data: apiData }
                ];
                // Limit the number of data points to preserve interval
                if(newData.length > MAX_DATA_POINTS){
                    newData.shift();
                }

                sessionStorage.setItem('graphData', JSON.stringify(newData));
                setKey(prevKey => prevKey + 1); // trigger re-render
                return [...newData]; // return new array to trigger re-render 
            });
        }
    }, [apiData, streaming]);

    const dataPoints = {
        labels: graphData.map(d => d.time),
        datasets: [
            {
                label: graphLabel,
                data: graphData.map(d => d.data),
                fill: false,
                backgroundColor: '#F3F4F6',
                borderColor: '#0077C8',
            },
        ],
    };

    useEffect(() => {
        if (clearFlag) {
            setGraphData([]);
            sessionStorage.removeItem('graphData');
            setClearFlag(false);
        }
    }, [clearFlag])

    const options = {
        scales: {
            y: {
                beginAtZero: true,
                max: 1000,
            },
        },
        maintainAspectRatio: false,
        animation: {
            duration: 0,
        },
        plugins: {
            legend: {
                labels: {
                    font: {
                        size: 18,
                        weight: 'bold',
                    },
                    color: 'black'
                }
            }
        }
    };

    return (
        <Container>
            <Line data={dataPoints} options={options} />
        </Container>
    );
};

export default Graph;

Threejs Raycaster intersections not updated immediately when adding to scene but when removing

I am trying to build a minecraft clone in threejs currently.

I have a very basic setup right now where I have added some cubes to a scene and a Raycaster, that checks if the Pointer is over any of the cubes in the scene and if so creating an indicator cube for removing/adding a cube.

When in Removal mode, the cube the pointer is over shall be highlighted in red and when clicked, remove that cube. Immediately after that, the Raycaster is called again, to check if the Pointer is now hovering over any cubes that were behind the one that has been removed and then indicate in red the next cube so on and so forth.

That is working great so far.

Now I have added the option to add cubes on click. When the pointer is hovering over a cube, the indicator shall now be placed next to the face of the cube where the pointer is hovering over, to indicate where the new cube would be placed. This is also working.

Here comes the point that is not working:
When clicking to add the new cube, the Raycaster is called again. But differently to when I removed the cube, the Raycaster is not recognizing the new intersection with the newly created cube, thus not updating the position of the indicator immediately.

Only after moving the mouse by at least one pixel, the raycaster is recognizing the new cube and updating the indicator.

I have created a minimal Threejs file. Pressing 1 brings you into Add Mode and pressing 2 into Removal Mode.

import * as THREE from 'three'

// Setup scene
const scene = new THREE.Scene()
const renderer = new THREE.WebGLRenderer({ antialias: true })

renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000)
const cameraDistance = 6
camera.position.set(cameraDistance, 4, cameraDistance)
camera.lookAt(new THREE.Vector3(0, 0, 0))

// Add example cubes
const cube = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 'gray', wireframe: false })
const mesh1 = new THREE.Mesh(cube, material)
const mesh2 = new THREE.Mesh(cube, material)
mesh2.position.set(1, 0, 0)
const mesh3 = new THREE.Mesh(cube, material)
mesh3.position.set(0, 1, 0)

const cubes = [mesh1, mesh2, mesh3]
scene.add(mesh1)
scene.add(mesh2)
scene.add(mesh3)

// Create indicator mesh that shows where the next cube will be placed/removed
const indicatorGeo = new THREE.BoxGeometry(1.01, 1.01, 1.01)
const indicatorMaterial = new THREE.MeshBasicMaterial({
  color: 'red',
  opacity: 0.2,
  transparent: true,
  wireframe: false,
})
const indicatorMesh = new THREE.Mesh(indicatorGeo, indicatorMaterial)
indicatorMesh.name = 'indicatorMesh'
indicatorMesh.position.set(0.5, 0.5, 0.5)
indicatorMesh.visible = false
scene.add(indicatorMesh)

let raycaster = new THREE.Raycaster()
let pointer = new THREE.Vector2()

// Mode can be changed by pressing 1 or 2
let MODE = 'remove'

// This is called on every pointermove event, and explicitly when a cube is added or removed
function checkIntersection() {
  pointer.set((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1)

  raycaster.setFromCamera(pointer, camera)

  let intersects = raycaster.intersectObjects(cubes, true)

  if (intersects.length > 0) {
    const intersect = intersects[0]
    indicatorMesh.position.copy(intersect.object.position)
    if (MODE === 'add') {
      indicatorMesh.position.add(intersect.face.normal)
    }
    indicatorMesh.visible = true
  } else {
    indicatorMesh.visible = false
  }
}

document.addEventListener('pointermove', checkIntersection)
document.addEventListener('pointerdown', (event) => {
  pointer.set((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1)

  raycaster.setFromCamera(pointer, camera)

  let intersects = raycaster.intersectObjects(cubes, true)

  if (intersects.length > 0) {
    const intersect = intersects[0]

    if (MODE === 'remove') {
      cubes.splice(cubes.indexOf(intersect.object), 1)
      scene.remove(intersect.object)
    } else if (MODE === 'add') {
      const voxel = new THREE.Mesh(
        new THREE.BoxGeometry(1, 1, 1),
        new THREE.MeshBasicMaterial({ color: 'gray', wireframe: false }),
      )
      voxel.position.copy(intersect.object.position).add(intersect.face.normal)
      cubes.push(voxel)
      scene.add(voxel)
    }

    checkIntersection()
  }
})
document.addEventListener('keydown', (event) => {
  switch (event.key) {
    case '1':
      MODE = 'add'
      checkIntersection(event)
      break
    case '2':
      MODE = 'remove'
      checkIntersection(event)
      break
  }
})

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

animate()

I will also add videos of what is happening when removing and adding. Note how the red indicator is immediately updated when clicking (You can try this out yourself) in Removal Mode, but only updating once the pointer is moved in Add Mode

I tried calling the checkIntersection function on the pointerup event, as a workaround, which does work, but it not what I am intending to do.

I also tried logging the intersections array, which confirms my suspicion, that the new object is not being recognized by the raycaster. I also tried adding the new cube manually to the intersections object but that didn’t help.

I am doubly confused why everything works as expected when in Removal Mode but I assume it could be, because the object is immediately removed from the scene?

What am I missing. I assume this must be possible but I am missing something here.

adding properly text gradient to my svg component

I’m trying to add the gradient on text for my svg image.

Here’s my svg image:

svg img

i’ve uploaded here in png format
That’s the way I’m trying to do that:

export const HawllIcon: React.FC<IconSvgProps> = ({
  size = 100,
  width,
  height,
  ...props
}: IconSvgProps) => (
  <svg
    height={size || height}
    preserveAspectRatio="xMidYMid meet"
    version="1.0"
    viewBox="0 0 800 500"
    width={size || width}
    {...props}
    xmlns="http://www.w3.org/2000/svg"
  >
    <defs>
      <linearGradient id="MyGradient" x1="0%" x2="100%" y1="0%" y2="100%">
        <stop offset="5%" stopColor="#ff9459" />
        <stop offset="95%" stopColor="#006fee" />
      </linearGradient>
    </defs>
    <g
      fill="url(#MyGradient)"
      stroke="none"
      transform="translate(0,500) scale(0.1,-0.1)"
    >
      <path
        d="M140 2490 l0 -700 195 0 195 0 0 275 0 275 275 0 275 0 0 -275 0
  -275 195 0 195 0 0 700 0 700 -195 0 -195 0 0 -260 0 -260 -275 0 -275 0 0
260 0 260 -195 0 -195 0 0 -700z"
      />
      <path
        d="M2181 3148 c-10 -24 -141 -320 -291 -658 -150 -338 -281 -634 -291
  -658 l-18 -42 201 2 201 3 203 505 203 505 16 -40 c9 -22 101 -249 204 -505
l187 -465 203 -3 c191 -2 203 -1 197 15 -4 10 -143 325 -309 700 l-302 683
-193 0 -193 0 -18 -42z"
      />
      <path
        d="M3133 3183 c3 -5 73 -219 157 -478 83 -258 155 -473 158 -477 4 -4
54 119 111 273 l104 281 -64 204 -63 204 -204 0 c-112 0 -201 -3 -199 -7z"
      />
      <path
        d="M3883 2490 l-231 -700 176 0 177 0 139 425 c77 234 143 421 146 415
4 -6 31 -89 61 -185 29 -96 57 -171 60 -167 3 4 48 121 98 261 l92 254 -62
198 -62 199 -181 0 -181 -1 -232 -699z"
      />
      <path
        d="M5055 3178 c-3 -7 -70 -215 -150 -463 -80 -247 -180 -553 -221 -680
  -40 -126 -74 -233 -74 -237 0 -4 82 -8 183 -8 l183 0 222 685 c122 376 225
691 228 700 5 13 -16 15 -180 15 -140 0 -188 -3 -191 -12z"
      />
      <path
        d="M5580 2490 l0 -700 530 0 530 0 0 155 0 155 -335 0 -335 0 0 545 0
545 -195 0 -195 0 0 -700z"
      />
      <path
        d="M6800 2490 l0 -700 530 0 530 0 0 155 0 155 -335 0 -335 0 0 545 0
545 -195 0 -195 0 0 -700z"
      />
    </g>
  </svg>
);

But I’m only achieving this:

enter image description here

And I’m trying to achieve that:

enter image description here

What do I need to do to get things done?

I’ve tried to:

  • change fill to almost every variation of this gradient,
  • change the gradientUnits both ways: objectBoundingBox & userSpaceOnUse and none of them does the thing correctly.

getAllShipment Function Not Fetching Data from Smart Contract Properly

I’m encountering an issue with my getAllShipment function in my JavaScript code. The function is intended to fetch and map shipment data from a smart contract. However, I’m seeing that only the first two console.log statements (1 and 2) are printed, and the third statement (3) isn’t reached.

const getAllShipment = async () => {
    try {
        console.log("1")
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        const contract = new ethers.Contract(ContractAddress, ContractABI, signer)
        
        console.log("2")
        const shipments = await contract.getAllTransactions()
        console.log(shipments)
        console.log("3")
        const allShipments = shipments.map((shipment) => ({
            sender: shipment.sender,
            receiver: shipment.receiver,
            price: ethers.utils.formatEther(shipment.price.toString()),
            pickupTime: shipment.pickupTime.toNumber(),
            deliveryTime: shipment.deliveryTime.toNumber(),
            distance: shipment.distance.toNumber(),
            isPaid: shipment.isPaid,
            status: shipment.status,
        }));

        return allShipments;
    } catch (error) {
        console.log("Something went wrong", error);
    }
}

Details:

  1. Contract Address and ABI: The ContractAddress and ContractABI are correctly defined and used.
  2. Function getAllTransactions: The function getAllTransactions is expected to return an array of shipment objects.
  3. Error Handling: The catch block is in place to catch any errors, but no specific errors are logged.

Could you help me diagnose why the code isn’t reaching the third console.log statement and how I might resolve this issue? I’ll provide the contract and full JavaScript code if needed.

Electron and React app experiences refresh-like effect during IPC database operations

I’m developing a desktop application using Electron and React, and I’m encountering an issue where performing write operations to a SQLite database via IPC causes a refresh-like effect in the UI. This happens without the page actually reloading.

Here’s a summary of the relevant code:

Electron Main Process:

ipcMain.handle("addManufacture", async (event, name) => {
  const manufacturer = await models.Manufacturer.create({ name });
  return manufacturer;
});

React Component:

const handleAddManufacturer = () => {
  window.electron
    .addManufacture(newManufacturerName)
    .then((manufacturer) => {
      setManufacturers([...manufacturers, manufacturer]);
      setNewManufacturerName("");
      onClose();
    })
    .catch((error) => {
      console.error(error);
    });
};

The refresh-like effect occurs right after the IPC call. There are no navigation or window reload commands in any part of the code that is being executed. I’ve confirmed that no unnecessary re-renders or state updates are causing this effect. How can I diagnose and resolve this issue?

My package.json file:

{
  "name": "parts-app",
  "version": "0.1.0",
  "private": true,
  "main": "public/electron.js",
  "homepage": ".",
  "dependencies": {
    "@chakra-ui/react": "^2.8.2",
    "@emotion/react": "^11.13.0",
    "@emotion/styled": "^11.13.0",
    "@reduxjs/toolkit": "^2.2.6",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "assert": "^2.1.0",
    "axios": "^1.7.2",
    "browserify-zlib": "^0.2.0",
    "crypto-browserify": "^3.12.0",
    "electron-is-dev": "^3.0.1",
    "framer-motion": "^11.3.19",
    "path-browserify": "^1.0.1",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-icons": "^5.2.1",
    "react-redux": "^9.1.2",
    "react-router-dom": "^6.25.1",
    "react-scripts": "5.0.1",
    "redux-persist": "^6.0.0",
    "sequelize": "^6.37.3",
    "sqlite3": "^5.1.7",
    "stream-browserify": "^3.0.0",
    "url": "^0.11.4",
    "util": "^0.12.5",
    "uuid": "^10.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "concurrently "npm run start-react" "npm run start-electron"",
    "start-react": "react-scripts start",
    "start-electron": "wait-on http://localhost:3000 && electron .",
    "build": "react-scripts build && electron-builder",
    "postinstall": "electron-builder install-app-deps",
    "react-build": "react-scripts build",
    "react-test": "react-scripts test"
  },
  "build": {
    "appId": "com.parts-app",
    "mac": {
      "category": "public.app-category.productivity"
    },
    "win": {
      "target": [
        "nsis",
        "portable"
      ]
    },
    "files": [
      "build/**/*",
      "public/electron.js"
    ],
    "directories": {
      "buildResources": "assets"
    }
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/preset-env": "^7.24.8",
    "@babel/preset-react": "^7.24.7",
    "concurrently": "^8.2.2",
    "electron": "^31.3.0",
    "electron-builder": "^24.13.3",
    "wait-on": "^7.2.0"
  }
}

Currently as i can’t able to add database with squilize orm in react so I add database, services in public folder where my electron.js file exists so i am communicating database operation with react using ipc main renderer. But don’t know when i get data from database there is no auto refresh app but when i add/update/delete then it refreshes the app.

Using JavaScript to take a screenshot of a browser’s actual display

I’ve seen many examples of using canvas or the html2canvas library, but this method takes a screenshot of a certain element instead of what is actually being displayed in the browser. For example, in this example, https://codepen.io/GDur/pen/eYBLeLM, even if I set the video as opacity: 0 to hide it from being displayed on the webpage, screenshot of the video can still be taken.

How can I take a screenshot of, say, a <div>, of what is actually being displayed at the moment?

React button refuses to activate function properly onClick

I am trying to set up a React component that includes two text input boxes and a button. When I click on the button, I would like for it to make a post request to the backend. However, either the text boxes activate the function, or the function refuses to activate.

Originally, typing in the boxes would activate the onClick event, and I could get onLogin({username, password}) to fire. In an attempt to get this to stop happening when I typed in the boxes and instead to happen when I clicked the button, I tried to make a click handler function, buttonClickHandler, in my Login() function. Now, clicking on the button doesn’t activate the buttonClickHandler function nor the onLogin() function. While I am new to React and JavaScript and I understand that I may be using the wrong forms of functions (still heavily confused), I was wondering if there’s a deeper structural issue with the way I have my functions set up. Thanks!

import React from 'react';
import './Login.css';
import Button from './button';
import {useState} from 'react';
import axios from 'axios';
import { render } from '@testing-library/react';

function TestToken({token}) {
    axios.get('http://localhost:8000/login/test_token', {
        headers: {
            Authorization: 'Token ' + token
        }
    }).then(response => {
        console.log(response.data);
        return(true);
    }).catch(error => {
        console.log(error + ", token authentication failed!");
        return(false);
    });
};

function OnLogin({username, password}) {
    alert("BUTTON CLICKED RAHHHH");
    const [token, setToken] = useState("");

    axios.post('http://localhost:8000/login',
        {
            username: {username},
            password: {password}
        }
    ).then(response => {
        setToken(response.data.token)
        console.log(response.data.user)
    }).catch(error => {console.log(error)});

    if(TestToken(token)) {
        console.log("Logged in!");
    } else {
        console.log("Log in failed!");
    };

    return(console.log("OnLogin function concluded!"));

};


export function Login() {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");

    function getUser(event) {
        setUsername(event.target.value);
    }

    function getPassword(event) {
        setPassword(event.target.value);
    }

    const buttonClickHandler = () => {
        console.log("Handle activated");
        OnLogin({username, password});
    }
        return(
            <div className= "functional-box">
            <div className= "login-page">
            <div className= "login-title">Log In</div>
            <div className= "inputs">
                <input className= "input-text" onChange={getUser} type="text" placeholder='Username'/>
                <input className= "input-text" onChange={getPassword} type="password" placeholder="Password"/>
            </div>
            <div className="button-div"><Button className="login-button" text="Login" onClick={buttonClickHandler}></Button></div>
            </div>
            </div>
        );
}


export default Login;

The Login() function is called in my App class and seems to be working fine there because the HTML is showing up.

import './App.css';
import Card from './components/Card.jsx'
import Login from './components/Login.jsx'
import { LoggedInSidebar, LoggedOutSidebar } from './components/Sidebar.jsx';
import React, { useState } from 'react';
import axios from 'axios';
import Button from './components/button.jsx';

class App extends React.Component {


  render() {
    return (
      <div className="main-page">

        <div className="topbar">
          <div className="topbar-title">Glass Table</div>
        </div>

        <div className= "main-box-div">

          <div className="login-sidebar">
            <LoggedOutSidebar></LoggedOutSidebar>
          </div>

          <div className="functional-box">
            <Login></Login>
          </div>

        </div>

      </div>
    )
  }

}

export default App;

And finally the button class which was borrowed from a template website. I don’t believe that it adjusts the onClick function?

import React from "react";
import styled from "styled-components";

const Button = ({text}) => {
  return (
    <StyledWrapper>
      <button className="animated-button">
        <svg
          viewBox="0 0 24 24"
          className="arr-2"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z" />
        </svg>
        <span className="text">{text}</span>
        <span className="circle" />
        <svg
          viewBox="0 0 24 24"
          className="arr-1"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z" />
        </svg>
      </button>
    </StyledWrapper>
  );
};

const StyledWrapper = styled.div`
  .animated-button {
  position: relative;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 16px 36px;
  border: 4px solid;
  border-color: transparent;
  font-size: 16px;
  background-color: inherit;
  border-radius: 100px;
  font-weight: 600;
  color: greenyellow;
  box-shadow: 0 0 0 2px greenyellow;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);
}

.animated-button svg {
  position: absolute;
  width: 24px;
  fill: greenyellow;
  z-index: 9;
  transition: all 0.8s cubic-bezier(0.23, 1, 0.32, 1);
}

.animated-button .arr-1 {
  right: 16px;
}

.animated-button .arr-2 {
  left: -25%;
}

.animated-button .circle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  background-color: greenyellow;
  border-radius: 50%;
  opacity: 0;
  transition: all 0.8s cubic-bezier(0.23, 1, 0.32, 1);
}

.animated-button .text {
  position: relative;
  z-index: 1;
  transform: translateX(-12px);
  transition: all 0.8s cubic-bezier(0.23, 1, 0.32, 1);
}

.animated-button:hover {
  box-shadow: 0 0 0 12px transparent;
  color: #212121;
  border-radius: 12px;
}

.animated-button:hover .arr-1 {
  right: -25%;
}

.animated-button:hover .arr-2 {
  left: 16px;
}

.animated-button:hover .text {
  transform: translateX(12px);
}

.animated-button:hover svg {
  fill: #212121;
}

.animated-button:active {
  scale: 0.95;
  box-shadow: 0 0 0 4px greenyellow;
}

.animated-button:hover .circle {
  width: 220px;
  height: 220px;
  opacity: 1;
}

`;

export default Button;

I get this error data:image/png;base64,[object Object] when i load image from Mongodb

I have a html table, where I do data from MongoDB but the image has refused to show, and I’m not sure what I am doing wrong.

here is what i have done so far.

here is the js code to get the image and the data from the client and send to the backend server

app.post('/newInt_ImgUpload', upload.array('inventoryImg', 3), async (req, res) => {
    //console.log(req.files);
    //console.log(req.body);
    const cookies = req.headers.cookie;
    const jwtToken = cookies.split("=")[1].split(";")[0];
    //console.log(jwtToken);
    if (!jwtToken) {
        console.log('app crashed at line 119: PersonalInfo');
        return res.sendStatus(401);
    }
    const refreshToken = jwtToken;

    const user = await userModel.findOne({RefreshToken: refreshToken}).exec()
    if(!user) return res.sendStatus(401);
    console.log('User was found');

    const count = new Uint32Array(1);

    try {
        const inventory = await inventoryModel.create({
            'UserId': user._id,
            'Name': req.body.ItemName,
            'DateAdded': date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[0],
            'Price': req.body.Price,
            'WeightKG': req.body.WeightKG,
            'Quantity': req.body.Quantity,
            'Description': req.body.Description,
            'image1': { 
                data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[0].filename)).toString('base64'),
                contentType: req.files[0].mimetype
            },
            'image2': { 
                data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[1].filename)).toString('base64'),
                contentType: req.files[1].mimetype
            },
            'image3': { 
                data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[2].filename)).toString('base64'),
                contentType: req.files[2].mimetype
            },
            'Id': Math.trunc((crypto.getRandomValues(count))/1000000)
        });
        const result = await inventory.save();
        console.log(result);
        const inventoryActivitylog = await activityLogsModel.create({
            'UserId': user._id,
            'Date': date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[0],
            "Time": date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[1],
            'Status':  "Inventory updated."
        });
        await inventoryActivitylog.save();

        req.files.forEach(files => {
            fs.unlink(path.join(__dirname + '/uploads/' + files.filename), (err) => {
                if (err) throw err;
                //console.log('Image deleted');
              });
        })
        console.log("All images deleted")
        //res.redirect('/userProfile');
        res.status(200).json({ success: true, message: 'Inventory updated and images processed' });
    } catch (error) {
        console.log(error);
    }
});

after that has been done, the code below loads each time to the page that shows the table data, but the image refuses to show and give the following error: data:image/png;base64,[object Object]

document.getElementById('allitems').addEventListener('click', async () => {
    try {
        const response = await fetch('http://localhost:4000/Inventory/allInventory/List', { 
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include' 
        })

        .then(async response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`); 
            }
            return response.json();
            })
        .then(data => {
            const inventoryList = document.querySelector('.inventoryList');
        
            // Clear any existing rows
            inventoryList.innerHTML = '';

            // Loop through the fetched data and create new rows
            data.forEach(item => {
                console.log(item);
                const eachInventory = document.createElement('div');
                eachInventory.classList.add('eachInventory');

                const imgsrc = `data:${item.image1.contentType};base64,${item.image1.data}`;

                eachInventory.innerHTML = `
                    <div class="itemName">
                        <div><img src="${imgsrc}" alt=""></div>
                        <div><h4>${item.Name}</h4></div>
                    </div>
                    <div class="itemDate"><h3>${new Date(item.DateAdded).toLocaleDateString()}</h3></div>
                    <div class="itemPrice"><h3>${item.Price.toLocaleString()}</h3></div>
                    <div class="itemQuantity"><h3>${item.Quantity}</h3></div>
                `;
                
                // Append the new row to the table
                inventoryList.appendChild(eachInventory);
            })
        });
    } catch (error) {
        console.error('Error:', error);
    }
});

this is the image
enter image description here