does the scale should change with the Page scale in react pdf

I am using pdf.js to show some pdf file with react project, actually using react-pdf which wrapped the pdf.js. Now I am using scale like this to zoom in or zoom out the pdf:

      <Page
        key={index + "@new-" + projAttribute.pdfScale}
        scale={projAttribute.pdfScale}
        className={styles.pdfPage}
        onLoad={handlePageChange}
        canvasRef={(element) => updateRefArray(index, element)}
        onChange={handlePageChange}
        onRenderSuccess={handlePageRenderSuccess}
        pageNumber={index}
        width={width}
      >
        {curPdfPosition && viewPort ? (
          <Highlight
            position={curPdfPosition}
            pageNumber={index}
            viewport={viewPort}
          ></Highlight>
        ) : (
          <div></div>
        )}
      </Page>

and this is how I get the viewport:

 React.useEffect(() => {
  setPageViewports(undefined);

  if (!pdf) {
    return;
  }

  (async () => {
    const pageNumbers = Array.from(new Array(pdf.numPages)).map(
      (_, index) => index + 1
    );

    const nextPageViewports = await asyncMap(
      pageNumbers,
      (pageNumber: number) =>
        pdf
          .getPage(pageNumber)
          .then((page) =>
            page.getViewport({ scale: projAttr.pdfScale || 1 })
          )
    );
    setPageViewports(nextPageViewports);
  })();
}, [pdf]);

should I change the viewport scale or keep it with the same with pdf scale(the pdf scale range is 0.1-6.0, and + or – 0.1 with each click) when zoom the pdf? or what value should I set with the viewport scale?

Open Local Outlook Client with Attachments from Backend Using Frontend File Selection [closed]

I’m working on a web application where users can select files in the frontend, and those files are fetched from the backend. After selecting the files, I want the user’s local Outlook client to open with a pre-drafted email that includes the selected attachments, allowing the user to review and send the email manually.

Here’s what I’m trying to achieve:

Scenario: The user selects files in the frontend. After clicking the “Send Mail” button, the local Outlook client should open with a new email, including the files (fetched from the backend) attached.

Requirements:
The email should be opened in the user’s local Outlook client before sending (instead of being sent programmatically).

Attachments should be dynamically fetched from the backend based on the user’s selection in the frontend.

I am aware of how to send emails programmatically using the Microsoft Graph API, but I need a solution that opens the local Outlook client instead.

I’m considering whether Outlook add-ins could help, but I haven’t figured out how to pass attachments from the backend.

timer doesn’t reset correctly when stopping in js code for a simple time tracker [closed]

I’m working on a simple time tracker project and I’ve written the following JavaScript code. The goal is to track the elapsed time, with options to start and stop the timer.

let startTime;
let elapsedTime = 0;
let timerInterval;

function startTimer() {
  startTime = Date.now() - elapsedTime;
  timerInterval = setInterval(() => {
    elapsedTime = Date.now() - startTime;
    document.getElementById('elapsed-time').textContent = (elapsedTime / 1000).toFixed(1);
  }, 100);
}

function stopTimer() {
  clearInterval(timerInterval);
}

document.getElementById('start-button').addEventListener('click', startTimer);
document.getElementById('stop-button').addEventListener('click', stopTimer);
<div>
  <h1>Simple Time Tracker</h1>
  <button id="start-button">Start</button>
  <button id="stop-button">Stop</button>
  <p>Elapsed Time: <span id="elapsed-time">0</span> seconds</p>
</div>

I’ve been using Traqq as an example for my project. However, I’m running into an issue where the timer doesn’t reset correctly when stopping and then starting again. I always get the cumulative time instead of it resetting back to zero.

Does anyone have an idea on how to correctly reset the timer so it starts from zero each time? Any suggestions or improvements on my current approach would be greatly appreciated.

I added an additional button to reset the timer and tried to reset elapsedTime to 0 when the stopTimer function is called. However, that didn’t work as expected. Specifically, I added:

<button id="reset-button">Reset</button>

Should I really handle no internet page in react?

I have develop a react app. While browsing, if internet connection is switch off then it show unexpected error, loading chunk failed. Should I handle the network error? Or I should only handle the error of the page and that will be enough? I am using react-router-dom 6.20+
enter image description here

How do I use a react-web-component component in a vanilla js file tied to an HTML file

I created a simple React component.

const ReactComponent = () => {
   const [name, setName] = useState("something");
  return <div>Hello {name}</div>
}
export default ReactComponent;

And I used react-to-webcomponent library to convert it to a plain HTML tag which gives me tags which I can use in any page. But I want to use it inside a standalone HTML page with vanilla js.

index.html

<script async defer src='index.js'></script>
<body>
<div id='main>Hello World</div>
</body>

index.js

import {initComponent} from '/ReactComponentWC.js'
const main = document.getElementById("main");
initComponent(main)

In ReactComponentWC.js

const initComponent = (containerElement) => {
    const reactElement = r2wc(ReactComponent, React, ReactDOM)
    customElements.define("react-component", reactElement)
    const myComp = document.createElement('div')
    myComp.innerHTML = `<react-component />`
    containerElement.appendChild(myComp)
}

export { initComponent }

When I load the index.html on Live Server, I get this error
‘Uncaught TypeError: Failed to resolve module specifier “react”. Relative references must start with either “/”, “./”, or “../”.’

Then I tried to bundle the ReactComponentWC.js file using webpack. Now when I imported from the bundled /dist/ReactComponent.js file, it showed “no export named initComponent found”

. This import works fine in any nextjs page in my app. The error occurs only in this standalone HTML page.

Any suggestions on how I can export my react component so that it can be used by any JS frontend framework or even vanilla js apps? Thanks in advance!

Sometimes in Space Invaders JS I shoot two aliens when the shoot hits the same time aliens shift

I would be very grateful for any help, trying to code Space Invaders in JS, managed to move aliens in functions to shift the board right left and down in Intervals, the laser shoot is also in another Interval moving it up.
The problem that sometimes when the laser hits the exact time aliens are shifting it shoots two aliens, and my alien counter on the screen doesn’t match the actual seen on the game, and cant finish the game, i finish the game according to the global var aliens counter, is it a problem of Intervals, or handleHit function I am not sure.

https://github.com/Farhan-Ganayim/Space-Invaders
https://farhan-ganayim.github.io/Space-Invaders/

I managed to shoot aliens and the score is fine, that happens when play game with slow aliens and shoot them accurately, but when setting the interval to 1 sec, sometimes the problem of shooting two aliens happens.

function handleAlienHit(pos) {
    
    // clearInterval(laserInterval)
    // updateCell(pos,null)
    gGame.alienCount--    
    updateScore()
    gHero.isShoot=false  
}

function blinkLaser(pos) {
    // var cellGameObject=gBoard[pos.i][pos.j].gameObject
    updateCell(pos, LASER)
    setTimeout(() => {
        updateCell(pos, null)
    }, 80)
}

React app offline page render on browser reload

I have a React app https://codesandbox.io/p/sandbox/q6l8jp that uses the react-use-is-online npm package to check online and offline status. The package works perfectly, displaying appropriate messages for online and offline states. However, when I try to reload my browser while offline, my app fails to render and shows the browser’s default “no internet” page instead.

I would like to load my app and display a custom error message even when there is no internet connection. For example, YouTube continues to render its app even when offline. How can I achieve this?

Dynamic import on Chrome for windows get stuck since today

I have many apps using dynamic import of javascript modules working for years.

Since today they are no longer working on chrome for windows.

The code line

const def = await import("../main.mjs");

is never returning nor throwing an exception (Its surrounded by try/catch)

On all other Browsers its still working fine.

Any suggestions?

await client.connect(); gives “await is only valid in async functions” [duplicate]

The below code is offered on many tutorials (e.g. https://node-postgres.com/#getting-started and https://node-postgres.com/apis/client):

const { Client } = require('pg')
const client = new Client({ user: 'postgres', password: 'postgres', database: 'postgres' })
await client.connect();
// do something
await client.end()

However, it doesn’t work; when I do node mytest.js it gives:

await client.connect()
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules

What I am doing wrong compared with the tutorials?

I tried this:

client.connect();
save(client, '1', '1', '1', '1')
client.end()

function save(client, playerId) {
    const res = client.query(`INSERT INTO  testtable (player_id)
    VALUES ($playerId)`, [playerId])
}

But this gives:

Error: Connection terminated

how to override a js function in api for wp plugin

I have to create a wp plugin that uses api provided by hero property management to show listings. I need to override a function that is in the api that shows single listing on onClick event in iframe. How to override that function a show the single listing in a new page/url.

The main js function in api is similar to this:
openListingFromSummary(‘listingId’, ‘listingDesc’);

I tried to override it using the following code:

var orig_openListingFromSummary = window.openListingFromSummary('TX055461L', '$1995/month 2 bedroom / 2.5 bathroom Single family');
window.openListingFromSummary = function(){
    orig_openListingFromSummary();
    alert('HI');
}

I want the orig_openListingFromSummary function to operate instead of previous openListingFromSummary

Onesignal Web Push Notification in Frappe

I am using Onesignal for web push notification for frappe projects, So basically on Frappe on Doctype (Custom) i created Custom Button Subscribe and Unsubscribe. So if the user click on subscribe it will get subscribe and same for unsubscribe. For that my code is:

frappe.ui.form.on("Settings", {
    
    onload: function(frm) {
        frappe.call({
            method: "plantmaintenance.plantmaintenance.doctype.settings.settings.get_context",
            callback: function(r) {
                var data = r.message;
                $(frm.fields_dict["subscribe_and_unsubscribe"].wrapper).html(data);
                refresh_field("subscribe_and_unsubscribe");
                bindOneSignalButtons(frm);
            }
        });
    }
});
function bindOneSignalButtons(frm) {
    $('#subscribe').on('click', function(event) {
        event.preventDefault();
        var userId = getUserId();
        if (userId) {
            OneSignal.push(["registerForPushNotifications"]);
                    var externalUserId = frappe.session.user; 
                    OneSignal.push(function() {
                    OneSignal.setExternalUserId(externalUserId);
                    updateButtonState(true); 
                })
        } else {
            frappe.msgprint(__('User is not logged in.'));
        }
    });

   
    $('#unsubscribe').on('click', function(event) {
            OneSignal.push(function() {
                OneSignal.setSubscription(false).then(function() {
                    updateButtonState(false); 
                });
            });
    });
    checkSubscriptionStatus();
}

function checkSubscriptionStatus() {
    OneSignal.push(function() {
        OneSignal.getSubscription().then(function(isSubscribed) {
            updateButtonState(isSubscribed);
        });
    });
}
function updateButtonState(isSubscribed) {
    if (isSubscribed) {
        $('#unsubscribe').show();
        $('#subscribe').hide();
    } else {
        $('#unsubscribe').hide();
        $('#subscribe').show();
    }
}

Below is my html code where I define my button and initialisation of OneSignal.

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

   
    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>

    <style>
        .button {
            background-color: #008CBA;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="home-top" class="clearfix">
        <br>
     
        <div id="subscribe_and_unsubscribe">
            <button id="subscribe" class="button" style="display:none;">Subscribe</button>
            <button id="unsubscribe" class="button" style="display:none;">Unsubscribe</button>
        </div>
    </div>

    <script>

        var OneSignal = window.OneSignal || [];

        OneSignal.push(["init", {
            appId: "ONE_SIGNAL_APP_ID",
            autoRegister: false,
            notifyButton: {
                enable: false
            },
            allowLocalhostAsSecureOrigin: false,
            persistNotification: false,
        }]);

        function getUserId() {
            return typeof frappe !== 'undefined' ? frappe.session.user : null;
        }
    </script>
</body>
</html> 

Above functionality is working fine. But as I refresh the page the two of the button get disappear totally. Getting error uncaught promise OneSignal Initialisation failed.

Again I have to clear the cache and the code works fine.

How catch open close event of Chrome browser tab?

I have a project like a web base chat application. It contains one page. The JavaScript code is listening to new message from the server through a fetch statement in a setinterval, then displaying on page. What I need is a way to catch the open and close event of the browser tab then I can set interval listening on and of.
Thanks in advance.

Everytime my client is getting these types of error we tried everything but no luck [closed]

failed to load config from C:UsersspandDesktopvirtualr-mainvite.config.js
error during build:
Error: ENOENT: no such file or directory, open ‘C:UsersspandDesktopvirtualr-mainnode_modulesreact-refreshcjsreact-refresh-runtime.development.js’
at Object.readFileSync (node:fs:441:20)
at file:///C:/Users/spand/Desktop/virtualr-main/node_modules/@vitejs/plugin-react/dist/index.mjs:17:6
at ModuleJob.run (node:internal/modules/esm/module_job:262:25)
at async onImport.tracePromise.proto (node:internal/modules/esm/loader:483:26)
at async loadConfigFromBundledFile (file:///C:/Users/spand/Desktop/virtualr-main/node_modules/vite/dist/node/chunks/dep-DyBnyoVI.js:66633:15)
at async loadConfigFromFile (file:///C:/Users/spand/Desktop/virtualr-main/node_modules/vite/dist/node/chunks/dep-DyBnyoVI.js:66474:24)
at async resolveConfig (file:///C:/Users/spand/Desktop/virtualr-main/node_modules/vite/dist/node/chunks/dep-DyBnyoVI.js:66082:24)
at async build (file:///C:/Users/spand/Desktop/virtualr-main/node_modules/vite/dist/node/chunks/dep-DyBnyoVI.js:65179:18)
at async CAC. (file:///C:/Users/spand/Desktop/virtualr-main/node_modules/vite/dist/node/cli.js:828:5)

there are files missing that do not allow the website to run dev or build.

Tried:
installing again vite and all dependencies but did not work