Change Badge Color In JS By Value

I’m new in javascript. I try to make the badge color change according to the value. I’ve tried but the output is error badge

<th>
                            <select class="select2-placeholder form-control" id="sIsLocked">
                                <option value="">Pilih</option>
                                <option value="false">Un Locked</option>
                                <option value="true">Locked</option>
                                    
                            </select>
                        </th>`your text`
                            render: function (data, type, row, meta) {
                                switch (data) {
                                    case false:
                                        return '<span class="badge bg-success">Un Locked</span>';
                                    case true:
                                        return '<span class="badge rounded-pill bg-secondary">Locked</span>';
                                    default:
                                        return '<span class="badge badge-danger badge-pill">Error!</span>';
                                        
                                }
                            }

Is the meatamask API incompatible with tron chains?

Why am I able to transfer USDT using the Metamask interface standard, but not on the tron chain? They are all managed in the same wallet, do I need to do different API docking? What is the difference between TRC20 and ERC20? Is it true?

I have read the official Meatamask API and implemented USDT transfer. I hope to make USDT transfers through the tron chain as well.

Array iteration management [closed]

I am trying to do an iteration to an array to validate data, The problem is that when I do the if(){}else{} For validation, the if is executed as else, both.

what I’m trying to do is, validate data to prevent repeated data from being inserted

  const myData = [
     {id: "001", nombre: "pedro",   apellido: "mejia",   codigo: "0012325", estado: "Activo"},
     {id: "002", nombre: "gristan", apellido: "smill",   codigo: "0022325", estado: "Activo"},
     {id: "003", nombre: "marco",   apellido: "rosario", codigo: "0032325", estado: "Desativado"},
     {id: "004", nombre: "juan",    apellido: "vergobe", codigo: "0042325", estado: "Activo"},
     {id: "005", nombre: "salomon", apellido: "mende",   codigo: "0052325", estado: "Desativado"},
  ]
var myclick = false;
  for (let index = 0; index < myData.length; index++) {
    const element = myData[index];
    var resultadoArray = element.id;
   if(myclick == false){
     if(resultadoArray != "003"){
          console.log('true');
          myclick = true;
        }else{
          console.log('fase');
          myclick = true;
      }
    }
  }

Swiperjs breakpoints doesn’t apply when reach the breakpoints

I’m using swiperjs and I want to make the swiper responsive by using breakpoints property. However, the default value of slidesPerView the isn’t applied when the screen reaches a smaller value than breakpoint. When I test in a separate html file, the breakpoints work fine but not in my laravel project. I’m using cdn as the source for swiper, here’s my code:

My js to initialize the swiper

var swiper = new Swiper('.history-swiper', {
    // Optional parameters
    slidesPerView: 2,
    spaceBetween: 10,

    breakpoints: {
        975: {
            slidesPerView: 2
        }
    },
  
    // If we need pagination
    pagination: {
      el: '.swiper-pagination',
      clickable: true,
    },
  
    // Navigation arrows
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
  
    // And if we need scrollbar
});

var swiper_index = new Swiper('.index-swiper', {
    // Optional parameters
    slidesPerView: 2,
    spaceBetween: 10,

    breakpoints: {
        975: {
            slidesPerView: 3,
            spaceBetween: 20,
        }
    },

    // If we need pagination
    pagination: {
        el: '.swiper-pagination',
    },

    // Navigation arrows
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },

    // And if we need scrollbar
});

my HTML for the swiper which have some cards as the swiper items

<div class="swiper index-swiper">
            <!-- Additional required wrapper -->
            <div class="swiper-wrapper">
              <!-- Slides -->
                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                              <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                              <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quae consectetur culpa quam nisi. Blanditiis sed officiis, corporis ullam maiores, magnam aperiam qui quasi amet eveniet quia quas cumque error dolore!
                            </p>
                              <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>

                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                            <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                            <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Explicabo mollitia sapiente et dicta fuga quaerat accusantium, omnis eligendi dolorem fugit facere dolores recusandae ea quisquam vero voluptatem reprehenderit? Libero, natus.
                            </p>
                            <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>

                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                            <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                            <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Explicabo mollitia sapiente et dicta fuga quaerat accusantium, omnis eligendi dolorem fugit facere dolores recusandae ea quisquam vero voluptatem reprehenderit? Libero, natus.
                            </p>
                            <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>

                <div class="swiper-slide">
                    <div class="card">
                        <div class="img-wrapper">
                            <img src="{{ asset('photos/anh1.jpeg') }}" class="card-img-top" alt="...">
                        </div>
                        <div class="card-body">
                              <h5 class="card-title">Dịch vụ chăm sóc sức khỏe A</h5>
                              <p class="card-text">Dịch vụ này mang đến rất nhiều những tư vấn hữu ích cho sức khỏe của khách hàng....Hơn nữa Khách hàng còn được trải nghiệmrất nhiều những tiện ích khác nữa...
                            </p>
                              <a href="#" class="fw-bold">Xem chi tiết</a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="swiper-button-prev"></div>
            <div class="swiper-button-next"></div>

        </div> 

Here’s my css for cards and swiper

.card{
    margin: 0 .5em;
    box-shadow: 2px 6px 8px 0 rgba(22, 22, 26, 0.18);
    border: none;
}

.card .img-wrapper {
    max-width: 100%;
    height: 13em;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

img{
    max-height: 100%;
}

.carousel-custom{
    max-width: 945px;;
}

.card-img-top{
    object-fit: none;
}

.card-text {
    display: -webkit-box;
    -webkit-line-clamp: 3; /* Number of lines to display before cutting off text */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.swiper {
    width: 100%;
    height: fit-content;
    padding: 0 10px 10px 0px;
}

.swiper-slide{
    width: fit-content;
}

.history-swiper > .swiper-wrapper{
    padding: 24px 0 24px 0;
}   

Unable to properly change one variable and access it in another JS File

I’m creating a variable called current to store what button was just clicked. Then I want to use that info in another JS File when loading up a new HTML page. However, current still remains as “my_null”. I’m assuming it’s still my_null because when file2 creates the new page, the problem_type_title displays “my_null”

I expected current to change to the value that I passed in based on which button was clicked. I ordered the JS Files correctly in my HTML files when using . I know the variable is being passed through files as problem_type is “my_null” and not undefined. However, it shouldn’t be “my_null” and should be “Geometry” for example.

Here is file 1

const geo = document.getElementById('geo');
const algebra = document.getElementById('alegbra');
const centroid = document.getElementById('centroid');
const angle_bisector = document.getElementById('angle_bisector');
const two_pole = document.getElementById('two_pole');
const herons = document.getElementById('herons');
const x_intercept = document.getElementById('x_intercept');
const inverse_functions = document.getElementById('inverse_functions');
const challenge = document.getElementById('challenge');
var current = 'my_null';

geo.addEventListener('click', () => {update_curr('Geometry')});
alegbra.addEventListener('click', () => {update_curr('Alegbra')});
centroid.addEventListener('click', () => {update_curr('Centroid')});
angle_bisector.addEventListener('click', () => {update_curr('Angle Bisector')});
two_pole.addEventListener('click', () => {update_curr('Two Pole')});
herons.addEventListener('click', () => {update_curr("Heron's Formula")});
x_intercept.addEventListener('click', () => {update_curr('X-intercept')});
inverse_functions.addEventListener('click', () => {update_curr('Inverse Functions')});
challenge.addEventListener('click', () => {update_curr('Challenge Problems')});


function update_curr(clicked) {
    current = clicked;
}

Here is file 2

// Deleted code before this function for readability
async function update(url){
  // Setting value of current as a variable in this function
  let problem_type = current;
  let id = await set_problem(url);
  url = url + "challenges/" + id;
  console.log(url);
  console.log("id = " + id)
  fetch(url).then(res => res.json())
  .then(function(problem) {
      console.log(problem);
      img = problem.img;
      answer = problem.answer;
      div_main = document.createElement('div');
      div_main.innerHTML = `
        <div class='trainer_area' id='trainer_area'>
            <div class='problem_type_title'>
                // Accessing the variable
                ${problem_type}
            </div>
       // More code that doesn't matter

Activating TOAST messages via _POST / _GET (mdl)

After successful or unsuccessful execution of a PHP script, i want to display the execution result on the site in the form of a pop-up notification. How can I do this better?
Let’s say I pass the result via _GET or _POST
Is it possible to use a toast for this, something like:

if (isset $_POST['message']) {
$message = $_POST['message'];
showmessage("$message");
}

I know that in PHP there is no such thing as ShowMessage, but I’m not very strong in JS.

How to make html hover over image

Ive been trying to fix my code for ages no matter how much i hover over the hamburger menu image the cursor just woudnt change:

    <div class="header">
        <nav>
            <h1 class="nav1">CEA</h1>
            <h1 class="line"></h1>
            
        </nav>
        <nav class="nav">
            <div class="nav-left "> <!--active-->
                
                <ul>
                    <li class="nav-link"> <a class="large" href="#">About</a></li>
                    <li class="nav-link"> <a class="large" href="#">Our Work</a></li>
                    <li class="nav-link"> <a class="large" href="#">Contact</a></li>
                    <li class="nav-link"> <a class="small" href="#">Web Design</a></li>
                    <li class="nav-link"> <a class="small" href="#">eCommerce</a></li>
                    <li class="nav-link"> <a class="small" href="#">Blog</a></li>
                </ul>
                    <div class="contact">
                        <p class="large">Get in touch</p>
                        <p class="small">0302101290391</p>
                        <p class="small">[email protected]</p>
                    </div>  
            </div>
            <div class="nav-right "> <!--active-->
                
            </div>
            <img src="Imagesmenu.png" alt="menu" class="menu" style="z-index: 10;">
        </nav>

        
    </div>

my css:

.header{
    height: 110px;
}

.menu{
    display: inline;
    height: 80px;
    position: fixed;
    top: 8px;
    right: 48px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    transition: 0.5;
}

idk if my js is affectign this code but heres my js:

const menuTog = document.querySelector(".menu");
const nav = document.querySelector(".nav");
const navLeft = document.querySelector(".nav-left");
const navRight = document.querySelector(".nav-right");
const navLinks = Array.from(document.querySelectorAll(".nav-links"));
const contact = document.querySelector('.contact');
const logo = document.querySelector('.logo');

menuTog.addEventListener('click', () => {
    menuTog.classList.toggle('active');
    nav.classList.toggle('active');
    navLeft.classList.toggle('active');
    navRight.classList.toggle('active');
    logo.classList.toggle('active');

    contact.classList.remove('active');
    navRight.classList.remove('active');

    if (menuTog.classList.contains('active')) {
        setTimeout(() => {
            navRight.classList.add('active');
        }, 100)
    }
});

I already addded pointer cursor in the div but it still woudnt work. I already added the .menu:hover but it still woudnt work idk whats wrong with my code if theres someone out there that could help me than please do thank you.

Function that returns object with same keys as the input object

I attempt to write a function fn() with the following properties:

  1. Takes a single argument x which is an object with optional keys “a” and “b” (for simplicity, each field may be numeric)
  2. It outputs a new object with the same keys as provided in the input object but each field is a specific class (a->A, b->B), i.e. the desired behavior is:
  • if I call fn({a: 1, b: 1}) I receive {a: A, b: B}
  • if I call fn({b:1}) I receive {b: B} and
  • if I call fn({}) I receive {}.

You can take the numeric values in the input object as initialization values for the classes in the output object. Also, new fields “c”, “d”, “e”, … may be added later to this function.

I struggle to set this up on the type level but also in the JS code. I have written the following code which raises Typescript errors:

  • Type ‘string’ is not assignable to type ‘keyof OutputObject’.ts(2344)
  • Type ‘Partial’ is not assignable to type ‘Pick<OutputObject, K>’.ts(2322)
class A {}
class B {} 

interface InputObject {
a: number,
b: number
}

interface OutputObject {
a: A,
b: B
}

// My failed attempt at writing fn()

const fn = <
    TObj extends Partial<InputObject>,
    K extends keyof TObj
>(x: TObj): Pick<OutputObject, K> => {

    let returnValue: Partial<OutputObject> = {}

    if (x.a) {
        returnValue.a = new A()
    }

    if (x.b) {
        returnValue.b = new B()
    }

    return returnValue
}

How do I stop website from caching? Is it at all possible?

I am making a website that needs to be able to be updated about once a day or so. Whenever I update the htdocs, it doesn’t update because the website is cached into the device (which means it can take days sometimes for it to update), is there a way to stop this without server side code? If so then how? If I go into icognito mode it works fine though.

I saw a couple other questions saying to use <meta http-equiv="cache-control" content="no-cache" />, but this doesn’t seem to quite work.

Sorry if this is a dumb question… I don’t do web dev.

I have a website, and I updated it. Now it doesn’t update for a while…

How can I load external data in React SSR

I’m new to React and I’m making React SSR page. Perfectly working (it’s almost stastic page yet but use JSON datas). Why I can’t here use in my compoment Suspense why I’ve load JSON data?

import React, { Suspense, useEffect, useState } from 'react';
import './interfaces/types';

interface ProductProperties {
    [key: string]: {
        title: string;
        comments: {
            comment1: string;
            comment2: string;
            comment3: string;
            comment4: string;
            comment5: string;
        };
    };
}

interface ProductPropertyProps {
    id: string;
    rating: number;
    comment?: string;
}

const ProductProperty: React.FC<ProductPropertyProps> = ({ id, rating, comment }) => {
    const [property, setProperty] = useState<ProductProperties | null>(null);

    useEffect(() => {
        import('../../data/productProperties.json')
            .then((json) => {
                setProperty(json.default);
            })
            .catch((error) => {
                console.error("Failed to load JSON file:", error);
            });
    }, []);

    if (property === undefined) {
        return null; // Or return a loading spinner or placeholder
    }

    if (!property) {
        return null; // Or return a loading spinner or placeholder
    }

    const propertyDefinition = property[id];

    // TODO: Handle the case when the property definition is not found
    if (!propertyDefinition) {
        console.error(`No property definition found for id ${id}`);
        return null; // Or return a default value or error message
    }

    const title = propertyDefinition.title;
    // Použitie vlastného komentára ak je k dispozícii, inak použitie predvoleného z definície
    const finalComment = comment || ((propertyDefinition.comments as unknown) as { [key: string]: string })[`comment${rating}`];

    return (
        <Suspense fallback={<div>Loading...</div>}>
            <div className="product-property">
                <div className="product-property-title">{title}</div>
                <div className="product-property-rating">
                    {[...Array(5)].map((_, index) => (
                        <i key={index} className={`star star-${index < rating ? 'filled' : 'outline'}`}></i>
                    ))}
                </div>
                <div className="product-property-comment">{finalComment}</div>
            </div>
        </Suspense>
    );
}

export default ProductProperty;

But in App.tsx I can use it

// App.tsx
import React, { Suspense } from 'react';
import Product from './components/product/Product';
import productData from './data/productData.json';

const App: React.FC = () => {

  // This will be used later if we want to update the product data
  //const [productDataState, setProductData] = useState<ProductData[]>(productData);

  return (
    <>
      {productData.map((product) => (
        // Title of product must be unique and therefore can be used as key
        <Suspense key={product.title} fallback={
          <div className='product-container-fallback'>
            <div>Nahrhráva sa produkt. Prosíme chvíľu strpenia</div>
          </div>
        }>
          <button style={{ border: 'none', background: 'none', padding: 0, margin: 0 }}>
            <Product productInfo={product} />
          </button>
        </Suspense >
      ))
      }
    </>
  );
};

export default App;

It’s some possible? I know that Vite SSR has some limitations yet, but code is so nice generated…

Or…. The page it’s working but I have error in browser console:

Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.

Or

Warning: An error occurred during hydration. The server HTML was replaced with client content in .

Thanks for any advice

How do I prevent the use of mocks on certain tests but use it on others?

I have written three Jest unit tests and I am mocking a function. This mock is used for two unit tests but my third one fails since it needs to access the real code. If I comment out the mock, then the first two tests fail and third one passes. I tried using beforeAll and beforeEach methods where I disable the mock only for the third test but haven’t had any success. I’d appreciate any help!

ReactErrorBoundary.tsx:

import { render, act, fireEvent } from '@testing-library/react';
import ReactErrorBoundary from '../../components/ReactErrorBoundary';
import { ErrorBoundary } from 'react-error-boundary';
import { logger } from '../../services/logService';

jest.mock('../../services/logService', () => ({
  logger: jest.fn(),
}));

jest.mock('react-error-boundary', () => {
  const ErrorPage = require('../../components/ErrorPage').default;

  return {
    ...jest.requireActual('react-error-boundary'),
    ErrorBoundary: jest.fn(({ onError, onReset, FallbackComponent }) => {
      onError && onError(new Error());
      onReset && onReset();

      return {
        FallbackComponent: ErrorPage,
      };
    }),
  };
});

describe('ReactErrorBoundary with mocked ErrorBoundary', () => {
  beforeAll(() => {
    jest.mock('react-error-boundary', () => {
      const ErrorPage = require('../../components/ErrorPage').default;

      return {
        ...jest.requireActual('react-error-boundary'),
        ErrorBoundary: jest.fn(({ onError, onReset, FallbackComponent }) => {
          onError && onError(new Error());
          onReset && onReset();

          return {
            FallbackComponent: ErrorPage,
          };
        }),
      };
    });
  });

  test('renders ErrorBoundary with ErrorPage as FallbackComponent', () => {
    render(<ReactErrorBoundary />);
    expect(ErrorBoundary).toHaveBeenCalledWith({
        FallbackComponent: expect.any(Function),
        onError: expect.any(Function),
        onReset: expect.any(Function),
        children: undefined,
      }, {});            
  });

  test('passes children to ErrorBoundary', () => {
    const children = <div>Hello World</div>;

    render(<ReactErrorBoundary>{children}</ReactErrorBoundary>);
    expect(ErrorBoundary).toHaveBeenCalledWith({
      FallbackComponent: expect.any(Function),
      onError: expect.any(Function),
      onReset: expect.any(Function),
      children: <div>Hello World</div>,
    }, {});  
  });
});

describe('ReactErrorBoundary without mocked ErrorBoundary', () => {
  beforeAll(() => {
    jest.unmock('react-error-boundary');
  });

  test('logs error message when onError is triggered', () => {
    const spy = jest.spyOn(console, 'log').mockImplementation();

    render(
      <ReactErrorBoundary>
        <ChildComponentWithError />
      </ReactErrorBoundary>
    );

    expect(spy).toBeCalledTimes(1);
    expect(spy).toHaveBeenCalledWith('Error caught!');

    expect(logger).toBeCalledTimes(1);
    expect(logger).toHaveBeenCalledWith(expect.any(Error));

    spy.mockRestore();
  });
});

const ChildComponentWithError = () => {
  throw new Error('Test Error');
};

No response when using formidable in Next.js

What I am trying to do is upload a file from the front end to my GCP workflow, and it properly does this, however I keep encountering the API resolved without sending a response issue. I tried placing the form.parse() inside a Promise, however that also does not effectively return a response for me. The part that’s even more confusing for me is I console log the response on the front end, and it properly shows the response if it’s succesful. Below is my current code:

export const config = {
  api: {
    bodyParser: false
  }
}

export default async function handler(req, res) {
  const { query: { uuid } } = req
  const token = await getToken({ req })
  const key = JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS.toString())

  if (!token) {
    return res.status(401).json({ error: 'User must be logged in to perform this action' })
  }

  const storage = new Storage({
    projectId: process.env.PROJECT_ID,
    credentials: {
      client_email: key.client_email,
      private_key: key.private_key.replace(/\n/g, 'n')
    }
  })

  const form = formidable({
    keepExtensions: true,
  })

  form.parse(req, async (error, fields, files) => {
    if (error) {
      console.error(`Error parsing form: ${error}`);
      return res.status(500).json({ error: 'Error parsing form' });
    }

    const selectedFile = files.file[0];
    if (!selectedFile) {
      console.error('No file uploaded')
      return res.status(400).json({ error: 'No file uploaded' })
    }

    const salt = crypto.randomBytes(16).toString('hex')
    const hashedFilename = crypto.createHash('sha256').update(selectedFile.originalFilename + salt).digest('hex')

    const bucket = storage.bucket(process.env.CLOUD_STORAGE_BUCKET_NAME)
    const blob = bucket.file(hashedFilename)

    const blobStream = createReadStream(selectedFile.filepath)
      .pipe(blob.createWriteStream({
        resumable: false,
        contentType: selectedFile.mimetype
      }))

    blobStream.on('error', (error) => {
      console.error(`Error uploading files to cloud storage: ${error}`)
      cleanupStreams(blobStream, selectedFile.filepath)
      return res.status(500).json({ error: 'Error uploading files to cloud storage' })
    })

    blobStream.on('finish', async () => {
      try {
        await blob.setMetadata({
          metadata: {
            UUID: uuid,
            FILE_NAME: selectedFile.originalFilename,
            CREATION_DATE: getDate(),
          }
        })

        cleanupStreams(blobStream, selectedFile.filepath)
        return res.status(201).json({ message: `Uploaded the file successfully: ${selectedFile.newFilename}` })
      } catch (error) {
        console.error(`Error setting metadata: ${error}`)
        cleanupStreams(blobStream, selectedFile.filepath)
        return res.status(500).json({ error: 'Error setting metadata' })
      }
    })
  })

  form.on('error', (error) => {
    console.error(`Form parsing error: ${error}`)
    return res.status(500).json({ error: 'Error processing form data' })
  })
}

Javascript List, Select default Items

I am trying to modify some code to better work for my needs.

It’s a list prompt that takes a text list from Keyboard Maestro and presents it to the user. The user then clicks the options they want.

Sometimes I need certain items in the list to be ‘selected’ when the list is presented. If the text items in the list have a suffix with |0|1 at the end then the item SHOULD NOT be selected. If the text items in the list have a suffix with |1|0 then the item SHOULD be selected.

Ex.

Test One|1|0

Test Two|0|1

Only “Test One” and “Test Two” should be displayed, but the |1|0 or |0|1 will tell the script to pre-select the list item or not.

I’m just trying to figure out what specific Javascript For Loop I need to add to the function init().

Here is the just some of the code, it should be the relevant bits:

// Create a reference to KeyboardMaestro, this helps avoid unnecessary global scope pollution
var KeyboardMaestro = window.KeyboardMaestro;

// Initialize an array to keep track of indices of selected items
var selectedIndices = [];

// Initialize an array to hold the selected items themselves
var selectedItems = [];

// A flag to determine if an item is currently being dragged
var isDragging = false;

// A flag to determine if an item is being marked or selected
var marking = false;

/**
 * Toggle the selection of a given item.
 * @param {HTMLElement} item - The list item to select or unselect.
 * @param {boolean} shouldSelect - Explicit instruction to select (true) or unselect (false). If undefined, toggle.
 */
function selectItem(item, shouldSelect) {
    // Convert the NodeList of 'li' elements to an array and get the index of the provided item
    var itemIndex = Array.from(document.querySelectorAll('li')).indexOf(item);

    // Check if the item's index is already in the selectedIndices array
    var index = selectedIndices.indexOf(itemIndex);

    if (index > -1) {
        // If the item is already selected
        if (shouldSelect !== true) {
            // If the function was called with explicit instruction not to select, remove the item from selections
            selectedIndices.splice(index, 1);
            item.firstChild.checked = false; // Uncheck the checkbox associated with the item
        }
    } else {
        // If the item is not currently selected
        if (shouldSelect !== false) {
            // If the function was called without explicit instruction to unselect, add the item to selections
            selectedIndices.push(itemIndex);
            item.firstChild.checked = true; // Check the checkbox associated with the item
        }
    }
    
    // Focus on the input element of type text, likely for further user input or interactions
    document.querySelector('input[type="text"]').focus();

    // Highlight the clicked item for visual feedback
    var selectedItem = document.querySelector('li.selected');
    if (selectedItem) {
        // If an item is already highlighted, remove the 'selected' class
        selectedItem.classList.remove('selected');
    }
    // Add the 'selected' class to the current item
    item.classList.add('selected');
}

/**
 * Initializes the application, sets up the list based on the KeyboardMaestro variables, and attaches event listeners.
 */
function init() {
    // Start with no initial selected item.
    window.selectedItemStart = null;

    // Process each line from the KeyboardMaestro prompt list variable.
    var promptList = KeyboardMaestro.GetVariable('Local__Prompt List').split('n');
    for (var i = 0; i < promptList.length; i++) {
        var parts = promptList[i].split('__'); // Split each line at '__'
        
        // Create new list item and checkbox elements.
        var li = document.createElement('li');
        var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.disabled = true; // Make sure checkbox is not interactive.
        li.appendChild(checkbox);

        // Add a space after the checkbox.
        var space = document.createTextNode(' '); 
        li.appendChild(space);

        // If '__' is present in the line, use the part after for display and store the part before in a data attribute.
        // If not, use the whole line for both display and output.
        var text;
        if (parts[1]) {
            text = document.createTextNode(parts[1]);
            li.dataset.fullText = parts[0];
        } else {
            text = document.createTextNode(parts[0]);
            li.dataset.fullText = parts[0];
        }
        li.appendChild(text);

        // Add the created list item to the list.
        list.appendChild(li);
    }

    // Mark the first item in the list as selected.
    list.firstChild.classList.add('selected');
    
}

So far it looks like I need something like:

selectItem(li, true);

Any help is much appreciated.

ESlint Plugin That Enforces Function Parameter Names

I am looking for an ESlint plugin that can enforce function parameter names with a regex in javascript. e.g: ^my[A-Z].

e.g:

const doSomething = (myUserInput) => {} // Ok 

const doSomethingWrong = (userInput) => {} // Wrong, param should has a prefix "my"

I saw that typescript-eslint has an option to do it. However, my project is mainly in JS and only use eslint. https://typescript-eslint.io/rules/naming-convention/. The other option would be to write a custom elsint which would be my last resource.