Event Listener Not Working After Page Transition with Barba.js

I’m using Barba.js for handling page transitions in my website. I have a navigation menu that opens when clicking on a div with the class nav-btn. Everything works perfectly when the page is loaded for the first time, but after transitioning to another page using Barba.js, the click event listener for the navigation menu button no longer works till refresh the page.

Here’s the relevant part of my code:

function navOpener() {
  let navbtn = document.querySelector(".nav-btn");

  if (navbtn != null) {
    console.log("Navopener running...");
    console.log(navbtn);
    navbtn.addEventListener("click", function () {
      console.log("nav opener clicked");
      // Other logic here...
    });
  }
}

When I check the console, I see the message “Navopener running…” and navbtn element after the transition so i am sure navbtn is ok, but the click event listener doesn’t trigger anymore, and the console.log(“nav opener clicked”) never shows up. I am running all the functions beforeEnter. And as i said when refresh the page everything works perfectly.

ESLint VSCode plugin not working with eslint.config.mjs

I have an Express.js API, and I’m using the latest version of ESLint (9.10.0). I’ve been trying to enable code warnings and errors in VS Code, but when I run npx eslint --init, ESLint creates an eslint.config.mjs file instead of a .eslintrc file, even though the ESLint plugin documentation mentions that it works with .eslintrc.

I also tried creating my own .eslintrc.js file manually with the following configuration:

module.exports = {
    env: {
        commonjs: true,
        es2021: true,
        node: true
    },
    extends: [
        'airbnb-base'
    ],
    parserOptions: {
        ecmaVersion: 12
    },
    rules: {}
};

However, it still doesn’t work. VS Code is not showing any warnings or errors from ESLint. I’ve tried restarting VS Code and reloading the extensions, but nothing seems to help.

Any suggestions on how to resolve this?

How to add a string only after the last match of a regex.replace (JavaScript)

I’m basically trying to reformat one string to another.
One of my functions can match certain areas of the original string and reformat them into a “properties” section which consists of “—” before and after it. I managed to add “—” before all the matches, but how would I go about only adding the second string after the last match of the replace function?

I tried many approaches but failed horribly. the closest I got was when it added “—” after the first match.

How to replace a quoted string with a modified version of it JQuery/Javascript

I’m looking for a solution to replace all quoted strings in a phrase with the same quoted strings but in a modified version.

This is an example of what I mean:

var str = 'name="benson"; password="1234"';

//Expected output: name=--"benson"--; passowrd=--"1234"--


var str = 'I "love" and I like "programming"';

//Expected output: I --"love"-- and I like --"programming"--
// and so on

Following is my approach, I’m almost there but it seems I’m missing something. I have spent quite some time on it.

var str = 'name="benson"; password="1234"';

var searching = str.match(/".+?"/gi); 

var result = str.replace(/".+?"/gi, "--" + searching + "--");

$( "p" ).html(result);

// out put: name=--"benson","1234"--; password=--"benson","1234"--

Execute JS for MapBox via Playwright

My goal is to be able to zoom in on a MapBox map when running automated web tests using playwright.

I have found that in the browsers console i can type map.zoomTo(15) and the map zoom in exactly how I want it to. However, when I try and do this in a test using:

page.evaluate("""
          map.setZoom(15);
              """)

I get the error playwright._impl._errors.Error: ReferenceError: map is not defined

Tring,

  page.evaluate("""
            window.map.setZoom(15);
                """)

I get the error playwright._impl._errors.Error: TypeError: Cannot read properties of undefined (reading 'setZoom')

I don’t understand why Playwright evaluate is different to issuing it on the browsers console.

The second example looks like map is defined so to me means the map should be initialized, but just doesn’t have access to the setZoom function.

Any help would be greatly apricated, reading the playwright doc makes it sound like it would be working.

Example code:

from playwright.sync_api import sync_playwright

pw = sync_playwright().start()
browser = pw.chromium.launch(headless=False, slow_mo=0)

browser_context = browser.new_context()
page = browser_context.new_page()

page.goto("http://127.0.0.1/map")

page.evaluate("""
          map.setZoom(15);
              """)

I don’t have a public facing version of the page available to me.

Why do negated character classes in JavaScript Regular Expressions traverse newlines even with multiline mode disabled

Encountered a strange behaviour with negated charatcer classes traversing newlines without m/multiline provided.

> node
Welcome to Node.js v22.7.0.
Type ".help" for more information.
> 'abcnabcnabcn'.replace(/b[^z]+/g, '')
'a'
> 'abcnabcnabcn'.replace(/b[^zn]+/g, '')
'ananan'

I expected that the first result would only be the case when the m multiline flag is enabled:

> 'abcnabcnabcn'.replace(/b[^z]+/gm, '')
'a'

Is this a bug, or is this expected? If it is expected, what is the reasoning?

Convert FormData to a list of objects

I have a form where a set of fields is repeated a couple of times. This form is then send as FormData (https://developer.mozilla.org/en-US/docs/Web/API/FormData) to the backend.

My current solution is to name the fields in the form like this:

<input name="firstname" />
<input name="lastname" />
<input name="firstname" />
<input name="lastname" />

Then on the backed I can convert FormData to an array of objects like this:

const firstnames = formData.getAll('firstnames')
const lastnames = formData.getAll('lastnames')
const persons = []

for (let i = 0; i < firstnames.length; i++) {
    persons.push({
       firstname: firstnames[i],
       lastname: lastnames[i]
     })
}

Since this seems to be a pretty standard scenario, I am just guessing that I am not on the right track to convert form data to a list of objects like this. How can this be done?

Can’t resolve ‘@clerk/shared/router’ in @clerk/elements

I am using Clerk Element on my sign-up flow for my React (typescript) webapp. Today my app stopped working with error:

./node_modules/@clerk/elements/dist/chunk-7WFXAEQQ.mjs:90:1
Module not found: Can't resolve '@clerk/shared/router'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/@clerk/elements/dist/react/sign-up/index.mjs
./src/<my app code>
 ⨯ ./node_modules/@clerk/elements/dist/chunk-7WFXAEQQ.mjs:90:1
Module not found: Can't resolve '@clerk/shared/router'

My sign-up page has the following imports:

import * as Clerk from '@clerk/elements/common'
import * as SignUp from '@clerk/elements/sign-up'

Any ideas on how to debug further?

How to fix the shadcn hover card position bug?

I’m trying to put this hovercard on trigger of my sidebar tab but when the hovercard appears it gets positioned below the relative positioned element. I’m new to next.js. How can I make it work? The other components of shadcn like Dropdown menu does not show this behaviour.

Behaviour

Card positioned below

//Sidebar.tsx

<HoverCard key={index}
  openDelay={0}
  closeDelay={0}
  onOpenChange={(open) => setIsHoverCardOpen(open)}>
 <HoverCardTrigger>
  <SidebarItem title={title} icon={Icon} altIcon={altIcon} href={href} path={path} type={type} className={isHoverCardOpen ? "bg-white-background" : ""} />
 </HoverCardTrigger>
 <HoverCardContent
   align="end"
   side="right"
   alignOffset={-50}
   sideOffset={16}
   className="p-2 border w-[220px] border-[#F0EDF9] rounded-[20px] bg-white"
    style={{
     boxShadow: "0px 2px 16px -4px rgba(0, 0, 0, 0.12)",
    }}>
   <SidebarDropdown />
 </HoverCardContent>
</HoverCard>


//SidebarDropdown.tsx
export const SidebarDropdown = () => {
  return (
    <div
      className="flex flex-col items-start gap-3"
    >
      {dropDownItems.map(({ title, Icon, href }, index) => {
        return (
          <DropDownItem key={index} title={title} icon={Icon} href={href} />
        )
      })}
    </div>
  )
}

//hover-card.tsx

const HoverCardContent = React.forwardRef<
  React.ElementRef<typeof HoverCardPrimitive.Content>,
  React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
  <HoverCardPrimitive.Content
    ref={ref}
    align={align}
    sideOffset={sideOffset}
    className={cn(
      "z-[50] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    )}
    {...props}
  />
))

//EvaluateBanner.tsx
export const EvaluateBanner = ({icon,title,cta_text,intent}:BannerPorps) => {
  
  return (
    <GradientWrapper>
        <div
          className="relative overflow-hidden flex flex-col md:flex-row items-end justify-end h-full w-full md:items-center md:justify-center gap-6 self-stretch py-4 pl-[22px] md:pl-[140px] pr-[22px] rounded-[22px] bg-white"
          style={{
            boxShadow: "0px 2px 8px -4px rgba(0, 0, 0, 0.08)",
          }}
        >
          <Image
          src={icon}
          alt="GradeReport"
          width={100}
          height={100}
          className="absolute rotate-[14.865deg] md:rotate-0 left-[-5px] bottom-[-14.274px] md:bottom-0 md:left-[20px]"
        />
          <p className="flex-1 text-[28px] text-neutral-900 font-extrabold leading-normal">
            {title}
          </p>
          <EvaluateButton label={cta_text} intent={intent}/>
        </div>
    </GradientWrapper>
  )
}

const GradientWrapper = ({ children }: { children: React.ReactNode }) => {
  return (
    <div className="bg-gradient-to-r from-[#FFB0383D] via-[#FF63633D] to-[#6100FF3D] p-[1px] rounded-[23px]">
      {children}
    </div>
  )
}

i tried increasing the z-index of the hover caard but it didnot worked.

Scheduled SuiteScript to load a CSV from File Cabinet and append saved search results to CSV and save

I am attempting to create a historical csv backup (appended rather than overwritten) to our file cabinet using a saved searches results (on a once a week schedule).

I know its possible to write a saved searches results to a CSV (using task), but I’m not sure how I can append instead (maybe using file.appendline?). Here is what I’ve come up with which results in the appended data being “task.SearchTask” instead of the saved search results:

/**
 * @NApiVersion 2.1
 * @NScriptType ScheduledScript
 */
define(['N/file', 'N/task'],
    /**
 * @param{file} file
 * @param{task} task
 */
    (file, task) => {

        /**
         * Defines the Scheduled script trigger point.
         * @param {Object} scriptContext
         * @param {string} scriptContext.type - Script execution context. Use values from the scriptContext.InvocationType enum.
         * @since 2015.2
         */

        //[file ID, Saved Search ID]
        const keys = [
            [72567, 1701]
        ]

        const execute = (scriptContext) => {
            for(var i = 0; i < keys.length; i++) {
                var searchTask = task.create({
                    taskType: task.TaskType.SEARCH,
                    savedsearchId: keys[i][1]
                });

                var csvFile = file.load({
                    id: keys[i][0]
                });

                //This probably doesn't work...
                csvFile.appendLine({
                    value: searchTask
                });

                csvFile.save();
            }
        }

        return {execute}

    });

Any assistance would be appreciated!

Trouble configuring ESLint v9 with React and TypeScript [duplicate]

I started a new project using Vite, with React and TypeScript. I’ve set up my ESLint configuration in eslint.config.js as follows:

import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh'; // Make sure to import all plugins

export default [
  {
    ignores: ['dist'],
    overrides: [
      {
        extends: [
          js.configs.recommended,
          'eslint:recommended',
          'plugin:@typescript-eslint/recommended',
          'plugin:react-hooks/recommended',
          'plugin:react/recommended',
          'plugin:react/jsx-runtime',
          'prettier', // `eslint-config-prettier` is usually just referred to as `prettier`
        ],
        files: ['**/*.{ts,tsx}'],
        languageOptions: {
          ecmaVersion: 2021,
          globals: globals.browser,
        },
        plugins: ['react-hooks', 'react-refresh'], // Ensure all plugins are listed here
        rules: {
          ...reactHooks.configs.recommended.rules,
          'react-refresh/only-export-components': [
            'warn',
            { allowConstantExport: true },
          ],
        },
      },
    ],
  },
];

However, I’m encountering the following error in my file:

ConfigError: Config (unnamed): Key “overrides”: This appears to be in eslintrc format rather than flat config format.

Could someone help me understand why this is happening? It seems like my ESLint config is using an outdated format, but I’m not sure how to resolve this.

I’d greatly appreciate any guidance on fixing this issue!

Error empty files storage Supabase with NextJS

I am trying to do something very basic, just uploading images to my storage but they are empty

enter image description here

This is how I upload it to Supabase

async function uploadImage(file) {
  log(file)
  const fileExt = file[0].filename.split('.').pop();
  const fileName = `${Date.now()}.${fileExt}`;
  const { data, error } = await supabase
    .storage
    .from('images') // Nombre del bucket
    .upload(fileName, file[0]);

  if (error) {
    console.error('Error uploading image:', error);
    return null;
  }

  const { publicURL, error: urlError } = supabase
    .storage
    .from('images')
    .getPublicUrl(fileName);
  console.log(publicURL)
  console.log("###")
  if (urlError) {
    console.error('Error getting public URL:', urlError);
    return null;
  }

  return publicURL;
}

This is where I am executing this:

app.post('/api/posts', upload.fields([{ name: 'image', maxCount: 1 }, { name: 'video', maxCount: 1 }]), async (req, res) => {
    try {
      const { title, content } = req.body;
    //   log(req.image)
    //   log(req.content)
      let image = null;
      let video = null;
  
      if (req.files['image']) {
        // image = `/uploads/${req.files['image'][0].filename}`;
        const publicImageUrl = await uploadImage(req.files['image']);
        image = publicImageUrl; // Use the public URL
        log('Image URL obtained:', publicImageUrl);
        log(`Imagen subida: ${image}`);
      }

What am I doing wrong? Thank you

WebSocket Connection Fails with “WebSocket is closed before the connection is established” Error

I’m having trouble with establishing a WebSocket connection in my React application. Despite my backend WebSocket server working as expected (verified using Postman), my frontend consistently fails to connect. I’m receiving the following error in the browser console:

SocketClient.ts:36 WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: WebSocket is closed before the connection is established.

Here’s the relevant setup for my frontend and backend.

Frontend Code
1 . src/services/socketClient.ts

import { io, Socket } from "socket.io-client";

class SocketClient {
  private socket: Socket | null = null;

  connect(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!process.env.REACT_APP_SOCKET_HOST) {
        reject("Socket host is not defined.");
        return;
      }

      this.socket = io(process.env.REACT_APP_SOCKET_HOST as string, {
        transports: ["websocket"],
        reconnection: true,
      });

      this.socket.on("connect", () => resolve());
      this.socket.on("connect_error", (error) => {
        console.error("Socket connection error:", error);
        reject(error);
      });
    });
  }

  disconnect(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.socket) {
        this.socket.disconnect();
        this.socket.once("disconnect", () => {
          this.socket = null;
          resolve();
        });
      } else {
        reject("No socket connection.");
      }
    });
  }

  emit(event: string, data: any): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.socket) return reject("No socket connection.");

      this.socket.emit(event, data, (response: any) => {
        if (response?.error) {
          return reject(response.error);
        }
        resolve();
      });
    });
  }

  on(event: string, callback: (data: any) => void): void {
    if (!this.socket) throw new Error("No socket connection.");
    this.socket.on(event, callback);
  }
}

export default new SocketClient();

2 .src/redux/slices/socketClient/socketSlice.ts

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import SocketClient from "../../../services/SocketClient";

const socketClient = SocketClient;

interface SocketState {
  connectionStatus:
    | "idle"
    | "connecting"
    | "connected"
    | "disconnected"
    | "failed"
    | "disconnecting";
}

const initialState: SocketState = {
  connectionStatus: "idle",
};

export const connectToSocket = createAsyncThunk("socket/connect", async () => {
  try {
    await socketClient.connect();
  } catch (error) {
    throw new Error("Failed to connect to the socket server");
  }
});

export const disconnectFromSocket = createAsyncThunk(
  "socket/disconnect",
  async () => {
    try {
      await socketClient.disconnect();
    } catch (error) {
      throw new Error("Failed to disconnect from the socket server");
    }
  }
);

const socketSlice = createSlice({
  name: "socket",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(connectToSocket.pending, (state) => {
      state.connectionStatus = "connecting";
    });
    builder.addCase(connectToSocket.fulfilled, (state) => {
      state.connectionStatus = "connected";
    });
    builder.addCase(connectToSocket.rejected, (state, action) => {
      state.connectionStatus = "failed";
      console.error("Socket connection error:", action.error.message);
    });
    builder.addCase(disconnectFromSocket.pending, (state) => {
      state.connectionStatus = "disconnecting";
    });
    builder.addCase(disconnectFromSocket.fulfilled, (state) => {
      state.connectionStatus = "disconnected";
    });
    builder.addCase(disconnectFromSocket.rejected, (state, action) => {
      state.connectionStatus = "failed";
      console.error("Socket disconnection error:", action.error.message);
    });
  },
});

export default socketSlice.reducer;
  1. src/App.tsx
import { BrowserRouter as Router } from "react-router-dom";
import AppRoutes from "./routes/Routes";
import { useDispatch } from "react-redux";
import { AppDispatch } from "./redux";
import { useEffect } from "react";
import {
  connectToSocket,
  disconnectFromSocket,
} from "./redux/slices/socketClient/socketSlice";

function App() {
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    const connect = async () => {
      try {
        await dispatch(connectToSocket()).unwrap();
      } catch (error) {
        console.error("Socket connection error:", error);
      }
    };

    connect();

    return () => {
      dispatch(disconnectFromSocket());
    };
  }, [dispatch]);

  return (
    <Router>
      <AppRoutes />
    </Router>
  );
}

export default App;

Backend Code

  1. index.js

const mongoose = require('mongoose');
const app = require('./app');
const config = require('./config/config');
const logger = require('./config/logger');
const setupSocketServer = require('./services/socket.io');
const harvester = require('./services/processedDataServices/saveTodb.service');

let server;
mongoose.connect(config.mongoose.url, config.mongoose.options).then(() => {
  logger.info('Connected to MongoDB');
  server = app.listen(config.port, () => {
    logger.info(`Listening to port ${config.port}`);
    harvester.startOnchangeServices();
  });
  setupSocketServer(server);
});

const exitHandler = () => {
  if (server) {
    server.close(() => {
      logger.info('Server closed');
      process.exit(1);
    });
  } else {
    process.exit(1);
  }
};

const unexpectedErrorHandler = (error) => {
  logger.error(error);
  exitHandler();
};

process.on('uncaughtException', unexpectedErrorHandler);
process.on('unhandledRejection', unexpectedErrorHandler);

process.on('SIGTERM', () => {
  logger.info('SIGTERM received');
  if (server) {
    server.close();
  }
});
  1. services/socket.io.js
const socketIo = require('socket.io');
const logger = require('../config/logger');

module.exports = (server) => {
  const corsOptions = {
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true,
  };
  const io = socketIo(server, {
    cors: corsOptions,
  });

  io.on('connection', (socket) => {
    logger.info(`User connected: Socket ID - ${socket.id}`);

    // Handle disconnection
    socket.on('disconnect', () => {
      logger.info(`User disconnected: Socket ID - ${socket.id}`);
    });
  });
};

My frontend code is using socket.io-client to connect to the WebSocket server. The backend WebSocket server is working fine (verified using Postman).

What I’ve Tried:
Verified that the WebSocket server is up and running.
Checked the URL and environment variables.
Ensured the server code handles connections and disconnections correctly.

Any guidance on how to resolve this issue or what might be going wrong would be greatly appreciated!

Type assertion in JSDoc VScode

/**
 * @typedef Animal
 * @property {string} noise
*/

/**
 * @typedef Duck
 * @property {string} noise
 * @property {number} wings
*/

/**
 * @param {Animal} a
 */
function TestAnimal(a) { console.log(a.noise) }

// 0. warning
TestAnimal({ noise: 'quack', wings: 2 })  // Object literal may only specify known properties, and 'wings' does not exist in type 'Animal'.ts(2353)

// 1. multiple
const bear = { noise: 'roar', feet: 4 }
TestAnimal(bear)

// 2. single, extra parentheses
TestAnimal(/** @type {Animal} */({ noise: 'meow', tails: 1 }))

Are these the only 2 ways to type assert without warning in VSCode? I find both unwieldy and something closer to (0) would be much preferred.

Another solution I’ve come across is

/**
 * @typedef {{
 *   noise: string
 *   [others: string]: any
 * }} Animal
*/

but it’s less than ideal since I have to apply it to all typedef I might extend from and defeats its purpose in some cases

I dont want to use

/** @typedef {Duck | Bear | Cat} Animal */

either, since this requires Animal to keep track of everything that extends it and doesn’t allow other users to extend it

rehype-mdx-code-props is not working correctly with nextjs app router

I’m using nextjs 14, using app router.
I was trying to use the mdx in nextjs, for creating documentation in which I require to add code blocks for reference.
now I found that rehype-mdx-code-props can help on passing the props to my component.

```js filename="demo.js" filetype="js"
function sayHello(name) {
  console.log('Hello', name);
}
```

And in the mdx-components.tsx which is inside the src folder I’ve written this:

export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    h1: ({ children }) => (
      <h1 className="text-3xl font-bold tracking-tight">{children}</h1>
    ),
    img: (props) => (
      <Image
        sizes="100vw"
        style={{ width: "100%", height: "auto" }}
        {...(props as ImageProps)}
      />
    ),
    code: ({children}) => {
        return <MyCodeBlock children={children} />;
    },
    p: ({ children }) => (
      <p className="text-sm text-muted-foreground">{children}</p>
    ),
    ...components,
  };
}

problem is the line code: ({children}) part, here I tried to do the console log for the props being passed but only children and classname is being passed as props, so this is causing filename and filetype arguments not getting passed to component.

How do I get filename and filetype as arguments to my method?

for ref next.config.mjs:

import createMDX from '@next/mdx'
import remarkGfm from 'remark-gfm'
import rehypeMdxCodeProps from 'rehype-mdx-code-props'

/** @type {import('next').NextConfig} */
const nextConfig = {
  // Configure `pageExtensions` to include markdown and MDX files
  pageExtensions: ['js', 'jsx', 'md', 'mdx', 'ts', 'tsx'],
  // Optionally, add any other Next.js config below
}
 
const withMDX = createMDX({
  // Add markdown plugins here, as desired
  options: {
    remarkPlugins: [remarkGfm],
    rehypePlugins: [rehypeMdxCodeProps],
    },
})
 
// Merge MDX config with Next.js config
export default withMDX(nextConfig)