Any clue to implement textarea with autosuggestion and autocompletion?

Right now this textarea is pretty popular.

enter image description here

Users type something, LLM suggests something and users can type tab to adopt the suggestion.

Any clue how to implement the UI portion? Specifically, I am trying to implement a textarea component taking two parameters, content and suggestion.

  1. Content will be in black and suggestion will be in grey
  2. Suggestion will not be in the value of the textarea

Preserve inner shadow in container

I am working on a react project with Tailwind CSS where I have a div (with inner shadow) block acting a as a container to a scroll-able page. The page has elements that stick to the top upon scroll. This affects the inner shadow of the container. I can’t really change the position of the sticky elements as I want the scroll-able elements slowly fade away. I have pasted the snippets below. Thanks in advance.

Container div block:
<div className="mb-10 h-11/12 w-11/12 rounded-lg bg-white border shadow-inner-dark overflow-y-scroll">

Sticky block:

      <div className="sticky top-0 mb-6 h-40 w-full flex flex-col items-center">
        <div className="bg-white min-w-full text-center">
          <h1 className="text-4xl text-black font-silkscreen">Agent Hub </h1>
        </div>
        <div className="w-full grid place-items-center backdrop-blur-xl">
          <div className="w-full grid place-items-center  bg-gradient-to-t from-transparent to-white">
            <input
              type="text"
              className="mt-10 w-1/4 pl-6 py-2 rounded-full bg-black opacity-80 hover:shadow-2xl-dark text-white placeholder-gray-500 focus:outline-none transition duration:700"
              placeholder="Search..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
        </div>
      </div>

I tried meddling with the z-index but it wasn’t of much use.

Where do you suggest that keyboard constants be added to Javascript?

I saw this code here:

myCombobox.addEventListener('keydown', function(event) {
  if (event.key === 'Escape') {
    myCombobox.close();
    event.stopPropagation();
  }
});

My education and experience tells me that the code should be comparing a constant.

myCombobox.addEventListener(MouseEvents.KEYDOWN, function(event) {
  if (event.key === KeyboardConstants.ESCAPE) {
    myCombobox.close();
    event.stopPropagation();
  }
});

Is there a class or object in JavaScript that has a list of all the keys and keyboard events on it?

Other languages do this for very obvious specific reasons, to prevent typos, which prevent errors and non-functioning code.

Does Javascript love errors or do these classes exist and I couldn’t find them?

I tried to suggest this to TC39 and they said it’s not a language feature. Where do I suggest this feature?

Where do you suggest that keyboard constants be added to the Javascript language?

I saw this code here:

myCombobox.addEventListener('keydown', function(event) {
  if (event.key === 'Escape') {
    myCombobox.close();
    event.stopPropagation();
  }
});

My education and experience tells me that the code should be comparing a constant.

myCombobox.addEventListener(MouseEvents.KEYDOWN, function(event) {
  if (event.key === KeyboardConstants.ESCAPE) {
    myCombobox.close();
    event.stopPropagation();
  }
});

Is there a class or object in JavaScript that has a list of all the keys and keyboard events on it?

Other languages do this for very obvious specific reasons, to prevent typos, which prevent errors and non-functioning code.

Does Javascript love errors or do these classes exist and I couldn’t find them?

I tried to suggest this to TC39 and they said it’s not a language feature. Where do I suggest this feature?

Why am I receiving undefined in the renderer process even though the main process logs a valid payload?

I am working on an Electron.js application and trying to pass a token from the main process to the renderer process using ipcMain and ipcRenderer. However, when I attempt to log the received data in the renderer, it logs undefined.

ipcMain.on(IPC_ACTIONS.RECEIVE_TOKEN, async (event) => {
    if (mainWindow) {
        try {
            const response = await fetch("http://example.com/generate-token", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
            });

            const data: { token?: string } = await response.json();
            console.log("API response in main process:", data); 
    correctly, e.g., { token: "your-token-here" }

            if (data && data.token) {
                event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { token: data.token });
            } else {
                event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { error: "Token not received from the server" });
            }
        } catch (error) {
            console.error("Error during API call:", error);
            event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { error: error.message });
        }
    }
});

const ipcRenderer = (window as any).ipcRenderer;
const navigate = useNavigate();

ipcRenderer.on(IPC_ACTIONS.RECEIVE_TOKEN, (event: any, payload: any) => {
    console.log("Full payload received from main process:", payload);

    if (payload && payload.token) {
        console.log("Token received in renderer:", payload.token);
    } else if (payload && payload.error) {
        console.error("Error received:", payload.error);
    } else {
        console.error("Unexpected response received from main process:", payload);
    }
});

const handleButtonClick = () => {
    ipcRenderer.send(IPC_ACTIONS.RECEIVE_TOKEN);
    
};

Even though the console.log(“API response in main process:”, data); in the main process prints a valid token (e.g., { token: “your-token-here” }), the console.log(“Full payload received from main process:”, payload); in the renderer process logs undefined

Type ‘undefined’ is not assignable to type ‘menuItemProps[]’

I am working on next.js 15 project using typescript. The goal is to create nested Navigation.
When I run npm run dev it compiles correctly but when I try to build the project I am getting the following error:

Type error: Type 'menuListProps | undefined' is not assignable to type 'menuItemProps[]'.                                               
  Type 'undefined' is not assignable to type 'menuItemProps[]'.

  90 |                                  <li key={id}>                                                                                   
  91 |                                          <h2>{title}</h2>                                                                        
> 92 |                                          <MenuContent subMenuItems={subMenuItems} />                                             
     |                                                       ^                                                                          
  93 |                                  </li>                                                                                           
  94 |                          </>                                                                                                     
  95 |                  )  

data for menu:

const menuItems = [

    {
        id:getRandomInt(maxIntegerRandom),
        title:"a",
        subMenuItems: [
        {
            id:getRandomInt(maxIntegerRandom),
            title:"a1",
            subMenuItems: [
            {
                id:getRandomInt(maxIntegerRandom),
                title:"a11",
            },
            {
                id:getRandomInt(maxIntegerRandom),
                title:"a12",

            },
            ],
        },
        {
            id:getRandomInt(maxIntegerRandom),
            title:"a2",
            subMenuItems: [
            {
                id:getRandomInt(maxIntegerRandom),
                title:"a21",
            },
            ],
        },  
        ]

    }
]

types definitions:

type menuListProps = {
    passedMenuItems: menuItemProps[];
}

type menuItemProps = {
    id: number;
    title: string;

    shortTitle?: string;
    description?: string;
    shortDescription?: string;
    path?: string;
    image?: string;
    icon?: string;

    hideForHamburgerMenu?: boolean;

    subMenuItems?: menuListProps;
}

components:

function MenuContent(props: menuListProps){

    const { passedMenuItems } = props;

    let toRender = null;

    toRender = passedMenuItems.map( (menuItem) => MenuItem(menuItem) )

    return (
        <>
            <ul>
                {toRender}
            </ul>
        </>
    )
}

function MenuItem (props: menuItemProps){
    const { id, path, title, subMenuItems, hideForHamburgerMenu } = props;

    if (!("hideForHamburgerMenu" in props && hideForHamburgerMenu))
    {
        if ("subMenuItems" in props)
            return (
                <>
                    <li key={id}>
                        <h2>{title}</h2>
                        <MenuContent passedMenuItems={subMenuItems} />
                    </li>
                </>
            )

        else 
            return (

                <li key={id}>
                    <h2>{title}</h2>
                </li>
            )
    }
}

default function:

export default function MobileAsideMainMenu(){
    return(
        <>
            <MenuContent passedMenuItems={menuItems} />
        </>
    )
}

Please help me investigate what am I doing wrong?

NextJS 13+ Infinite Loops for routes with dynamic params

im having some issues with dynamic routing in Next. For example a route like /api/chat/[id] or would cause an infinite loop.

Here is the code:

"use client"

import React, {useEffect} from 'react';
import { useAuth } from "@/context/AuthContext";
import { useMsal } from "@azure/msal-react";

const TestPage = () => {
    const { acquireToken } = useAuth();
    const { accounts } = useMsal();

    useEffect(() => {
        const fetchData = async () => {
            const token = await acquireToken(accounts[0], "id");
            const res = await fetch("/api/clients/b00b24ba-2933-4d5e-919d-835cc05057a6", {
                method: "GET",
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            });

            const data = await res.json()
            console.log(data)
        }

        fetchData();
    })

  return (
    <div>
      <h1>Test Page</h1>
      <p>This is a test page for the application.</p>
    </div>
  );
};

export default TestPage;
import { NextRequest, NextResponse } from "next/server";
import { createServerSupabaseClient } from "@/lib/supabase/supabaseServer";

export async function GET(
  req: NextRequest,
  { params }: { params: { clientId: string } },
) {
  try {
    const supabase = createServerSupabaseClient();
    const { clientId } = params;

    const { data, error } = await supabase
      .from("clients")
      .select("*")
      .eq("id", clientId)
      .single();

    if (error) throw error;

    return NextResponse.json(data, { status: 200 });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

The path is app/api/clients/[clientId]/route.ts

Seems like nothing fancy.

My current fix is sending my dynamic id through a query instead of param

/api/clients/client?clientId=b00b24ba-2933-4d5e-919d-835cc05057a6

but i dont want to do that.

Am i missing something? I am somewhat new to Next.

Thanks!

Ive tried simple logging, expected a 200 but got a 508.

How do I setup a variable in a jest test environment if IFFE requires that variable, beforeAll in setupTest is not working

I have a scenario where one of my program files has an IFFE and wants to access a variable which is being set in a setupTest beforeAll block.

For example I have a component.js file which has an IFFE

const { getSandbox } = require("../env");

(async function () {
  const sandbox = getSandbox();
  const { pluralize } = sandbox;
  console.log(pluralize("word"));
})();

module.exports = {
  summingComponent: function (num1, num2, word) {
    return num1 + num2 + " " + getSandbox().pluralize(word);
  },
};

This above code is executed before I call setSandbox in the beforeAll

// setupTests.js

const sandbox = require("./__mocks__/sandbox");
const { setSandbox } = require("./env");


beforeAll(() => {
  setSandbox(sandbox)
});

The tests are breaking even before the tests start their execution, as the IFFE is being executed before the beforeAll block. How do I fix this. Can’t find a way.

I have created a ReplIt to reproduce this problem, this is mimicing my actual project.
https://replit.com/join/dnrlauoevi-mohammaddanishs

Pacman clone – Issue with HTML spritesheet canvas animation that is mapped dynamically to Javascript variables

I have a Pacman clone originally built with HTML5/CSS3/JQuery. I am trying to change the Pacman character (which was originally coded with a canvas arc method) to a custom animated character using requestAnimationFrame and a spritesheet. I was able to create the spritesheet and animate it without issue, then I was able to bind it to the variables that allow Pacman to move. However the strange issue I am noticing is that Pacman is only animated when he hits a wall or when the game is paused (hitting the ‘P’ key) or when he dies. Also note that I only mapped the spritesheet canvas for when Pacman goes right
(PACMAN_DIRECTION === 1)
All other directions are mapped to a static image file (I plan to update the rest later on). The code in question:

function animateRight() {
var canvas = document.querySelector("#animation-canvas");
var context = canvas.getContext("2d");
 
var myImage = new Image();
myImage.src = "https://i.ibb.co/ydGKpCR/spritesheet3.png";
myImage.addEventListener("load", loadImage, false);

var shift = 0;
var frameWidth = 33;
var frameHeight = 29;
var totalFrames = 3;
var currentFrame = 0;

function loadImage(e) {
  animate();
}

function animate() {

requestAnimationFrame(animate);

context.clearRect(0, 0, 33, 29);

context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
 
shift += frameWidth + 1;
 
  /*
    Start at the beginning once you've reached the
    end of your sprite!
  */

  if (currentFrame == totalFrames) {
    shift = 0;
    currentFrame = 0;
  }
 
  currentFrame++;

}
}

function positionCanvas(canvasId, x, y) {
  const position = document.getElementById(canvasId)
  var ctx = getPacmanCanevasContext();
  position.style.display = "block";
  position.style.left = x + "px";
  position.style.top = y + "px";
  animateRight();
}

function drawPacman() { 

var ctx = getPacmanCanevasContext();
  
ctx.beginPath();

if (PACMAN_DIRECTION === 1)  {
        positionCanvas("animation-canvas", PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2));
} else if (PACMAN_DIRECTION === 2) { 
    img = document.getElementById("pacmandown");          //down
    ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE); 
} else if (PACMAN_DIRECTION === 3 ) {                 //left & up
    img = document.getElementById("pacmanleft");
    ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE); 
} else {
    img = document.getElementById("pacmanup");
    ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE); 
}

  //ctx.arc(PACMAN_POSITION_X, PACMAN_POSITION_Y, PACMAN_SIZE, startAngle, endAngle, false);
  //ctx.lineTo(lineToX, lineToY);
  //ctx.fill();
  ctx.closePath();
}

I don’t believe any other functions in the game files could be causing the issue, as I left them as-is for the most part. I also uploaded the game online so it can be tested:

https://ggalvin.itch.io/pacman-game-test

Javascript (for loop for linked list -> array questions) [closed]

If you scroll to the bottom of this page https://eloquentjavascript.net/04_data.html you will see ‘Display Hints’ under the heading ‘A List’. Click that and then you will see hints where there is a line of code that I don’t understand:

Code:

for (let node = list; node; node = node.rest) {}

Why is the 2nd part of the for loop say nothing but ‘node’? Is this the same as saying node == true?
The last part of the for loop says ‘node.rest’. What does that do? Does .rest mean anything specific?

The book gives an explanation but it’s not enough for me to grasp it so I’m hoping someone can break it down in a simple manner

Git ignore does not recognize a node modules file, I’m not able to push my file to git because its exceeds file size limit

I want to push my project to Github, and I have a gitignore file to track my node modules so it won’t be pushed to github.
But I’m getting an error pushing my files to github because a folder in node_modules exceeds github file size limit. But my node_modules is also in my .gitignore. I don’t know my git is not able to track the file.

remote: error: File node_modules/@next/swc-win32-x64-msvc/next-swc.win32-x64-msvc.node is 117.24 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.

I’ll be glad to get help on this so I can push my project to github.

regex to match HTML tag

I would like to match an HTML <p ...> tag when the 1st char after closing tag > is in lower case, I saw some answers on this site to match p tag with attribute, but not a simple p tag (<p>), what change I need to do to match both?
Ex:

<p class="calibre1">All the while I was
<p>All the while I was
<p class="calibre1">all the while I was
<p>all the while I was

the regex should match the last 2 tags, the code that I have (/</?([^p](s.+?)?|..+?)>[a-z]/) matches only the 3rd, not the 4th tag

Using vite with jsx in .js files

I know JSX should be written in .jsx or .tsx files. But I just joined a project and want to migrate to vite, and they used .js for years now. There is not a single .jsx file in the project. How can I make vite accept jsx in .js files?

vite.config.js:

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

export default defineConfig({
    envDir: 'build-config',
    build: {
        outDir: '../dist',
        rollupOptions: {
            output: {
                entryFileNames: 'client.min.js'
            }
        }
    },
    plugins: [
        checker({typescript: true}),
        react({
            devTarget: "es2022",
            jsxImportSource: '@emotion/react',
            include: ['**/*.js', '**/*.jsx'], // Include both .js and .jsx files
            babel: {
                plugins: [
                    '@emotion/babel-plugin'
                ]
            }
        }),
        svgr(),
        { // being desperate
            name: 'custom-jsx',
            enforce: 'pre',
            transform(code, id) {
                if (id.endsWith('.js')) {
                    return {
                        code: code.replace(//* @jsxImportSource *//, ''),
                        map: null
                    };
                }
            }
        }
    ],
    server: {
        open: true,
        hot: true,
        port: 8080,
        watch: {
            usePolling: true
        }
    },
    optimizeDeps: {
        include: ['react', 'react-dom'] // Add any other dependencies you need to pre-bundle
    },
    esbuild: {
        loader: {
            '.js': 'jsx', // Set the loader for .js files to jsx
        },
    },
});

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

I’d prefer swc, but the result was the same for both transpilers

OpenAI API Issues Integration to JS

I’m currently testing integrating OpenAI’s GPT API on a small-scale project that involves index.html(web-page), index.cjs (where the code is run and was previously index.js) And then the necessary files such as the .env , package-lock.json, node_modules , and package.json. I’ve done the following commands via gitbash already:
-npm install dotenv
-npm install openai

I declared dotenv at the beginning of my index.cjs file and I correctly set up my API key in the .env by the following format: OPENAI_API_KEY = example_api

I did the following troubleshooting steps:

  1. verified .env file is present in under the root project directory and that the API key is correctly configured.
  2. Attempted to print the API key to the console but got “undefined”.
    3.Attempted different API keys from my account and a friends whom we both have no usage and are on a free plan. I used the gpt-3.5-turbo model, somehow I got error 429 on both given that neither has ever used it.
    4.Restarted VS code to make sure changes to the .env file and environment variable were applied.
    5.Restarted GitBash.
  3. Got the following errors: “RateLimitError: 429″(Exceeding quota), “NotFoundError: 404″(Model unavailable when I had used GPT-4”, and “AuthenticationError”(incorrect API key).

What I Tried:
I checked my .env file to ensure the OPENAI_API_KEY is correctly set and loaded using the dotenv package.
I logged the API key to the console to verify it was being loaded correctly.
I tested the connection to OpenAI’s API by running a script that attempts to generate a haiku using the gpt-3.5-turbo model.
I also tried using different API keys and different OpenAI models to see if they work under the free plan.
I checked my OpenAI dashboard to confirm my quota usage was at 0 and that I was on the free plan with no cost.
What I Expected:
I expected the OpenAI API key to load correctly from the .env file.
I anticipated the haiku generation to succeed, without hitting rate limits or quota errors.
I thought that the gpt-3.5-turbo model would work under the free tier without exceeding usage limits, given that no cost had been incurred yet.
I expected to see the generated haiku printed in the console if everything was set up correctly.
What Actually Happened:
The API key loaded correctly, as confirmed by the logged output.
However, despite having no usage cost, I received an “insufficient quota” error (status 429) indicating that I had exceeded my current quota, even though no usage had occurred.
The model I selected (gpt-3.5-turbo) should be available on the free plan, but I encountered a rate limit error suggesting a quota issue.
No haiku was generated due to this error, and instead, the error message pointed to an issue with my plan or quota. The following code:

index.cjs:

// Load environment variables before anything else
require('dotenv').config();


// Import the OpenAI client
const { OpenAI } = require('openai');

// Initialize the OpenAI client with the API key from the environment
const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,  // The API key is automatically read from the .env file
});

async function generateHaiku() {
    try {
        // Call OpenAI's API to generate a haiku based on a prompt
        const completion = await openai.chat.completions.create({
            model: "gpt-3.5-turbo", // Using GPT-3.5 for the free plan
            messages: [
                { role: "system", content: "You are a helpful assistant." },
                {
                    role: "user",
                    content: "Write a haiku about recursion in programming.",
                },
            ],
        });

        // Log the generated haiku
        console.log("Generated Haiku:", completion.choices[0].message.content);
    } catch (error) {
        // Catch any errors and log them
        console.error("Error generating haiku:", error);
    }
}

// Call the function to generate the haiku
generateHaiku();

Tldraw and React portal, change handler issue

Have a problem:
I use Tldraw editor in my project, and have “full screen” mode for it. When user has the editor full-screened, he draws or removes some shapes and quits full screen mode.
Fullscreen mode implemented using ReactDOM.createPortal and styles like “position: fixed”
Tldraw editor has event listener that handles all the changes, which after that sets some states.

First of all I notice that without using react portal everything seems fine.
The problem I have:

  1. User enters fullscreen mode
  2. User removes something using eraser tool, the state in parent component updates, (console.log(editor.getCurrentPageShapes()) here works like it has to, and displays correct data, an empty data structure)
  3. Quits fullscreen mode (editor now renders again without portal, state is used to set data to editor)
  4. Doesn’t see any changes. There are still those shapes that were here before erasing

Drawing works correct in both modes, all the changes save correctly. That’s why I’m not sure the problem is in state saving. It seems like either Tldraw considers erasing as something else (handleChange is just state saving, and according to console.log it should work as expected), or react portal creates some restrictions.

Code example (pastebin)