Web application and Browser memory limitations

I am facing a challenge dealing with Browser memory limitations. Seems like on the 64-bit system the limit is 4GB. Loading less data at this point is not an option. However, in the Task Manager I see this:
enter image description here

which clearly shows that Edge is taking more than that.

I am thinking about a few of ideas (all crazy ones).

  1. Is it possible to swap some JS objects to a local file and later read it back?
  2. Is it possible to use some kind of a local DB for data/objects caching?
  3. (similar to #1) Is it possible to download a complete data snapshot to a local file and then read some into the app?

Please share any ideas.

Thanks

Should React state know how to update itself?

I am trying to decide if it is a good idea to design a React state that contains the logic to update itself (primarily by use of JS class syntax).

Below are two versions of a same Clock component:

import React from "react";

type TickTock = "tick" | "tock";

function Clock() {
    const [tick, setTick] = React.useState<TickTock>("tick");

    const handleTick = () => {
        setTick(state => {
            switch (state) {
                case "tick":
                    return "tock";

                case "tock":
                    return "tick";
            }
        });
    };

    React.useEffect(() => {
        const id = setInterval(handleTick, 1000);
        return () => {
            clearInterval(id);
        };
    }, []);

    return <div>{tick}</div>;
}

export default Clock;

In this one, the handleTick function looks at the state and decides how to update it.

import React from "react";

interface TickTock {
    title: string;
    next: TickTock;
}

class Tick implements TickTock {
    get title() {
        return "tick";
    }

    get next() {
        return new Tock();
    }
}

class Tock implements TickTock {
    get title() {
        return "tock";
    }

    get next() {
        return new Tick();
    }
}

function Clock() {
    const [tick, setTick] = React.useState<TickTock>(new Tick());

    const handleTick = () => {
        setTick(state => state.next);
    };

    React.useEffect(() => {
        const id = setInterval(handleTick, 1000);
        return () => {
            clearInterval(id);
        };
    }, []);

    return <div>{tick.title}</div>;
}

export default Clock;

In that one, the handleTick function merely calls the next getter to make the state update itself. The point is that the handleTick function has no knowledge of the state logic.

The first version is what I have seen done most often and seems the most straightforward. However, there have been cases where I have found the second version appealing, for example when a state gets complex and has only few definite ways of getting updated.

I was wondering therefore if there were drawbacks to the second version.

Ant Design Chart x and y scale starting position

When I encounter the same y values ​​or a small amount of x values

How to make the starting position of the y-axis scale align with the bottom, and the starting position of the X-axis scale align with the left

enter image description here
enter image description here

// my config
const config = {
       
        data,
        // height: 400,
        // width: 400,
        xField: "item",
        yField: "value",
        point: {
            shapeField: "circle",
            sizeField: 6,
        },
      
        style: {
            lineWidth: 2, 
            // stroke: "#f3f3f3", 
        },
        axis: {
            x: {
                labelSpacing: 16, 
                ...axisXYShared,
                labelFormatter: (dataum: string) => dataum + "day",
            },
            y: {
                labelSpacing: 32, 
                ...axisXYShared,
                labelDirection: "negative",
            },
        },

        tooltip: false,
        
    };

I have referenced the file scale configuration and tested it, but it does not work.

25/5000 How to use websocket together with http requests [closed]

When the front-end uses websocket, it immediately sends an http request after receiving a listening event, and the return result is not in the same order as the socket receives the result, and the expectation should be synchronous, please ask everyone to have a solution

重点词汇
55/5000
通用场景
I have tried to use the queue id setting method and have failed without exception. The problem of asynchronism still exists, and the http interface still has the problem of the results returning out of order

Slow Bouncy Effect on Hover using CSS and JS

I have this reference website called pipe.com and I’m so impressed with the bounce effect of the first section after the banner (see attached photo and please try to hover on the card on their website).

I’m having difficulty on achieving the same effect. Is there anyone who can guide me to do this? I’m building the website on WebFlow

Right Now I have this: https://codepen.io/sachin-kumar-mishra/pen/mdZKGWL

document.addEventListener("DOMContentLoaded", function() {
  const item1 = document.getElementById("item1");
  const items = document.querySelectorAll(".item");

  item1.classList.add("initial");

  items.forEach(item => {
    if (item.id !== "item1") {
      item.addEventListener("mouseenter", () => {
        if (window.innerWidth > 786) { // Only apply hover effects if screen width is larger than 768px
          items.forEach(i => i.classList.remove("hovered"));
          item.classList.add("hovered");
          item1.classList.remove("initial");
          
          const initialContent = item1.querySelector('.initial-content');
          const hiddenContent = item1.querySelector('.hidden-content');
          
          if (initialContent) 
            initialContent.style.display = 'none';
            
          if (hiddenContent) 
            hiddenContent.style.display = 'block';
        }
      });

      item.addEventListener("mouseleave", () => {
        if (window.innerWidth > 786) { // Only apply hover effects if screen width is larger than 768px
          items.forEach(i => i.classList.remove("hovered"));
          item1.classList.add("initial");
          
          const initialContent = item1.querySelector('.initial-content');
          const hiddenContent = item1.querySelector('.hidden-content');
          
          if (initialContent) 
            initialContent.style.display = 'block';
            
          if (hiddenContent) 
            hiddenContent.style.display = 'none';
        }
      });
    }
  });
});


var mobilevideo = document.getElementsByTagName("video")[0];
mobilevideo.setAttribute("playsinline", "");
mobilevideo.setAttribute("muted", "");
.ccontainer {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  gap: 15px;
  height: 100%;
  flex-direction: row;
}

.item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 30%;
  border-radius: 20px;
  overflow: hidden;
  color: #030043;
  text-align: left;
  position: relative;
  background: linear-gradient(180deg, #F0EEF3 0%, #B3C8FF 100%);
  font-family: Everett, sans-serif;
}

.item.hovered {
  width: 54%;
  background-color: #e0e0e0;
  /*animation: horizontalBounce 0.5s;*/
}

#item1.initial {
  width: 54%;
  background-color: #e0e0e0;
  /*animation: horizontalBounce 0.5s;*/
}

.content {
  z-index: 99;
  flex: 1;
  height: 110%;
  padding: 55px 20px 20px;
}

.image {
  display: none;
  width: 320px;
  height: auto;
  margin-top: 2rem;
  margin-bottom: -5px;
}

.item#item1.initial .image,
.item.hovered .image {
  display: block;
}

button {
  color: white;
  padding: 4px 30px;
  font-size: 18px;
  line-height: 35px;
  gap: 10px;
  border: none;
  background: linear-gradient(90deg, #0063EC 0%, #012681 100%);
  border-radius: 100px;
  font-family: Everett, sans-serif;
  position: absolute;
  bottom: 1.3rem;
}

.content p,
.heading2 {
  font-family: Everett, sans-serif;
  font-weight: 500;
  font-size: 30px;
  margin: 15px 0 10px;
  color: #030043;
}

.cont ul {
  margin: 1rem 0;
  padding-left: 5px;
  list-style-type: none;
  /* Remove the default list style */
}

.cont ul li {
  list-style-image: url('https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66be3617b3d309575b7840e0_Vector.png');
  margin: 0 0 9px 20px;
  /* Adjust margin as needed */
  line-height: 22px;
  color: #030043;
  font-size: 14px;
}

.cont p {
  line-height: 23px;
  color: #030043;
  max-width: 320px;
  font-size: 14px;
}

button a {
  color: #fff;
}

button:hover {
  background-color: #0056b3;
}

.item.hovered .initial-content {
  display: none;
}

.item.hovered .hidden-content {
  display: block;
}

.hidden-content {
  display: none;
}

.initial-content {
  display: block;
}

.cont {
  display: flex;
  flex-direction: column;
  height: 90%;
}

.initial-content,
.hidden-content {
  height: 80%;
}

@keyframes horizontalBounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateX(0);
  }
  40% {
    transform: translateX(-5px);
  }
  60% {
    transform: translateX(10px);
  }
}

@media (max-width: 768px) {
  .cont ul {
    display: none;
  }
  #item1.initial {
    width: 100%;
  }
  #item1.initial .content .initial-content,
  #item1.initial .content .image {
    display: none;
  }
  #item1.initial .content .hidden-content {
    display: block;
  }
  .item#item1.initial .image,
  .item.hovered .image {
    display: none;
  }
  .ccontainer {
    flex-direction: column;
    align-items: center;
  }
  .item {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
  }
  .item.hovered {
    width: 100%;
  }
  .image {
    width: 85%;
    height: auto;
    display: none;
    margin-left: 50px;
    margin-top: 1.5rem;
  }
  .content {
    padding: 20px 20px 5px;
  }
  button {
    position: relative;
    width: 100%;
    margin-top: 1.4rem;
  }
  .initial-content button {
    bottom: 1.5rem;
    position: absolute;
    width: 79%;
  }
  #item1 .initial-content button {
    bottom: 1.5rem;
    position: absolute;
    width: 79%;
  }
  #item1 .hidden-content button {
    margin-top: 4rem;
  }
  /* .initial-content {
            display: none;
        }
        .hidden-content {
            display: block;
        }*/
}

@media (max-width: 480px) {
  .item {
    padding: 10px 0 0 10px;
    min-height: 330px;
  }
  h2 {
    font-size: 18px;
  }
  .heading-2 span {
    padding-right: 7px;
  }
}
<div class="ccontainer">
  <div class="item" id="item1">
    <div class="content">
      <div class="hidden-content">
        <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66b0cbe1e7741c9e30daf857_Icon.png" alt="icon" />
        <p class="heading2">Property Owners</p>
        <div class="cont">
          <p>Keyper unlocks an array of services that help you manage your property with unparalleled efficiency, from financing options to portfolio monitoring and market insights.
          </p>
        </div>
        <a href="/property-owner"><button>Learn more</button></a>
      </div>
      <div class="initial-content">
        <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66b0cbe1e7741c9e30daf857_Icon.png" alt="icon" />
        <p class="heading2">Property Owners</p>
        <div class="cont">
          <p>Keyper unlocks an array of services that help you manage your property with unparalleled efficiency, from financing options to portfolio monitoring and market insights.
          </p>
          <ul>
            <li>Cash out on your tenant’s outstanding rent any time and receive it digitally.</li>
            <li>Track your property's valuation & activity and that of properties like yours. </li>
            <li>Experience full-service property management. Buying, selling, leasing & financing. We'll handle it all.</li>
          </ul>
        </div>
        <a href="/property-owner"><button>Learn more</button></a>
      </div>
    </div>
    <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66c7048bbd323fa74ca1f934_Property%20Owner%20Image.png" class="image" alt="Image 1">
  </div>
  <div class="item" id="item2">
    <div class="content">
      <div class="initial-content">
        <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66b0cbe1e7741c9e30daf857_Icon.png" alt="icon" />
        <p class="heading2">Tenants</p>
        <div class="cont">
          <p>Say hello to pain free rent! With Keyper, you can pay your yearly rent in 12 installments by card. It’s what we like to call Rent Now, Pay Later or RNPL for short.</p>
        </div>
        <a href="https://t.realkeyper.com/tenants"><button>Learn more</button></a>
      </div>
      <div class="hidden-content">
        <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66b0cbe1e7741c9e30daf857_Icon.png" alt="icon" />
        <p class="heading2">Tenants</p>
        <div class="cont">
          <p>Say hello to pain free rent! With Keyper, you can pay your yearly rent in 12 installments by card. It’s what we like to call Rent Now, Pay Later or RNPL for short.</p>
          <ul>
            <li>Enjoy monthly rent payments, no matter your landlord’s terms.</li>
            <li>Drop the cheque book and unlock bank rewards when you pay by card.</li>
            <li>Find the perfect home that meets your preferred payment terms on Keyper’s marketplace.</li>
          </ul>
        </div>
        <a href="https://t.realkeyper.com/tenants"><button>Learn more</button></a>
      </div>
    </div>
    <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66c7048ca48207cc04c4aeac_Tenants%20Image.png" class="image" alt="Image 2">
  </div>
  <div class="item" id="item3">
    <div class="content">
      <div class="initial-content">
        <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66b0cbe1e7741c9e30daf857_Icon.png" alt="icon" />
        <p class="heading2">Partners</p>
        <div class="cont">
          <p>Grow your sales with Keyper! Elevate your clients’ experience with an array of services designed to help them manage their property. The best part? You’ll earn a commission for every property you refer.</p>
          <!--a href="https://keyper-website-4.webflow.io/partners"--><button>Learn more</button>
          <!--/a-->
        </div>
      </div>
      <div class="hidden-content">
        <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66b0cbe1e7741c9e30daf857_Icon.png" alt="icon" />
        <p class="heading2">Partners</p>
        <div class="cont">
          <p>Grow your sales with Keyper! Elevate your clients’ experience with an array of services designed to help them manage their property. The best part? You’ll earn a commission for every property you refer.</p>
          <ul>
            <li>Earn a minimum of AED 2,000 for each successful referral.</li>
            <li>Close deals faster by offering tenants the option to pay their rent monthly.</li>
            <li>Your clients are always yours to keep.</li>
          </ul>
        </div>
        <!--a href="https://keyper-website-4.webflow.io/partners"--><button>Learn more</button>
        <!--/a-->
      </div>
    </div>
    <img src="https://uploads-ssl.webflow.com/66ac6355674df55afff1135a/66c7048be2b6c800111808fc_Partners%20Image.png" class="image" alt="Image 3">
  </div>
</div>

How to use widgetVar in Javascript in Selenium in Java with PrimeFaces?

I have got on localhost a JavaEE with PrimeFaces appplication running. Now I want to test it with Selenium using the widgetVar ids in Javascript and JQuery.

I have got the following code in my Helper functions class:

private static boolean isContentByWidgetVarProDriver(WebDriver driver, String driverName, String content, String widgetVar) {
       String value = "";
        try {
            Wait wait = waitForJQueryAndPrimeFaces(driver);
            Object selectedItemAsObject = wait.until((webdriver) -> {
                return ((JavascriptExecutor) driver).executeScript("$output = PF('domains_counter').content[0].innerText;" +
                        "return $output;");
            });
            WebElement selectedItem = (WebElement) selectedItemAsObject;

            if (selectedItem.getText().contains(content)) {
                return true;
            }
        } catch (Exception e) {
            LOGGER.info("Test failed on {}:nSelector was '{}' but value '{}' could not be read. '{}' was expected as content.", driverName, widgetVar, value, content);
        }
        return false;
    }

and

private static Wait waitForJQueryAndPrimeFaces(WebDriver driver) {
        return (Wait) new FluentWait(driver).withTimeout(Duration.ofSeconds(TIME_OUT_SECONDS))
                .pollingEvery(Duration.ofMillis(POLLING_MILLISECONDS))
                .until(new Function< WebDriver, Boolean >() {
                    @Override
                    public Boolean apply(WebDriver input) {
                        boolean ajax = false;
                        boolean jQueryDefined = executeBooleanJavascript(input, JS_JQUERY_DEFINED);
                        boolean primeFacesDefined = executeBooleanJavascript(input, JS_PRIMEFACES_DEFINED);

                        if (jQueryDefined) {
                            // jQuery is still active
                            ajax |= executeBooleanJavascript(input, JS_JQUERY_ACTIVE);
                        }
                        if (primeFacesDefined) {
                            // PrimeFaces queue isn't empty
                            ajax |= executeBooleanJavascript(input, JS_PRIMEFACES_QUEUE_NOT_EMPTY);
                        }

                        // continue if all ajax request are processed
                        return !ajax;
                    }
                });
    }

    private static boolean executeBooleanJavascript(WebDriver input, String javascript) {
        return (Boolean) ((JavascriptExecutor) input).executeScript(javascript);
    }

First I tried without wait, but the String value was always null. Then I tried with wait, but now the String value is empty.

I did test the javascript and JQuery in the browser console and it worked. But not from Selenium.

The important thing for me is to use the widgetVar’s from Primefaces. Before I used other selectors (css, xpath, …) from the DOM, but the DOM is so complicated with popup items, that it would be better to use the widgetVar ids from PrimeFaces. But how? Any help is appreciated.

Yesterday I did a lot of googling on the subject.

JavaScript Heap Out of Memory Error: Allocation Failure

I’m using NestJS with Node.js version v20.12.1, and every time I run my project, I encounter an “insufficient memory” error. I’m not sure where this issue is coming from. Can you help me figure out how to resolve it?
The error as below.

FATAL ERROR: Reached heap limit Allocation failed – JavaScript heap out of memory

—– Native stack trace —–

1: 00007FF60DA7C81B node::SetCppgcReference+17979

2: 00007FF60D9E6674 DSA_meth_get_flags+89316

3: 00007FF60E464871 v8::Isolate::ReportExternalAllocationLimitReached+65

4: 00007FF60E44DFC8 v8::Function::Experimental_IsNopFunction+1336

5: 00007FF60E2AFA70 v8::Platform::SystemClockTimeMillis+659328

6: 00007FF60E2ACAF8 v8::Platform::SystemClockTimeMillis+647176

7: 00007FF60E2C1E0A v8::Platform::SystemClockTimeMillis+733978

8: 00007FF60E2C2687 v8::Platform::SystemClockTimeMillis+736151

9: 00007FF60E2D0F7F v8::Platform::SystemClockTimeMillis+795791

10: 00007FF60DF91CA5 v8::CodeEvent::GetFunctionName+116773

11: 00007FF60E51619E v8::PropertyDescriptor::writable+677998

12: 00007FF60E4E2115 v8::PropertyDescriptor::writable+464869

13: 00007FF60E484E13 v8::PropertyDescriptor::writable+83171

14: 00007FF5E83DE857

RpcExitError: Process 11824 exited with code 134

Issues checking service aborted – probably out of memory. Check the `memoryLimit` option in the ForkTsCheckerWebpackPlugin configuration. If increasing the memory doesn’t solve the issue, it’s most probably a bug in the TypeScript.

Index.html not served [closed]

I am currently working on an React application using Vite. When I NPM run dev the frontend and backend server do start, but the index.html does not get served and I can’t figure out why.

My file structure looks like this:

I tried to use tree, but I got 4099 directories and 21093 files printed out.

And this is my vite.config.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  root: 'client',
  build: {
    outDir: '../dist',
    assetsDir: 'src/assets',
  },
  define: {
    "process.env": {},
  },
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^/api/, ''),
      },
    },
  },
});

express js module not found and node_modules file not creating

First, I ran the ‘npm init’ command in the folder I was working in. Then, I ran the ‘npm install express’ command. Two files named package-lock.json and package.json were created in my folder, but the node_modules file was not created. When I run the ‘node app.js’ command in the same directory, I get a ‘module not found’ error.

i upgrade npm, reinstall express, reinstall node

WebSocket connection ending and re-establishing navigation to different pages

I am building a medium sized project on React with Vite. The websocket connection gets closed and re-established when navigate to another page using the sidebar

main.tsx :-

import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { AuthProvider } from '@/contexts/AuthContext';
import React from 'react';
import { WebSocketProvider } from '@/contexts/WebSocketContext';

const Root = React.memo(() => (
    <React.StrictMode>
        <AuthProvider>
            <WebSocketProvider>
                <App />
            </WebSocketProvider>
        </AuthProvider>
    </React.StrictMode>
));

ReactDOM.createRoot(document.getElementById('root')!).render(<Root />);

router.tsx :-

import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import SignInPage from '@/pages/SignInPage';
import TasksPage from '@/pages/Tasks/TasksPage';
import CreateTaskPage from '@/pages/Tasks/CreateTaskPage';
import DashboardPage from '@/pages/Dashboard/DashboardPage';
import AuthRedirect from '@/components/AuthComponents/AuthRedirect';
import ProtectedRoute from '@/components/AuthComponents/ProtectedRoute';
import TaskViewPage from '@/pages/Tasks/TaskViewPage';
import EditTaskPage from '@/pages/Tasks/EditTaskPage';
import MembersPage from '@/pages/Members/Members/MembersPage';
import CreateMemberPage from '@/pages/Members/Members/CreateMemberPage';
import MemberViewPage from '@/pages/Members/Members/MemberViewPage';
import MemberEditPage from '@/pages/Members/Members/MemberEditPage';
import MemberDashboardPage from '@/pages/Members/Dashboard/MemberDashboardPage';
import MemberActivity from '@/pages/Activity/MemberActivity';
import MyActivity from '@/pages/Activity/MyActivity';
import NotificationsPage from '@/pages/Activity/NotificationsPage';
import Alerts from '@/pages/Activity/Alerts';
import Account from '@/pages/Account/Account';
import NotFoundPage from "@/pages/404";

const router = createBrowserRouter([
  {
    path: '/',
    element: <AuthRedirect />,
  },
  {
    path: 'sign-in',
    element: <SignInPage />,
  },
  {
    path: 'tasks',
    element: (
      <ProtectedRoute>
        <TasksPage />
      </ProtectedRoute>
    ),
  },
  {
    path: 'create-task',
    element: (
      <ProtectedRoute>
        <CreateTaskPage />
      </ProtectedRoute>
    ),
  },
  {
    path: 'dashboard',
    element: (
      <ProtectedRoute>
        <DashboardPage />
      </ProtectedRoute>
    ),
  },
  {
    path: 'task/:id',
    element: (
      <ProtectedRoute>
        <TaskViewPage />
      </ProtectedRoute>
    ),
  },
  {
    path: 'task/edit/:id',
    element: (
      <ProtectedRoute>
        <EditTaskPage />
      </ProtectedRoute>
    ),
  },
  {
    path: 'members',
    element: (
      <ProtectedRoute>
        <MembersPage />
      </ProtectedRoute>
    ),
  },
  {
    path: '/members/create',
    element: (
      <ProtectedRoute>
        <CreateMemberPage />
      </ProtectedRoute>
    ),
  },
  {
    path: '/member/:id',
    element: (
      <ProtectedRoute>
        <MemberViewPage />
      </ProtectedRoute>
    ),
  },
  {
    path: '/member/edit/:id',
    element: (
      <ProtectedRoute>
        <MemberEditPage />
      </ProtectedRoute>
    ),
  },
  {
    path: '/members/dashboard',
    element: (
      <ProtectedRoute>
        <MemberDashboardPage />
      </ProtectedRoute>
    ),
  },
  {
    path: '/activity/members',
    element: (
      <ProtectedRoute>
        <MemberActivity />
      </ProtectedRoute>
    ),
  },
  {
    path: '/activity/member',
    element: (
      <ProtectedRoute>
        <MyActivity />
      </ProtectedRoute>
    ),
  },
  {
    path: '/activity/notifications',
    element: (
      <ProtectedRoute>
        <NotificationsPage />
      </ProtectedRoute>
    ),
  },
  {
    path: '/activity/alerts',
    element: (
      <ProtectedRoute>
        <Alerts />
      </ProtectedRoute>
    ),
  },
  {
    path: '/account',
    element: (
      <ProtectedRoute>
        <Account />
      </ProtectedRoute>
    ),
  },
  {
    path: "*",
    element: (
      <ProtectedRoute>
        <NotFoundPage />
      </ProtectedRoute>
    )
  }
]);

export function Router() {
  return <RouterProvider router={router} />;
}

WebSocketContext.tsx :-

import React, { createContext, ReactNode, useContext, useEffect, useState } from 'react';
import { getMemberId } from '@/utils/auth';
import { Notification } from '@/types/NotificationTypes';
import { nanoid } from 'nanoid';

interface WebSocketContextType {
  notifications: Notification[];
  addNotification: (newNotification: Notification) => void;
  removeNotification: (notificationId: string) => void;
}

const WebSocketContext = createContext<WebSocketContextType | undefined>(undefined);

export const WebSocketProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const userId = getMemberId();

  const addNotification = (newNotification: Notification) => {
    newNotification = { ...newNotification, id: nanoid(), vanish: true };
    setNotifications([...notifications, newNotification]);

    setTimeout(() => {
      removeNotification(newNotification.id ?? '');
    }, 5000);
  };

  const removeNotification = (notificationId: string) => {
    setNotifications((notifications) =>
      notifications.filter((notification) => notification.id !== notificationId)
    );
  };

  useEffect(() => {
    if (!userId) {
      console.error('User ID is not available.');
      return;
    }

    const socket = new WebSocket(`wss://apiuverp.stepnex.tech/notifications/ws/${userId}`);

    socket.onopen = () => {
      console.log('WebSocket connection established');
    };

    socket.onmessage = (event) => {
      try {
        const newNotification = JSON.parse(event.data);
        if (
          newNotification &&
          newNotification.description &&
          newNotification.priority &&
          newNotification.url &&
          newNotification.id
        ) {
          setNotifications((prevMessages) => [...prevMessages, newNotification]);
          const acknowledgment = {
            action: 'acknowledge',
            notificationId: newNotification.id,
            memberId: userId,
          };
          socket.send(JSON.stringify(acknowledgment));
        } else {
          console.warn('Received malformed message:', newNotification);
        }
      } catch (error) {
        console.error('Error parsing WebSocket message:', error);
      }
    };

    socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    socket.onclose = (event) => {
      console.log('WebSocket connection closed', event);
    };

    return () => {
      socket.close();
    };
  }, [userId]);

  return (
    <WebSocketContext.Provider value={{ notifications, addNotification, removeNotification }}>
      {children}
    </WebSocketContext.Provider>
  );
};

export const useWebSocketMessages = () => {
  const context = useContext(WebSocketContext);
  if (context === undefined) {
    throw new Error('useWebSocketMessages must be used within a WebSocketProvider');
  }
  return context;
};

MainLayout.tsx (where i display notification) :-

'use client';
import React, { useEffect, useState } from 'react';
import { Dialog, DialogBackdrop, DialogPanel, TransitionChild } from '@headlessui/react';
import { Bars3Icon, BellIcon, UserCircleIcon, XMarkIcon } from '@heroicons/react/24/outline';
import Sidebar from '@/components/Common/Sidebar';
import MobileSidebar from '@/components/Common/MobileSidebar';
import TopBar from '@/components/Common/TopBar';
import { useWebSocketMessages } from '@/contexts/WebSocketContext';
import { useNavigate } from 'react-router-dom';
import axiosInstance from '@/axiosInstance';
import { Notification, NotificationPriority } from '@/types/NotificationTypes';
import navigation from '@/utils/NavigationItems';
import { Scope } from '@/types/EmployeeTypes';
import NotificationDropdown from '@/components/Notification/NotificationDropdown';
import { getScope } from '@/utils/auth';
import NotificationComponent from '@/components/Notification/NotificationComponent';
import HighPriorityNotification from '@/components/Notification/HighPriorityNotification';

interface SidebarLayoutProps {
  children: React.ReactNode;
  pageName: string;
}

export default function MainLayout({ children, pageName }: SidebarLayoutProps) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [localNotifications, setLocalNotifications] = useState<Notification[]>([]);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const { notifications, removeNotification } = useWebSocketMessages();
  const [highPriorityNotificationExists, setHighPriorityNotificationExists] =
    useState<boolean>(false);

  const userScope = getScope();

  const handleNotificationIconClick = () => {
    setIsDropdownOpen(!isDropdownOpen);
  };

  useEffect(() => {
    setLocalNotifications(notifications);
  }, [notifications]);

  useEffect(() => {
    if (notifications.length > 0) {
      const latestMessage = notifications[notifications.length - 1];
      console.log('New notification:', latestMessage);
      setLocalNotifications((prevNotifications) => [...prevNotifications, latestMessage]);
    }
  }, [notifications]);

  const navigate = useNavigate();

  useEffect(() => {
    const fetchTasksWithDeadlines = async () => {
      try {
        const response = await axiosInstance.get('/tasks/dead_task'); // Replace with your API endpoint

        if (typeof response.data === 'string' && response.data !== 'null') {
          navigate(`/task/${response.data}`);
        } else if (response.data === null) {
          return;
        } else {
          console.error('Unexpected response format');
        }
      } catch (error) {
        console.error('Error fetching tasks:', error);
      }
    };

    fetchTasksWithDeadlines();
  }, [navigate]);

  return (
    <div className={'antialiasing'}>
      <div className={'h-full bg-gray-400'}>
        <div className={'z-50 text-black'}>
          <Dialog open={sidebarOpen} onClose={setSidebarOpen} className="relative z-50 lg:hidden">
            <DialogBackdrop
              transition
              className="fixed inset-0 bg-gray-900/80 transition-opacity duration-300 ease-linear data-[closed]:opacity-0"
            />

            <div className="fixed inset-0 flex">
              <DialogPanel
                transition
                className="relative mr-16 flex w-full max-w-xs flex-1 transform transition duration-300 ease-in-out data-[closed]:-translate-x-full"
              >
                <TransitionChild>
                  <div className="absolute left-full top-0 flex w-16 justify-center pt-5 duration-300 ease-in-out data-[closed]:opacity-0">
                    <button
                      type="button"
                      onClick={() => setSidebarOpen(false)}
                      className="-m-2.5 p-2.5"
                    >
                      <span className="sr-only">Close sidebar</span>
                      <XMarkIcon aria-hidden="true" className="h-6 w-6 text-white" />
                    </button>
                  </div>
                </TransitionChild>
                {/* Sidebar component, swap this element with another sidebar if you like */}
                <MobileSidebar Navigation={navigation} />
              </DialogPanel>
            </div>
          </Dialog>
          <TopBar pageName={pageName} />
        </div>

        {/* Static sidebar for desktop */}
        <div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-72 lg:flex-col">
          {/* Sidebar component, swap this element with another sidebar if you like */}
          <Sidebar />
        </div>

        <div className="sticky top-0 z-40 flex items-center gap-x-6 bg-white px-4 py-4 shadow-sm sm:px-6 lg:hidden">
          <button
            type="button"
            onClick={() => setSidebarOpen(true)}
            className="-m-2.5 p-2.5 text-gray-700 lg:hidden"
          >
            <span className="sr-only">Open sidebar</span>
            <Bars3Icon aria-hidden="true" className="h-6 w-6" />
          </button>
          <h2 className={'flex flex-row flex-grow'}>{pageName}</h2>
          {userScope !== Scope.EM && (
            <div>
              <span className="inline-flex items-center rounded-md bg-custom-blue-1 px-2 py-1 text-lg font-medium text-custom-blue-2 ring-1 ring-inset ring-blue-700/10">
                Admin
              </span>
            </div>
          )}
          <div className={'ml-10 flex flex-row justify-end gap-8'}>
            <div className="relative">
              <div
                className="relative hover:bg-gray-100 rounded-full cursor-pointer"
                onClick={handleNotificationIconClick}
              >
                <BellIcon height={32} />
              </div>
              {isDropdownOpen && (
                <div className="absolute right-0 mt-2">
                  <NotificationDropdown />
                </div>
              )}
            </div>
            <UserCircleIcon height={32} />
          </div>
        </div>

        <main className="py-1 lg:pl-64 bg-background-grey min-h-screen relative lg:pt-16">
          <div className="px-2 sm:px-4 lg:px-8 relative flex min-h-full flex-col bg-background-grey gap-4 my-4">
            {children}
          </div>
        </main>
      </div>
      {localNotifications.length > 0 && (
        <div className="flex flex-col fixed bottom-4 z-50 w-auto gap-2 right-4">
          {notifications.map((notification, index) => {
            if (notification.priority === NotificationPriority.HIGH) {
              console.log('HIGH PRIORITY NOTIFICATION RECEIVED');
              return (
                <HighPriorityNotification
                  setHighPriorityNotificationExists={setHighPriorityNotificationExists}
                  agenda={notification.agenda}
                  description={notification.description}
                  url={notification.url}
                />
              );
            }
            return (
              <NotificationComponent
                id={notification.id}
                removeNotification={removeNotification}
                key={index}
                priority={notification.priority}
                agenda={notification.agenda}
                description={notification.description}
                success={true}
                button_name={notification.button_name}
                url={notification.url}
                created_at={notification.created_at}
              />
            );
          })}
        </div>
      )}
    </div>
  );
}

Sidebar.tsx :-

import { Disclosure, DisclosureButton, DisclosurePanel } from '@headlessui/react';
import { ChevronRightIcon } from '@heroicons/react/20/solid';
import { useAuth } from '@/contexts/AuthContext';
import { useLocation } from 'react-router-dom';

import React from 'react';
import navigation from '@/utils/NavigationItems';

function classNames(...classes: string[]) {
  return classes.filter(Boolean).join(' ');
}

// Example of how to dynamically build the sidebar
export default function Sidebar() {
  const { logout } = useAuth();
  const location = useLocation();
  const currentPath = location.pathname;

  return (
    <div className="flex grow flex-col gap-y-5 overflow-y-auto border-r border-gray-200 bg-white px-6 py-1 h-screen fixed top-0 left-0 w-80 lg:w-64">
      <a href={'/'} className="flex h-16 shrink-0 items-center">
        <img alt="Your Company" src="/images/company_logo.png" className="h-auto w-full" />
      </a>
      <nav className="flex flex-1 flex-col">
        <ul role="list" className="flex flex-1 flex-col gap-y-7">
          <li>
            <ul role="list" className="-mx-2 space-y-1">
              {navigation.map((item) => (
                <li key={item.name}>
                  {!item.children ? (
                    <a
                      href={item.href}
                      className={classNames(
                        currentPath === item.href ? 'bg-gray-100' : 'hover:bg-gray-50',
                        'group flex gap-x-3 rounded-md p-2 text-sm font-semibold leading-6 text-gray-700'
                      )}
                    >
                      <item.icon aria-hidden="true" className="h-6 w-6 shrink-0 text-gray-400" />
                      {item.name}
                    </a>
                  ) : (
                    <Disclosure as="div">
                      <DisclosureButton
                        className={classNames(
                          currentPath.startsWith(item.href as string)
                            ? 'bg-gray-100'
                            : 'hover:bg-gray-50',
                          'group flex w-full items-center gap-x-3 rounded-md p-2 text-left text-sm font-semibold leading-6 text-gray-700'
                        )}
                      >
                        <item.icon aria-hidden="true" className="h-6 w-6 shrink-0 text-gray-400" />
                        {item.name}
                        <ChevronRightIcon
                          aria-hidden="true"
                          className="ml-auto h-5 w-5 shrink-0 text-gray-400 group-data-[open]:rotate-90 group-data-[open]:text-gray-500"
                        />
                      </DisclosureButton>
                      <DisclosurePanel as="ul" className="mt-1 px-2">
                        {item.children.map((subItem) => (
                          <li key={subItem.name}>
                            <DisclosureButton
                              as="a"
                              href={subItem.href}
                              className={classNames(
                                currentPath === subItem.href ? 'bg-gray-100' : 'hover:bg-gray-50',
                                'block rounded-md py-2 pl-9 pr-2 text-sm leading-6 text-gray-700'
                              )}
                            >
                              {subItem.name}
                            </DisclosureButton>
                          </li>
                        ))}
                      </DisclosurePanel>
                    </Disclosure>
                  )}
                </li>
              ))}
            </ul>
          </li>
          <li className="mt-auto">
            <button
              className="inline-flex w-full items-center gap-x-2 rounded-md bg-[#667A8A] px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-[#8093A4] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 mb-4"
              onClick={() => logout()}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth={2.5}
                stroke="currentColor"
                className="w-5 h-5"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-9a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 004.5 21h9a2.25 2.25 0 002.25-2.25V15M9 12h12m0 0l-3-3m3 3l-3 3"
                />
              </svg>
              Logout
            </button>
          </li>
        </ul>
      </nav>
    </div>
  );
}

I thought maybe the reason could be because i am using anchor tags in navigation instead of Link tags for navigation but even that didnt seem to work. This seems like an issue of unnecessary unmounting and remounting of WebSocketContext. Still not able to find the reason.

How to create an npm package that references CSS files and a service worker

I have an npm package that contains a main script (index.js), a CSS file (main.css), and a service worker (sw.js).

The main script adds the CSS files to the head by adding tags and initiates the service worker. I have been trying to figure out how to reference these files. The current workaround I have is ./node_modules/PACKAGE_NAME/main.css ,
./node_modules/PACKAGE_NAME/sw.js, etc.

However, this doesn’t allow me to see the service worker due to the scope and seems unnecessary instead of ./

What string should I write to reference these files? Do I need to use a packager like Parcel (I’ve tried but I couldn’t get it to work)?

Issues with EJS path resolution after deployment to Vercel

I’m encountering a path resolution issue with my EJS templates after deploying my Express.js application to Vercel. The application works perfectly in my local environment, but after deploying, I’m receiving errors related to missing files.

Project Directory Structure

image of tree

Here’s the structure of my project:

Project (main folder)
    node_modules/ (Dependency files installed via npm)
    src/ (Main source directory)
        pages/ (Directory for EJS templates or views)
            index.ejs (Main page or template)
        public/ (Static files directory, including styles and images)
            styles.css (CSS file)
            og image.jpg (Open Graph image)
            small logo.png (Small logo image)
            large logo.png (Large logo image)
        partials/ (Directory for reusable EJS partials)
            header.ejs (Header partial)
            footer.ejs (Footer partial)
            script.ejs (Script partial)
            bootcss.ejs (Bootstrap CSS partial)
        index.js (Main application file, likely where Express.js is set up)
    nodemon.json (Configuration for Nodemon)
    .gitattributes (Git configuration file)
    .gitignore (Specifies files to ignore in Git)
    LICENSE (License for the project)
    package-lock.json (Specific version information for dependencies)
    package.json (Project configuration, including dependencies and scripts)
    README.md (Documentation for the project)
    vercel.json (Configuration for Vercel deployment)

Problem

When I deploy the application to Vercel, I receive the following error:


Error: /var/task/src/pages/index.ejs:29
    27|     <!-- Favicon -->
    28|     <link rel="icon" href="zorbis small logo.png" type="image/x-icon">
 >> 29|     <%- include ('src/partials/bootcss.ejs') %>       
    30|     </head>
    31|     <body>
    32|         <%- include ('partials/header') %>

Could not find the include file "src/partials/bootcss.ejs"
    at getIncludePath (/var/task/node_modules/ejs/lib/ejs.js:185:13)
    at includeFile (/var/task/node_modules/ejs/lib/ejs.js:311:19)
    at include (/var/task/node_modules/ejs/lib/ejs.js:701:16)
    at eval ("/var/task/src/pages/index.ejs":12:17)
    at index (/var/task/node_modules/ejs/lib/ejs.js:703:17)
    at tryHandleCache (/var/task/node_modules/ejs/lib/ejs.js:274:36)
    at exports.renderFile [as engine] (/var/task/node_modules/ejs/lib/ejs.js:491:10)
    at View.render (/var/task/node_modules/express/lib/view.js:135:8)
    at tryRender (/var/task/node_modules/express/lib/application.js:657:10)
    at Function.render (/var/task/node_modules/express/lib/application.js:609:3)

Things I’ve Tried

Updating Paths: Initially, I used paths like ../partials/file which worked locally but failed on Vercel. I have since changed the paths to src/partials/file but it still does not resolve the issue.
Path Formatting: I have tried including the file with and without the .ejs extension, but neither approach works on Vercel.

Directory Structure: I verified that the directory structure on Vercel matches my local setup, and all necessary files are included.

transformer.js error SyntaxError: Unexpected token ‘<', "<!doctype "… is not valid JSON, hugging face

text generator funtion

import { pipeline } from '@xenova/transformers';
export default async function textGen(input){
    let poet = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');
    let result = await poet(input, {
        max_new_tokens: 200,
        temperature: 0.9,
        repetition_penalty: 2.0,
        no_repeat_ngram_size: 3,
    });
    return result[0].generated_text
}

react code

import { useState } from 'react'
import './App.css'
import textGen from './hf'

function App() {
  const [text, setText] = useState('')
  const [out, setOut] = useState('')
  const handleClick = async(e) => {
    try{
      const result = textGen(text)
      setOut(result)
    }catch(e){
      console.log(e)
    }
  }
  return (
    <div>
        <h1>Text-Generator</h1>
        <input type="text" value={text} onChange={(e)=>setText(e.target.value)} placeholder='Enter text'/>
        <button onClick={handleClick}>Generate</button>
        {out && <p>{out}</p>}
    </div>
  )
}
export default App

your text
im trying to send dynamic input to text generator function, but its not working as expectd, i triedeverything but still getting above error

For the Drag and Drop Model [closed]

How can I implement a drag-and-drop file upload feature in React, without relying on any external libraries? I want to allow users to drag and drop an image file, manage the uploaded file’s state, and display a preview of the uploaded image.

I use the package of react name “DropZone” for making drag and drop file component but want to make this without using any external libraries.

import { useDropzone } from "react-dropzone";
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop: (acceptedFiles) => {
      formik.setFieldValue("image", acceptedFiles[0]);
    },
    accept: {
      "image/*": [".jpeg", ".pjpeg", ".png", "jpeg"],
      // "application/pdf": [],
    },
    multiple: false,
  });
   <div className="row mb-3">
        <label htmlFor="image" className="col-sm-2 col-form-label">
          Card Image
        </label>
        <div className="col-sm-10">
          <div
            {...getRootProps()}
            className={`dropzone ${
              isDragActive ? "dropzone-active" : ""
            } form-control ${
              formik.touched.image && formik.errors.image
                ? "input-error"
                : "input-bg-error"
            }`}
          >
            <input
              {...getInputProps()}
              name="image"
              id="image"
              onChange={(e) => {
                formik.setFieldValue("image", e.target.files[0]);
              }}
            />
            {isDragActive ? (
              <p>Drop the file here...</p>
            ) : (
              <p>Drag & drop your file here, or click to browse.</p>
            )}
          </div>
          {formik.touched.image && formik.errors.image && (
            <div style={{ color: "red" }}>{formik.errors.image}</div>
          )}
          {formik.values.image && (
            <div>
              <strong>Selected File:</strong> {formik.values.image.name}
            </div>
          )}
        </div>
      </div>

this is the how i use library for make the drag and drop functionality but i want to create this functionality without using any other library.